diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index 439cbf8..b7ac062 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -11,6 +11,7 @@ using Febe.Core.Collection.Requests; using Febe.Core.Collection.Search; using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Library; using Febe.Core.Security; @@ -196,6 +197,7 @@ public sealed class FebeApp : IAsyncDisposable await StartWebAsync(hooks, services => { services.AddSingleton(longWork); + services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false)); services.AddSingleton(Database); services.AddSingleton(library); services.AddSingleton(Clock); @@ -220,7 +222,15 @@ public sealed class FebeApp : IAsyncDisposable var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false); var libraryRoot = o.LibraryFolderFromSettings ? settings.LibraryRoot : o.LibraryFolder; var importRoot = o.ImportFolder is { } import ? Path.GetFullPath(import) : null; - Log.Info("avvio", $"Febe {typeof(FebeApp).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(libraryRoot)}{(importRoot is null ? string.Empty : ", importazioni da " + importRoot)}, fuso {o.ZoneId}, lingua {o.Language}."); + var exportRoot = hooks.ExportMounts is { } mounts ? o.ExportRoot with { Mounts = mounts } : o.ExportRoot; + var exportState = ExportRoots.Evaluate(exportRoot); + Log.Info("avvio", $"Febe {typeof(FebeApp).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(libraryRoot)}{(importRoot is null ? string.Empty : ", importazioni da " + importRoot)}{ExportLogText(exportRoot, exportState)}, fuso {o.ZoneId}, lingua {o.Language}."); + if (exportRoot is { Root: not null, Declared: true } && !exportState.Active) + { + // Not a configuration problem: the engine starts, the copies stay off until the folder is mounted. + Log.Warn("avvio", exportState.Problem ?? ExportRoots.NotDeclaredText); + } + if (o.TestSite is not null) { Log.Warn("avvio", $"Modalità di sviluppo: il browser lavora sul sito di prova {o.TestSite.Authority}, non su Instagram."); @@ -329,6 +339,9 @@ public sealed class FebeApp : IAsyncDisposable await StartWebAsync(hooks, s => { s.AddSingleton(longWork); + s.AddSingleton(exportRoot); + s.AddSingleton(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts)); + s.AddSingleton(new RuntimeSessionState(services.Runtime)); s.AddSingleton(Database); s.AddSingleton(library); s.AddSingleton(Clock); @@ -358,6 +371,11 @@ public sealed class FebeApp : IAsyncDisposable await Web.Services.GetRequiredService().GetAsync(ct).ConfigureAwait(false); } + // Copies to external folders (spec §4.10): built now, so that a copy interrupted by the last stop is marked at once. + var exports = Web.Services.GetRequiredService(); + await exports.GetAsync(ct).ConfigureAwait(false); + LogRecoveredExports(exports.Recovered); + // Alerts (spec §13.3): from the engine's timeline and the free space of the two folders, to the shell's // notifications (the desktop's; in Docker the shell cannot notify and the channel stays silent) and Telegram. // The strip of the interface is the engine snapshot's. The library folder is read at every check: on Windows @@ -847,6 +865,25 @@ public sealed class FebeApp : IAsyncDisposable } } + private void LogRecoveredExports(int recovered) + { + if (recovered > 0) + { + Log.Info("esportazione", recovered == 1 + ? "Una copia interrotta dall'arresto precedente: si riprende dalla Dashboard, scheda Esportazione." + : $"{recovered.ToString(CultureInfo.InvariantCulture)} copie interrotte dall'arresto precedente: si riprendono dalla Dashboard, scheda Esportazione."); + } + } + + /// The part of the start-up line about the copies to external folders (Docker only). + private static string ExportLogText(ExportRootOptions root, ExportRootState state) => root.Root switch + { + null => string.Empty, + var folder when state.Active => ", copie esterne in " + folder, + var folder when !root.Declared => $", copie esterne spente ({folder} non dichiarata)", + var folder => $", copie esterne spente ({folder} non montata)", + }; + private void LogRecovered(int recovered) { if (recovered > 0) diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs index 0187a55..955bc86 100644 --- a/src/Febe.App/IFebePlatform.cs +++ b/src/Febe.App/IFebePlatform.cs @@ -1,6 +1,7 @@ using Febe.Browser.Recipes; using Febe.Core.Abstractions; using Febe.Core.Alerts; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Security; using Febe.Core.Storage; @@ -108,6 +109,12 @@ public sealed record FebeAppOptions /// Docker: the read-only root of the import sources (/importa). Null: any folder, chosen with the picker. public string? ImportFolder { get; init; } + /// + /// Where the copies to external folders may go (spec §4.10, tappa E2). Docker: the subfolders of /esporta, and only + /// when declared (--esporta) and mounted. Windows: any folder, chosen with the picker. + /// + public ExportRootOptions ExportRoot { get; init; } = ExportRootOptions.AnyFolder; + /// Time zone of the engine, of file names and (Docker) of the browser. public string ZoneId { get; init; } = "Europe/Rome"; @@ -163,4 +170,10 @@ public sealed record FebeAppHooks /// Fake free-space probe for the «Disco quasi pieno» alert. public IFreeSpaceProbe? FreeSpace { get; init; } + + /// Fake mount table for /esporta (it replaces the one of ). + public IExportMounts? ExportMounts { get; init; } + + /// Fake free space and file size limit of the export folders. + public IExportDisk? ExportDisk { get; init; } } diff --git a/src/Febe.Core/Export/ExportDestinations.cs b/src/Febe.Core/Export/ExportDestinations.cs index cb1ada1..52a8131 100644 --- a/src/Febe.Core/Export/ExportDestinations.cs +++ b/src/Febe.Core/Export/ExportDestinations.cs @@ -257,6 +257,21 @@ public sealed class ExportDestinations(ExportEnvironment env) .ToList(); } + /// + /// After a rebuild of the database (WP1.10 of tappa E2): every destination in use that now overlaps a protected + /// folder is paused with the reason. Nothing is interactive there. Returns the conflicts. + /// + public async Task> RecheckAndPauseAsync(CancellationToken ct) + { + var conflicts = await RecheckAsync(null, ct).ConfigureAwait(false); + foreach (var conflict in conflicts) + { + await ExportPause.PauseAsync(_env, conflict.Destination, conflict.Problem.Message).ConfigureAwait(false); + } + + return conflicts; + } + /// Whether a destination answers now, its pause, its copies and its free space. /// No such destination. public async Task StatusAsync(long id, CancellationToken ct) diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs index 8c89db3..ef8cc83 100644 --- a/src/Febe.Core/Export/ExportModels.cs +++ b/src/Febe.Core/Export/ExportModels.cs @@ -110,5 +110,8 @@ public sealed record ExportProgress( /// What ExportService.StartAsync did: one run per destination (D6), and the plan it followed. public sealed record ExportStart(IReadOnlyList Runs, ExportPlan Plan); +/// What «Riprova» of a paused destination did: the reason it is still paused (null: it answers), and the jobs resumed. +public sealed record ExportRetry(string? Problem, IReadOnlyList Resumed); + /// The export job ended (however it ended): the runs it worked on, and whether copies may have changed. public sealed record ExportJobFinished(IReadOnlyList RunIds, bool CopiesChanged); diff --git a/src/Febe.Core/Export/ExportRoot.cs b/src/Febe.Core/Export/ExportRoot.cs index 2f2eacd..b888dbf 100644 --- a/src/Febe.Core/Export/ExportRoot.cs +++ b/src/Febe.Core/Export/ExportRoot.cs @@ -65,6 +65,9 @@ public sealed record ExportRootOptions /// The mount table. public IExportMounts Mounts { get; init; } = new ProcMountInfo(); + /// How the page names (the demo shows «/esporta» for its temporary folder); null: as it is. + public string? ShownAs { get; init; } + /// Windows (and development): any folder. public static ExportRootOptions AnyFolder { get; } = new() { Declared = true }; @@ -202,7 +205,8 @@ public static class ExportRoots if (o.Root is { } root && ExportPaths.IsSameOrInside(full, root)) { var relative = Path.GetRelativePath(root, full); - return relative == "." ? LibraryLayout.ToStored(root) : LibraryLayout.ToStored(root).TrimEnd('/') + "/" + LibraryLayout.ToStored(relative); + var shown = o.ShownAs ?? LibraryLayout.ToStored(root); + return relative == "." ? shown : shown.TrimEnd('/') + "/" + LibraryLayout.ToStored(relative); } return full; diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs index 2ba975e..7bd09de 100644 --- a/src/Febe.Core/Export/ExportService.cs +++ b/src/Febe.Core/Export/ExportService.cs @@ -316,6 +316,41 @@ public sealed class ExportService : IAsyncDisposable StartJob([], (progress, token) => CheckJobAsync(destination, progress, token)); } + /// + /// «Riprova» of a paused destination: checks it with its probe (WP1.3). Still not writable: it stays paused with the + /// new reason, returned. Writable: the pause goes and, when no other long work runs, its paused jobs resume (oldest + /// first); otherwise they wait for «Riprendi». + /// + /// No such destination. + /// The destination was retired. + public async Task RetryDestinationAsync(long destinationId, CancellationToken ct = default) + { + var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata."); + if (destination.IsRetired) + { + throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da riprovare."); + } + + if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem) + { + await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false); + return new ExportRetry(problem, []); + } + + await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false); + var paused = (await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)) + .Where(r => r.DestinationId == destinationId && r.State == ExportRunState.Paused) + .Select(r => r.Id) + .ToList(); + if (paused.Count == 0 || IsBusy || _env.Gate?.Busy is not null) + { + return new ExportRetry(null, []); + } + + return new ExportRetry(null, await ResumeAsync(paused, ct).ConfigureAwait(false)); + } + /// The progress of the running job, or a snapshot of the newest job. public async Task GetProgressAsync(CancellationToken ct = default) { diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index 0cd89ec..59ad84c 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -216,6 +216,12 @@ public interface IExportStore /// Task> GetEntryMarksAsync(IReadOnlyList entryIds, CancellationToken ct = default); + /// + /// As , with the numbers behind the mark (the «1/3» of «Copiato in parte»): the due + /// files of each entry and how many of them are copied. Entries without due files are absent. + /// + Task> GetEntryCopyCountsAsync(IReadOnlyList entryIds, CancellationToken ct = default); + /// The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent. Task> GetFileMarksAsync(IReadOnlyList mediaIds, CancellationToken ct = default); @@ -245,6 +251,13 @@ public enum ExportMark Copied, } +/// The due files of an entry and how many are copied (decision D3 of tappa E2). +public sealed record ExportEntryCopies(int Due, int Copied) +{ + /// «Non ancora copiato» (none), «Copiato in parte», «Copiato». + public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly; +} + /// Counts of the due files of an account (decision D3 of tappa E2). /// Files that go to the account's effective destination. /// Due files «Copia in…» would copy: neither copied nor «Tolti o superati» (failed ones included). diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index 4bb1f39..0580b1e 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -1102,13 +1102,16 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun), ct); - public Task> GetEntryMarksAsync(IReadOnlyList entryIds, CancellationToken ct = default) + public async Task> GetEntryMarksAsync(IReadOnlyList entryIds, CancellationToken ct = default) => + (await GetEntryCopyCountsAsync(entryIds, ct).ConfigureAwait(false)).ToDictionary(p => p.Key, p => p.Value.Mark); + + public Task> GetEntryCopyCountsAsync(IReadOnlyList entryIds, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(entryIds); - return db.ReadAsync>( + return db.ReadAsync>( c => { - var marks = new Dictionary(); + var marks = new Dictionary(); var x = ExportFilterSql.Load(c); if (!x.HasDestination || entryIds.Count == 0) { @@ -1128,9 +1131,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore using var r = command.ExecuteReader(); while (r.Read()) { - var due = r.GetInt32(1); - var copied = r.GetInt32(2); - marks[r.GetInt64(0)] = copied == 0 ? ExportMark.None : copied >= due ? ExportMark.Copied : ExportMark.Partly; + marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2)); } } diff --git a/src/Febe.Desktop.Core/DesktopPlatform.cs b/src/Febe.Desktop.Core/DesktopPlatform.cs index a5deb82..686eb1f 100644 --- a/src/Febe.Desktop.Core/DesktopPlatform.cs +++ b/src/Febe.Desktop.Core/DesktopPlatform.cs @@ -61,6 +61,12 @@ public interface IDesktopShell /// desktop framework of .NET (no package). Tests on Linux pass AES-256-GCM with a key made at run time. /// ISessionProtector SessionProtector { get; } + + /// + /// Free space and file system of the folders of the copies (spec §4.10), network shares included; null: the + /// shared measure (drive letters only). + /// + Febe.Core.Export.IExportDisk? ExportDisk => null; } /// @@ -176,6 +182,10 @@ public sealed class DesktopPlatform : IFebePlatform services.AddSingleton(_shell.Native); services.AddSingleton(new DesktopBrowserWindow()); services.AddSingleton(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed)); + if (_shell.ExportDisk is { } disk) + { + services.AddSingleton(disk); + } } public void RegisterProblemServices(IServiceCollection services, FebeApp app) diff --git a/src/Febe.Desktop/DesktopShell.cs b/src/Febe.Desktop/DesktopShell.cs index 03c1ebb..c6a83fb 100644 --- a/src/Febe.Desktop/DesktopShell.cs +++ b/src/Febe.Desktop/DesktopShell.cs @@ -21,6 +21,8 @@ internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShel public ISessionProtector SessionProtector { get; } = new DpapiSessionProtector(); + public Febe.Core.Export.IExportDisk? ExportDisk { get; } = new Native.WindowsExportDisk(); + public string? WebView2Version() { try diff --git a/src/Febe.Desktop/Native/WindowsExportDisk.cs b/src/Febe.Desktop/Native/WindowsExportDisk.cs new file mode 100644 index 0000000..6f76465 --- /dev/null +++ b/src/Febe.Desktop/Native/WindowsExportDisk.cs @@ -0,0 +1,79 @@ +using System.Runtime.InteropServices; +using System.Text; +using Febe.Core.Export; + +namespace Febe.Desktop.Native; + +/// +/// The disks of the copies to external folders on Windows (spec §4.10 «Spazio»): free space and file system of drive +/// letters and of network shares (\\nas\foto), which does not measure. Only reads: the +/// free space for the current user (quotas included) and the name of the file system (FAT32: no file over 4 GB). +/// +internal sealed class WindowsExportDisk : IExportDisk +{ + public long? FreeBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + var folder = Path.GetFullPath(root); + return GetDiskFreeSpaceExW(EnsureTrailingSeparator(folder), out var available, out _, out _) + ? (long)Math.Min(available, long.MaxValue) + : null; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException) + { + return null; + } + } + + public long? MaxFileBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + var volume = Path.GetPathRoot(Path.GetFullPath(root)); + if (string.IsNullOrEmpty(volume)) + { + return null; + } + + var name = new StringBuilder(64); + return GetVolumeInformationW(EnsureTrailingSeparator(volume), null, 0, out _, out _, out _, name, name.Capacity) + && ExportSpace.IsFat(name.ToString()) + ? ExportSpace.Fat32Limit + : null; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException) + { + return null; + } + } + + private static string EnsureTrailingSeparator(string path) => + path.EndsWith(Path.DirectorySeparatorChar) ? path : path + Path.DirectorySeparatorChar; + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetDiskFreeSpaceExW(string directory, out ulong freeForCaller, out ulong total, out ulong free); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetVolumeInformationW( + string rootPath, + StringBuilder? volumeName, + int volumeNameSize, + out uint serialNumber, + out uint maxComponentLength, + out uint flags, + StringBuilder fileSystemName, + int fileSystemNameSize); +} diff --git a/src/Febe.Server/ServerCommand.cs b/src/Febe.Server/ServerCommand.cs index 94fdc98..64ece6b 100644 --- a/src/Febe.Server/ServerCommand.cs +++ b/src/Febe.Server/ServerCommand.cs @@ -10,12 +10,12 @@ namespace Febe.Server; internal static class ServerCommand { public const string Usage = - "Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--porta 8480] [--ascolta 0.0.0.0]\n" + "Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--esporta] [--porta 8480] [--ascolta 0.0.0.0]\n" + " [--porta-debug 9222] [--display :99] [--chromium percorso] [--senza-sandbox]\n" + " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n" + " [--raccolta pagine|richieste]\n" + "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM,\n" - + " FEBE_RACCOLTA, FEBE_CHIAVE_SESSIONE.\n" + + " FEBE_RACCOLTA, FEBE_CHIAVE_SESSIONE, FEBE_ESPORTA.\n" + "Altri comandi: --demo, --simula 30g --profilo prudente, --controllo-salute."; public static async Task RunAsync(string[] args, TextWriter output, TextWriter error) diff --git a/src/Febe.Server/ServerOptions.cs b/src/Febe.Server/ServerOptions.cs index 0f57a94..cc076d8 100644 --- a/src/Febe.Server/ServerOptions.cs +++ b/src/Febe.Server/ServerOptions.cs @@ -66,6 +66,15 @@ internal sealed record ServerOptions /// Import sources, read-only (/importa). public string ImportFolder { get; init; } = "/importa"; + /// + /// --esporta or FEBE_ESPORTA=1: the copies to external folders are switched on (spec §4.10). They are + /// written only below , and only when a folder of the server is mounted there. + /// + public bool ExportDeclared { get; init; } + + /// Root of the copies to external folders (/esporta); not on the command line, tests change it. + public string ExportFolder { get; init; } = "/esporta"; + /// FEBE_HOST: names the interface is reached with (comma separated). Empty: any name. public IReadOnlyList Hosts { get; init; } = []; @@ -125,6 +134,7 @@ internal sealed record ServerOptions LibraryFolder = LibraryFolder, LibraryFolderFromSettings = false, ImportFolder = ImportFolder, + ExportRoot = Core.Export.ExportRootOptions.Docker(Path.GetFullPath(ExportFolder), ExportDeclared), ZoneId = ZoneId, Zone = Zone, Language = Language, @@ -236,6 +246,7 @@ internal sealed record ServerOptions Hosts = SplitHosts(Env("FEBE_HOST")), TrustForwardedHost = Flag("FEBE_PROXY_FIDATO"), NoSandbox = Flag("FEBE_SENZA_SANDBOX"), + ExportDeclared = Flag("FEBE_ESPORTA"), ChromiumPath = Env("FEBE_CHROMIUM"), DebugPort = debugPort, Display = Env("FEBE_DISPLAY") ?? DefaultDisplay, @@ -305,6 +316,9 @@ internal sealed record ServerOptions case "--senza-sandbox": options = options with { NoSandbox = true }; break; + case "--esporta": + options = options with { ExportDeclared = true }; + break; case "--sito-di-prova": case "--cdn-di-prova": { @@ -400,7 +414,7 @@ internal sealed record ServerOptions var key = SessionKey is not null ? "impostata" : SessionKeyProblem is not null ? "non valida" : "assente"; return string.Create( CultureInfo.InvariantCulture, - $"ServerOptions {{ Dati = {DataFolder}, Libreria = {LibraryFolder}, Porta = {Port}, Sito = {Site.Name}, Raccolta = {CollectionRouteNames.Name(Collection)}, {ChildProcessEnvironment.PasswordVariable} = {password}, {Core.Security.SessionKey.EnvironmentVariable} = {key} }}"); + $"ServerOptions {{ Dati = {DataFolder}, Libreria = {LibraryFolder}, Porta = {Port}, Sito = {Site.Name}, Raccolta = {CollectionRouteNames.Name(Collection)}, Copie esterne = {(ExportDeclared ? "dichiarate" : "spente")}, {ChildProcessEnvironment.PasswordVariable} = {password}, {Core.Security.SessionKey.EnvironmentVariable} = {key} }}"); } /// The time zone named by TZ, or null when unknown. diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs index 41afc54..ac8d073 100644 --- a/src/Febe.Web/Api/AccountsApi.cs +++ b/src/Febe.Web/Api/AccountsApi.cs @@ -4,9 +4,11 @@ using Febe.Core.Collection.Recipes; using Febe.Core.Collection.Search; using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Web.Engine; +using Febe.Web.Export; using Febe.Web.Library; using Febe.Web.Native; using Microsoft.AspNetCore.Builder; @@ -23,8 +25,8 @@ public static class AccountsApi endpoints.MapGet("/api/accounts", async (IFebeStorage storage, IClock clock, CancellationToken ct) => ApiHttp.Json(await ListAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountListDto)); - endpoints.MapGet("/api/accounts/{id:long}", async (long id, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) => - ApiHttp.Json(await DetailAsync(id, storage, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto)); + endpoints.MapGet("/api/accounts/{id:long}", async (long id, HttpContext context, IFebeStorage storage, FebeLibrary library, ExportHub exports, IClock clock, CancellationToken ct) => + ApiHttp.Json(await DetailAsync(id, storage, library, clock, exports.RootFor(context), ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto)); endpoints.MapPost("/api/accounts/{id:long}/plan", async (long id, HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) => { @@ -35,17 +37,32 @@ public static class AccountsApi }); endpoints.MapPut("/api/accounts/{id:long}/settings", async (long id, HttpContext context, IFebeStorage storage, FebeLibrary library, FebeWebOptions options, - INativeShell shell, IBrowserWindow browser, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) => + INativeShell shell, IBrowserWindow browser, IEngineControl engine, LibraryChanges changes, ExportHub exports, IClock clock, CancellationToken ct) => { var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AccountSettingsDto).ConfigureAwait(false); var account = await GetAsync(storage, id, ct).ConfigureAwait(false); var readOnly = SystemApi.Capabilities(context, options, shell, browser, clock).FoldersReadOnly; var folder = ResolveFolder(account, body.Folder, library, readOnly); var edited = AccountSettingsMapper.Apply(account, body, clock.LocalZone, clock.Now, folder); + await RefuseExportConflictAsync(account, edited, library, exports, ct).ConfigureAwait(false); await storage.Accounts.UpdateAsync(edited, ct).ConfigureAwait(false); await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false); changes.Publish(new LibraryChange(clock.Now, id, "account")); - return ApiHttp.Json(await DetailAsync(id, storage, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto); + return ApiHttp.Json(await DetailAsync(id, storage, library, clock, exports.RootFor(context), ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto); + }); + + // «Esporta questo account» (spec §4.4, tappa E2): acts at once. Off, no copy of the account is made, not even + // with «Copia in…» (decision of 25 November 2026); the copies already made stay where they are. + endpoints.MapPost("/api/accounts/{id:long}/export-enabled", async (long id, HttpContext context, IFebeStorage storage, ExportHub exports, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.SwitchRequest).ConfigureAwait(false); + var account = await GetAsync(storage, id, ct).ConfigureAwait(false); + var service = await exports.GetAsync(ct).ConfigureAwait(false); + await service.Destinations.SetAccountEnabledAsync(id, body.Value, ct).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, id, "export")); + return ApiHttp.Message(body.Value + ? $"{ItalianText.Handle(account.Username)} si copia nelle cartelle di esportazione." + : $"{ItalianText.Handle(account.Username)} non si copia più nelle cartelle di esportazione. Le copie già fatte restano dove sono."); }); // «Tieni aggiornato» of the table: acts at once. @@ -273,7 +290,7 @@ public static class AccountsApi account.PreviousUsername); } - public static async Task DetailAsync(long id, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) + public static async Task DetailAsync(long id, IFebeStorage storage, FebeLibrary library, IClock clock, ExportRootOptions exportRoot, CancellationToken ct) { ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(library); @@ -311,7 +328,32 @@ public static class AccountsApi account.State == AccountState.ArchiveOnly && account.InstagramId is null && account.IsMine is false ? null : InstagramLinks.Profile(account.Username), highlights, AccountSettingsMapper.MaxBackfillPerDay, - (await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).ToNames()); + (await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).ToNames(), + await ExportApi.AccountAsync(storage, account, exportRoot, clock, ct).ConfigureAwait(false)); + } + + /// + /// A new folder of an account may not sit inside, or contain, a folder of the copies (spec §4.10): the change is + /// refused and nothing is saved. + /// + private static async Task RefuseExportConflictAsync(Account account, Account edited, FebeLibrary library, ExportHub exports, CancellationToken ct) + { + var before = library.Layout.AccountFolder(account); + var after = library.Layout.AccountFolder(edited); + if (string.Equals(Path.TrimEndingDirectorySeparator(before), Path.TrimEndingDirectorySeparator(after), StringComparison.Ordinal)) + { + return; + } + + var service = await exports.GetAsync(ct).ConfigureAwait(false); + // Only what the new folder adds: a destination already in conflict is paused by its own check. + var already = (await service.Destinations.RecheckAsync(null, ct).ConfigureAwait(false)).Select(c => c.Destination.Id).ToHashSet(); + var conflicts = await service.Destinations.RecheckAsync([after], ct).ConfigureAwait(false); + if (conflicts.FirstOrDefault(c => !already.Contains(c.Destination.Id)) is { } conflict) + { + throw new BadRequestException( + $"La cartella scelta per {ItalianText.Handle(edited.Username)} è dentro (o contiene) la cartella di esportazione «{ExportDestinations.Label(conflict.Destination)}»: scegline un'altra."); + } } /// «Con queste impostazioni», recomputed at every change of the form (spec §4.4). diff --git a/src/Febe.Web/Api/ApiMapping.cs b/src/Febe.Web/Api/ApiMapping.cs index f8bc906..6f9df0b 100644 --- a/src/Febe.Web/Api/ApiMapping.cs +++ b/src/Febe.Web/Api/ApiMapping.cs @@ -218,9 +218,19 @@ public static class ApiMapping _ => throw new BadRequestException("Provenienza sconosciuta."), }; + LibraryCopiesFilter? copies = query["copies"].ToString().ToLowerInvariant() switch + { + "" => null, + "notcopied" => LibraryCopiesFilter.NotCopied, + "copied" => LibraryCopiesFilter.Copied, + "removedorsuperseded" => LibraryCopiesFilter.RemovedOrSuperseded, + _ => throw new BadRequestException("Filtro delle copie sconosciuto."), + }; + var search = query["q"].ToString().Trim(); return new LibraryFilter { + Copies = copies, Kind = kind, AccountIds = accounts, From = from, diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs index 62662d9..fe62860 100644 --- a/src/Febe.Web/Api/Dtos.cs +++ b/src/Febe.Web/Api/Dtos.cs @@ -43,7 +43,9 @@ public sealed record CoverDto(long MediaId, string Kind, int? Width, int? Height /// /// A tile of the mosaic: one entry, or with «Tutte le foto» one file of it (the cover is that file and -/// its place in the series; null for an entry tile). +/// its place in the series; null for an entry tile). : the mark of the copies +/// to external folders, copied or partly (with of , the +/// «1/3»), null when nothing is copied or no destination is in use. /// public sealed record TileDto( long Id, @@ -57,7 +59,10 @@ public sealed record TileDto( string State, int Files, CoverDto? Cover, - int? Position = null); + int? Position = null, + string? Copies = null, + int? CopiesDone = null, + int? CopiesDue = null); /// A window of tiles; cursors continue it (null: nothing more that way). public sealed record LibraryPageDto(IReadOnlyList Tiles, string? Older, string? Newer); @@ -69,7 +74,7 @@ public sealed record ArrivedDto(IReadOnlyList Tiles, int Total); public sealed record DayDto(string Day, int Count, string Cursor); /// Days of the mosaic with the totals; only with «Tutte le foto» (the files of the entries). -public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList Days, int? Files = null); +public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList Days, int? Files = null, bool HasDestinations = false); public sealed record AccountBriefDto(long Id, string Username, string? DisplayName, bool IsPrivate, bool IsFollowed, bool IsMine, string State, string? Avatar); @@ -86,7 +91,8 @@ public sealed record MediaDto( string? Thumb, bool Available, string State, - bool Damaged = false); + bool Damaged = false, + IReadOnlyList? Copies = null); /// Everything the viewer shows of an entry. public sealed record EntryDto( @@ -106,7 +112,8 @@ public sealed record EntryDto( LocalTimeDto? Downloaded, IReadOnlyList Highlights, string? InstagramUrl, - IReadOnlyList Media); + IReadOnlyList Media, + bool CanCopy = false); public sealed record EntryIdsRequest(IReadOnlyList Ids, string? Mode); @@ -200,7 +207,8 @@ public sealed record AccountDetailDto( string? InstagramUrl, IReadOnlyList Highlights, int MaxBackfillPerDay, - IReadOnlyList? GeneralDownloadOrder = null); + IReadOnlyList? GeneralDownloadOrder = null, + ExportAccountDto? Export = null); public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message); diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs new file mode 100644 index 0000000..55afea9 --- /dev/null +++ b/src/Febe.Web/Api/ExportApi.cs @@ -0,0 +1,733 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Web.Export; +using Febe.Web.Library; +using Febe.Web.Native; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.WebUtilities; + +namespace Febe.Web.Api; + +/// +/// The copies to external folders (spec §4.10, §10.3, tappa E2) over : destinations and +/// their folders, «Copia in…» (plan, then start), the progress for the Dashboard tab «Esportazione», jobs, reports and +/// «Copia di nuovo». Every command passes the Origin check of the security middleware like any other. Nothing here +/// touches a file of a destination except through the service (its probe, its copies): no file is ever deleted, moved +/// or overwritten. +/// +public static class ExportApi +{ + /// Title of the native folder picker for a destination. + public const string PickTitle = "Scegli la cartella delle copie"; + + /// The most files a «Copia in…» can name one by one (a larger choice goes through the filter). + public const int MaxIds = 50_000; + + private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10); + + public static void Map(IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + + endpoints.MapGet("/api/export", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var root = hub.RootFor(context); + var d = SettingsApi.Deps.From(services); + var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock); + var state = ExportRoots.Evaluate(root); + var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); + var names = await UsernamesAsync(storage, ct).ConfigureAwait(false); + var mapped = new List(destinations.Count); + foreach (var destination in destinations) + { + var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); + mapped.Add(Destination(destination, names, counts, root, clock)); + } + + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var active = service.ActiveRunIds; + var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id)); + var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming; + return ApiHttp.Json( + new ExportOverviewDto( + new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder), + SamePost(settings.SamePost), + mapped.FirstOrDefault(x => x.Scope == "general"), + [.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)], + active, + unfinished, + new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders)), + FebeJsonContext.Default.ExportOverviewDto); + }); + + endpoints.MapPut("/api/export/settings", async (HttpContext context, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false); + var samePost = body.SamePost?.Trim().ToLowerInvariant() switch + { + "oneperaccount" => SamePostCopies.OnePerAccount, + "oneonly" => SamePostCopies.OneOnly, + _ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."), + }; + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + await (settings with { SamePost = samePost }).SaveAsync(storage.Settings, ct).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, null, "export")); + return ApiHttp.Message(samePost == SamePostCopies.OneOnly + ? "Fatto: lo stesso post in due account si copia una volta sola." + : "Fatto: lo stesso post in due account si copia una volta per ciascun account."); + }); + + endpoints.MapGet("/api/export/folders", async (string? path, HttpContext context, ExportHub hub, CancellationToken ct) => + { + await hub.GetAsync(ct).ConfigureAwait(false); + var root = hub.RootFor(context); + if (root.Root is not { } rootFolder) + { + throw new BadRequestException("Qui la cartella si sceglie con la finestra del sistema."); + } + + if (ExportRoots.Evaluate(root) is { Active: false, Problem: { } problem }) + { + throw new BadRequestException(problem); + } + + var relative = string.IsNullOrWhiteSpace(path) ? string.Empty : path.Trim().Trim('/', '\\').Replace('\\', '/'); + var folders = Guard(() => ExportRoots.Browse(root, relative.Length == 0 ? null : relative)); + string? parent = relative.Length == 0 ? null : relative.Contains('/', StringComparison.Ordinal) ? relative[..relative.LastIndexOf('/')] : string.Empty; + var full = relative.Length == 0 ? rootFolder : Path.Combine(rootFolder, LibraryLayout.ToPlatform(relative)); + return ApiHttp.Json( + new ExportFolderListDto(relative, parent, ExportRoots.DisplayPath(root, full), [.. folders.Select(f => new SourceFolderDto(f.Name, f.Path, f.HasSubfolders))]), + FebeJsonContext.Default.ExportFolderListDto); + }); + + endpoints.MapPost("/api/export/pick-folder", async (HttpContext context, ExportHub hub, IFebeStorage storage, INativeShell shell, CancellationToken ct) => + { + var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.ExportPickRequest, new ExportPickRequest(null)).ConfigureAwait(false); + if (!shell.CanPickFolder || hub.RootFor(context).Root is not null) + { + throw new BadRequestException("Qui la cartella delle copie si sceglie dall'elenco delle cartelle di /esporta."); + } + + // The picker opens on the folder of the destination being changed (from the database, never from the page). + string? initial = null; + if (body.DestinationId is { } id && await storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) is { } destination + && await ExistsAsync(destination.RootPath, ct).ConfigureAwait(false)) + { + initial = destination.RootPath; + } + + var picked = await shell.PickFolderAsync(PickTitle, initial, ct).ConfigureAwait(false); + return ApiHttp.Json(new PathDto(picked), FebeJsonContext.Default.PathDto); + }); + + endpoints.MapPost("/api/export/check-folder", async (HttpContext context, ExportHub hub, IExportDisk disk, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PathRequest).ConfigureAwait(false); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + EnsureActive(hub); + var verdict = await GuardAsync(() => service.Destinations.CheckFolderAsync(body.Path ?? string.Empty, ct)).ConfigureAwait(false); + long? free = null; + var fat = false; + if (verdict.Accepted) + { + free = await MeasureAsync(() => disk.FreeBytes(verdict.FullPath), ct).ConfigureAwait(false); + fat = await MeasureAsync(() => disk.MaxFileBytes(verdict.FullPath), ct).ConfigureAwait(false) is { } max && max <= ExportSpace.Fat32Limit; + } + + return ApiHttp.Json( + new ExportFolderCheckDto(verdict.Accepted, verdict.FullPath, Display(hub.RootFor(context), verdict.FullPath), verdict.Problem?.Message, free, fat), + FebeJsonContext.Default.ExportFolderCheckDto); + }); + + endpoints.MapPost("/api/export/naming-preview", async (HttpContext context, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportNamingPreviewRequest).ConfigureAwait(false); + var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming; + var sample = await SettingsApi.SampleAccountAsync(storage, ct).ConfigureAwait(false); + var preview = ExportNamingPreview.Build(ParseScope(body.Scope), Clean(body.General), Clean(body.Highlight), Clean(body.Profile), naming, clock.LocalZone, sample); + return ApiHttp.Json(SettingsApi.Preview(preview), FebeJsonContext.Default.NamingPreviewDto); + }); + + endpoints.MapPost("/api/export/destinations", async (HttpContext context, ExportHub hub, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportDestinationRequest).ConfigureAwait(false); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + EnsureActive(hub); + var saved = await GuardAsync(() => service.Destinations.CreateAsync(Spec(body), ct)).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, saved.Destination.AccountId, "export")); + return ApiHttp.Json(await SavedAsync(storage, saved, hub.RootFor(context), clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportDestinationSavedDto); + }); + + endpoints.MapPut("/api/export/destinations/{id:long}", async (long id, HttpContext context, ExportHub hub, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportDestinationRequest).ConfigureAwait(false); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + EnsureActive(hub); + var saved = await GuardAsync(() => service.Destinations.UpdateAsync(id, Spec(body), ct)).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, saved.Destination.AccountId, "export")); + return ApiHttp.Json(await SavedAsync(storage, saved, hub.RootFor(context), clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportDestinationSavedDto); + }); + + endpoints.MapDelete("/api/export/destinations/{id:long}", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(async () => + { + await service.Destinations.RetireAsync(id, ct).ConfigureAwait(false); + return true; + }).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, null, "export")); + return ApiHttp.Message(ExportDestinations.RetiredText); + }); + + endpoints.MapGet("/api/export/destinations/{id:long}/status", async (long id, HttpContext context, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var status = await GuardAsync(() => service.Destinations.StatusAsync(id, ct)).ConfigureAwait(false); + var names = await UsernamesAsync(storage, ct).ConfigureAwait(false); + return ApiHttp.Json( + Destination(status.Destination, names, status.Counts, hub.RootFor(context), clock, status.Reachable, status.FreeBytes, status.Problem), + FebeJsonContext.Default.ExportDestinationDto); + }); + + endpoints.MapPost("/api/export/destinations/{id:long}/resume", async (long id, ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var retry = await GuardAsync(() => service.RetryDestinationAsync(id, ct)).ConfigureAwait(false); + if (retry.Problem is { } problem) + { + throw new BadRequestException(problem); + } + + return ApiHttp.Message(retry.Resumed.Count > 0 + ? "La cartella risponde di nuovo: la copia riprende." + : "La cartella risponde di nuovo."); + }); + + endpoints.MapPost("/api/export/destinations/{id:long}/check", async (long id, ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(async () => + { + await service.CheckCopiesAsync(id, ct).ConfigureAwait(false); + return true; + }).ConfigureAwait(false); + return ApiHttp.Message("Controllo delle copie avviato: segui l'avanzamento nella Dashboard, scheda Esportazione. Nessun file viene toccato."); + }); + + endpoints.MapPost("/api/export/plan", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyJobRequestDto).ConfigureAwait(false); + var request = Request(body, clock); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var plan = await GuardAsync(() => service.PlanAsync(request, ct)).ConfigureAwait(false); + return ApiHttp.Json(Plan(plan, hub.RootFor(context)), FebeJsonContext.Default.ExportPlanDto); + }); + + endpoints.MapPost("/api/export/start", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyJobRequestDto).ConfigureAwait(false); + var request = Request(body, clock); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var start = await GuardAsync(() => service.StartAsync(request, ct)).ConfigureAwait(false); + return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); + }); + + endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyAgainRequest).ConfigureAwait(false); + var copy = await storage.Exports.GetCopyAsync(body.CopyId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa copia non è più registrata."); + if (copy.State is not (ExportCopyState.Removed or ExportCopyState.Superseded)) + { + throw new BadRequestException("Si copia di nuovo solo un file tolto dalla destinazione o superato."); + } + + if (copy.AccountId is not { } accountId) + { + throw new BadRequestException("L'account di questa copia è stato rimosso: non c'è niente da copiare di nuovo."); + } + + // The file the library has now: the one that took the place of the copied one, else the copied one itself. + var sha = copy.SupersededBySha256 ?? copy.SourceSha256; + if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c => + c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant)) + { + throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella."); + } + + var location = (await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false)) + .FirstOrDefault(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State)) + ?? throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo."); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false); + return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); + }); + + endpoints.MapGet("/api/export/progress", async (ExportHub hub, IFebeStorage storage, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var progress = await service.GetProgressAsync(ct).ConfigureAwait(false); + var error = service.LastJobError; + if (error is null && progress.RunId is { } runId && await storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) is { } run) + { + error = run.LastError; + } + + return ApiHttp.Json( + new ExportProgressDto( + progress.RunId, + Phase(progress.Phase), + progress.Fraction, + progress.FilesDone, + progress.FilesTotal, + progress.BytesDone, + progress.BytesTotal, + progress.CurrentFile, + progress.DestinationLabel, + ItemCounts(progress.ByState), + service.IsBusy, + error), + FebeJsonContext.Default.ExportProgressDto); + }); + + endpoints.MapGet("/api/export/runs", async (int? limit, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var runs = await storage.Exports.ListRecentRunsAsync(Math.Clamp(limit ?? 20, 1, 100), ct).ConfigureAwait(false); + var labels = await LabelsAsync(storage, ct).ConfigureAwait(false); + var active = service.ActiveRunIds; + var list = new List(runs.Count); + foreach (var run in runs) + { + var summary = await storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false); + list.Add(Run(run, summary, labels, clock, active.Contains(run.Id))); + } + + return ApiHttp.Json>(list, FebeJsonContext.Default.IReadOnlyListExportRunDto); + }); + + endpoints.MapPost("/api/export/interrupt", async (ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await service.InterruptAsync(ct).ConfigureAwait(false); + return ApiHttp.Message("Interrotta: quello che è stato copiato resta, e riprendi da qui quando vuoi."); + }); + + endpoints.MapPost("/api/export/runs/{id:long}/resume", async (long id, ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(() => service.ResumeAsync([id], ct)).ConfigureAwait(false); + return ApiHttp.Message("Copia ripresa: segui l'avanzamento qui."); + }); + + endpoints.MapPost("/api/export/resume", async (ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var resumed = await GuardAsync(() => service.ResumeAsync(null, ct)).ConfigureAwait(false); + return ApiHttp.Message(resumed.Count switch + { + 0 => "Non c'è nessuna copia da riprendere.", + 1 => "Copia ripresa: segui l'avanzamento qui.", + var n => $"{Core.Engine.ItalianText.Number(n)} copie riprese, una cartella alla volta: segui l'avanzamento qui.", + }); + }); + + endpoints.MapPost("/api/export/runs/{id:long}/discard", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(async () => + { + await service.DiscardAsync(id, ct).ConfigureAwait(false); + return true; + }).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, null, "export")); + return ApiHttp.Message("Annullata. I file già copiati restano dove sono."); + }); + + endpoints.MapGet("/api/export/runs/{id:long}/report", async (long id, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var report = await GuardAsync(() => service.Reports.BuildAsync(id, ct)).ConfigureAwait(false); + var labels = await LabelsAsync(storage, ct).ConfigureAwait(false); + var summary = new ExportRunSummary(report.Total, report.ByState); + return ApiHttp.Json( + new ExportReportDto( + Run(report.Run, summary, labels, clock, service.ActiveRunIds.Contains(id)), + ItemCounts(report.ByState), + report.BytesCopied, + [.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed))], + [.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]), + FebeJsonContext.Default.ExportReportDto); + }); + } + + // ---------------------------------------------------------------------------------------------- mapping + + public static string Scope(ExportScope scope) => scope == ExportScope.General ? "general" : "account"; + + public static string SamePost(SamePostCopies copies) => copies == SamePostCopies.OneOnly ? "oneOnly" : "onePerAccount"; + + /// The wire names of the content types of a destination, in the order of the dialog. + public static IReadOnlyList TypeNames(ContentTypes types) + { + var names = new List(6); + foreach (var (type, name) in TypeTable) + { + if ((types & type) != ContentTypes.None) + { + names.Add(name); + } + } + + return names; + } + + public static string CopyState(ExportCopyState state) => state switch + { + ExportCopyState.Copied => "copied", + ExportCopyState.Removed => "removed", + ExportCopyState.Superseded => "superseded", + _ => "failed", + }; + + public static string RunState(ExportRunState state) => state switch + { + ExportRunState.Running => "running", + ExportRunState.Interrupted => "interrupted", + ExportRunState.Paused => "paused", + ExportRunState.Completed => "completed", + _ => "cancelled", + }; + + public static string ItemState(ExportItemState state) => state switch + { + ExportItemState.Pending => "pending", + ExportItemState.Copied => "copied", + ExportItemState.Adopted => "adopted", + ExportItemState.AlreadyCopied => "alreadyCopied", + ExportItemState.Skipped => "skipped", + ExportItemState.Missing => "missing", + _ => "failed", + }; + + /// Copies per state with every state present. + public static IReadOnlyDictionary CopyCounts(IReadOnlyDictionary counts) + { + ArgumentNullException.ThrowIfNull(counts); + return Enum.GetValues().ToDictionary(CopyState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal); + } + + /// Files of a job per state with every state present. + public static IReadOnlyDictionary ItemCounts(IReadOnlyDictionary counts) + { + ArgumentNullException.ThrowIfNull(counts); + return Enum.GetValues().ToDictionary(ItemState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal); + } + + /// The path of a folder as shown to Alberto (relative to /esporta in Docker). + public static string Display(ExportRootOptions root, string fullPath) + { + ArgumentNullException.ThrowIfNull(root); + try + { + return string.IsNullOrWhiteSpace(fullPath) ? fullPath ?? string.Empty : ExportRoots.DisplayPath(root, fullPath); + } + catch (ArgumentException) + { + return fullPath; + } + } + + public static ExportDestinationDto Destination( + ExportDestination destination, + IReadOnlyDictionary usernames, + IReadOnlyDictionary counts, + ExportRootOptions root, + IClock clock, + bool? reachable = null, + long? freeBytes = null, + string? problem = null) + { + ArgumentNullException.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(usernames); + ArgumentNullException.ThrowIfNull(clock); + var now = clock.Now; + return new ExportDestinationDto( + destination.Id, + Scope(destination.Scope), + destination.AccountId, + destination.AccountId is { } a && usernames.TryGetValue(a, out var name) ? name : null, + ExportDestinations.Label(destination), + destination.RootPath, + Display(root, destination.RootPath), + TypeNames(destination.ContentTypes), + destination.NamingScheme, + destination.HighlightNamingScheme, + destination.ProfileNamingScheme, + destination.Automatic, + destination.PausedAt is { } paused ? ApiMapping.Local(paused, now, clock.LocalZone) : null, + problem ?? (destination.PausedAt is not null ? destination.LastError : null), + CopyCounts(counts), + reachable, + freeBytes, + destination.IsOrphan, + destination.RemovedAccountUsername); + } + + /// A destination with its counts, read from the database. + public static async Task DestinationAsync(IFebeStorage storage, ExportDestination destination, ExportRootOptions root, IClock clock, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(destination); + var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); + var names = new Dictionary(); + if (destination.AccountId is { } accountId && await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is { } account) + { + names[accountId] = account.Username; + } + + return Destination(destination, names, counts, root, clock); + } + + /// «Copie esterne» of the account card (decisions D1-D3 of tappa E2). + public static async Task AccountAsync(IFebeStorage storage, Account account, ExportRootOptions root, IClock clock, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(account); + var exports = storage.Exports; + var own = await exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false); + var destination = own ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false); + var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(account.Id, ct).ConfigureAwait(false)); + var counts = await exports.CountAccountFilesAsync(account.Id, ct).ConfigureAwait(false); + return new ExportAccountDto( + enabled, + own is not null, + destination is null ? null : await DestinationAsync(storage, destination, root, clock, ct).ConfigureAwait(false), + counts.Due, + counts.NotCopied, + counts.RemovedOrSuperseded, + counts.Failed); + } + + public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root) + { + ArgumentNullException.ThrowIfNull(plan); + return new ExportPlanDto( + plan.Files, + plan.Bytes, + plan.AlreadyCopied, + plan.RemovedOrSuperseded, + plan.NotExported, + plan.Missing, + [.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))]); + } + + /// The request of a «Copia in…»: exactly one selection. + public static ExportJobRequest Request(CopyJobRequestDto body, IClock clock) + { + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(clock); + var chosen = (body.MediaIds is { Count: > 0 } ? 1 : 0) + (body.EntryIds is { Count: > 0 } ? 1 : 0) + (body.Query is not null ? 1 : 0) + (body.AccountId is not null ? 1 : 0); + if (chosen != 1) + { + throw new BadRequestException("Scegli che cosa copiare: dei file, degli elementi, i risultati del filtro o un account."); + } + + ExportSelection selection; + if (body.MediaIds is { Count: > 0 } media) + { + selection = new ExportSelection.Media(Ids(media)); + } + else if (body.EntryIds is { Count: > 0 } entries) + { + selection = new ExportSelection.Entries(Ids(entries)); + } + else if (body.Query is { } query) + { + var parsed = new QueryCollection(QueryHelpers.ParseQuery(query)); + var mode = ApiMapping.Mode(body.Mode ?? parsed["mode"].ToString()); + selection = new ExportSelection.Filter(ApiMapping.Filter(parsed, clock.LocalZone), mode); + } + else + { + selection = new ExportSelection.Account(body.AccountId!.Value); + } + + return new ExportJobRequest(selection, body.CopyAgain); + } + + // ---------------------------------------------------------------------------------------------- helpers + + private static readonly (ContentTypes Type, string Name)[] TypeTable = + [ + (ContentTypes.PostPhotos, "postFoto"), + (ContentTypes.PostVideos, "postVideo"), + (ContentTypes.Stories, "storie"), + (ContentTypes.Highlights, "evidenza"), + (ContentTypes.Tagged, "taggati"), + (ContentTypes.ProfilePicture, "profilo"), + ]; + + private static ContentTypes ParseTypes(IReadOnlyList? names) + { + var types = ContentTypes.None; + foreach (var name in names ?? []) + { + var match = TypeTable.FirstOrDefault(t => string.Equals(t.Name, name?.Trim(), StringComparison.OrdinalIgnoreCase)); + if (match.Name is null) + { + throw new BadRequestException("Tipo di contenuto sconosciuto."); + } + + types |= match.Type; + } + + return types; + } + + private static ExportScope ParseScope(string? text) => text?.Trim().ToLowerInvariant() switch + { + "general" or "generale" => ExportScope.General, + "account" => ExportScope.Account, + _ => throw new BadRequestException("Tipo di cartella sconosciuto: generale o di un account."), + }; + + private static DestinationSpec Spec(ExportDestinationRequest body) => new( + ParseScope(body.Scope), + body.AccountId, + body.Path ?? string.Empty, + Clean(body.Label), + ParseTypes(body.Types), + Clean(body.NamingScheme), + Clean(body.HighlightNamingScheme), + Clean(body.ProfileNamingScheme), + body.Automatic, + body.OnlyNew); + + private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + + private static List Ids(IReadOnlyList ids) => + ids.Count > MaxIds ? throw new BadRequestException("Troppi file in una volta: copia con il filtro della libreria.") : [.. ids.Distinct()]; + + private static string Phase(ExportPhase phase) => phase switch + { + ExportPhase.Preparing => "preparing", + ExportPhase.Checking => "checking", + ExportPhase.WaitingForSession => "waitingForSession", + ExportPhase.Copying => "copying", + _ => "finished", + }; + + private static ExportJobDto Job(ExportStart start, ExportRootOptions root) => new( + [.. start.Runs.Select(r => r.Id)], + Plan(start.Plan, root), + start.Runs.Count == 0 + ? "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria." + : "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione."); + + private static ExportRunDto Run(ExportRun run, ExportRunSummary summary, IReadOnlyDictionary labels, IClock clock, bool running) + { + var now = clock.Now; + return new ExportRunDto( + run.Id, + run.DestinationId, + labels.TryGetValue(run.DestinationId, out var label) ? label : "Cartella tolta", + run.Kind == ExportRunKind.Recognize ? "recognize" : "copy", + run.Origin == ExportRunOrigin.Automatic ? "automatic" : "manual", + RunState(run.State), + ApiMapping.Local(run.StartedAt, now, clock.LocalZone), + run.CompletedAt is { } done ? ApiMapping.Local(done, now, clock.LocalZone) : null, + run.LastError, + summary.Total, + summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending), + running); + } + + private static async Task SavedAsync(IFebeStorage storage, DestinationSaveResult saved, ExportRootOptions root, IClock clock, CancellationToken ct) => + new(await DestinationAsync(storage, saved.Destination, root, clock, ct).ConfigureAwait(false), saved.Warnings); + + private static async Task> UsernamesAsync(IFebeStorage storage, CancellationToken ct) => + (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + + /// Names of every destination, retired ones included (old jobs keep their name). + private static async Task> LabelsAsync(IFebeStorage storage, CancellationToken ct) => + (await storage.Exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false)).ToDictionary(d => d.Id, ExportDestinations.Label); + + /// Docker with /esporta not declared or not mounted: nothing can be written (decision D14 of tappa E2). + private static void EnsureActive(ExportHub hub) + { + if (ExportRoots.Evaluate(hub.Root) is { Active: false, Problem: { } problem }) + { + throw new BadRequestException(problem); + } + } + + /// A measure of a disk that may not answer (a disconnected share): null after the timeout. + private static async Task MeasureAsync(Func measure, CancellationToken ct) + where T : struct + { + try + { + return await Task.Run(measure, ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return null; + } + } + + private static async Task ExistsAsync(string folder, CancellationToken ct) + { + try + { + return await Task.Run(() => Directory.Exists(folder), ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return false; + } + } + + // ---------------------------------------------------------------------------------------------- errors + + /// The export's own exceptions become Italian answers: 400 for a refused request, 404 for something missing. + internal static T Guard(Func action) + { + try + { + return action(); + } + catch (Exception ex) when (Translate(ex) is { } translated) + { + throw translated; + } + } + + internal static async Task GuardAsync(Func> action) + { + try + { + return await action().ConfigureAwait(false); + } + catch (Exception ex) when (Translate(ex) is { } translated) + { + throw translated; + } + } + + private static Exception? Translate(Exception ex) => ex switch + { + ExportFolderException => new BadRequestException(ex.Message, ex), + DuplicateRecordException => new BadRequestException(ex.Message, ex), + KeyNotFoundException => new NotFoundException(ex.Message, ex), + ArgumentException a => new BadRequestException(ApiErrorMiddleware.CleanMessage(a), ex), + InvalidOperationException => new BadRequestException(ex.Message, ex), + _ => null, + }; +} diff --git a/src/Febe.Web/Api/ExportDtos.cs b/src/Febe.Web/Api/ExportDtos.cs new file mode 100644 index 0000000..383ee9f --- /dev/null +++ b/src/Febe.Web/Api/ExportDtos.cs @@ -0,0 +1,219 @@ +namespace Febe.Web.Api; + +// JSON shapes of the copies to external folders (spec §4.10, tappa E2). Same conventions as Dtos.cs: English camelCase +// names, Italian texts, times as LocalTimeDto. Names of states and types on the wire: +// scope «general»|«account»; types «postFoto», «postVideo», «storie», «evidenza», «taggati», «profilo»; +// copy states «copied», «removed», «superseded», «failed»; job states «running», «interrupted», «paused», «completed», +// «cancelled»; file states «pending», «copied», «adopted», «alreadyCopied», «skipped», «missing», «failed». + +/// +/// Where copies can go. : destinations are subfolders of (the page +/// lists them); otherwise any folder, with the native picker when . +/// false: nothing can be written, says why. +/// +public sealed record ExportRootDto(bool Docker, bool Active, string? Root, string? Problem, bool PickFolder); + +/// The library's naming schemes, to prefill «Uno schema suo», and the placeholders. +public sealed record ExportSchemesDto(string General, string Highlight, string Profile, IReadOnlyList Placeholders); + +/// +/// A destination. is the folder as shown («/esporta/usb» in Docker). +/// are the wire names of the content types; null schemes are «Come la libreria». : the reason +/// of its pause (or, with /status, why it does not answer now). : copies per state +/// (copied, removed, superseded, failed). and +/// only from /status. : an own folder whose account was +/// removed («era di @»). +/// +public sealed record ExportDestinationDto( + long Id, + string Scope, + long? AccountId, + string? Username, + string Label, + string RootPath, + string Display, + IReadOnlyList Types, + string? NamingScheme, + string? HighlightNamingScheme, + string? ProfileNamingScheme, + bool Automatic, + LocalTimeDto? PausedAt, + string? Problem, + IReadOnlyDictionary Counts, + bool? Reachable = null, + long? FreeBytes = null, + bool Orphan = false, + string? FormerUsername = null); + +/// +/// GET /api/export: Impostazioni → Esportazione and the notice of the Dashboard. : +/// onePerAccount or oneOnly. : interrupted or paused jobs («Riprendi»). +/// +public sealed record ExportOverviewDto( + ExportRootDto Root, + string SamePost, + ExportDestinationDto? General, + IReadOnlyList Own, + IReadOnlyList ActiveRunIds, + int UnfinishedRuns, + ExportSchemesDto Library); + +/// PUT /api/export/settings: «Lo stesso post in due account», onePerAccount or oneOnly. +public sealed record ExportSettingsRequest(string SamePost); + +/// Docker: the subfolders of a folder of /esporta. is "" for the root. +public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList Folders); + +/// POST /api/export/pick-folder: the destination being changed, to open the picker on its folder. +public sealed record ExportPickRequest(long? DestinationId); + +/// The check of a candidate folder (before saving). : files over 4 GB cannot go there. +public sealed record ExportFolderCheckDto(bool Accepted, string FullPath, string Display, string? Problem, long? FreeBytes, bool Fat32); + +/// The «Risultato» of a destination's naming. : general or account; null schemes are the library's. +public sealed record ExportNamingPreviewRequest(string Scope, string? General, string? Highlight, string? Profile); + +/// +/// A destination to add or change. : in Docker the folder relative to /esporta (as listed), +/// elsewhere the full path. : wire names, at least one. Null or empty schemes: «Come la +/// libreria». «Automatica» is stored only (tappa E5 acts on it). +/// +public sealed record ExportDestinationRequest( + string Scope, + long? AccountId, + string Path, + string? Label, + IReadOnlyList Types, + string? NamingScheme, + string? HighlightNamingScheme, + string? ProfileNamingScheme, + bool Automatic = false, + bool OnlyNew = true); + +/// A saved destination (a change of folder gives a new id) and the warnings of its schemes. +public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList Warnings); + +/// +/// What a «Copia in…» copies: exactly one of (files of «Tutte le foto» or the viewer), +/// (a grouped selection), (the filter of the Libreria, as its query +/// string, with grouped or files) or (every file of +/// the account). : «Copia di nuovo anche i tolti o superati». +/// +public sealed record CopyJobRequestDto( + IReadOnlyList? MediaIds, + IReadOnlyList? EntryIds, + string? Query, + string? Mode, + long? AccountId, + bool CopyAgain = false); + +/// A destination of a plan. : why it cannot be written now (paused, not reachable). +public sealed record ExportPlanDestinationDto( + long Id, + string Label, + string Display, + string Scope, + string? Username, + int Files, + long Bytes, + bool Paused, + string? Problem, + long? FreeBytes); + +/// +/// The summary of «Copia in…» (spec §10.3). /: what will be written +/// (with «Copia di nuovo» the tolti/superati too). : of accounts that are not exported +/// (switch off, no destination, type not taken). : not in the library. +/// +public sealed record ExportPlanDto( + int Files, + long Bytes, + int AlreadyCopied, + int RemovedOrSuperseded, + int NotExported, + int Missing, + IReadOnlyList Destinations); + +/// The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed. +public sealed record ExportJobDto(IReadOnlyList RunIds, ExportPlanDto Plan, string Message); + +/// «Copia di nuovo» of a copy «Tolto» or «Superato» (the viewer). +public sealed record CopyAgainRequest(long CopyId); + +/// +/// GET /api/export/progress, polled by the Dashboard tab. : preparing, checking, +/// waitingForSession, copying, finished. : files of the job per state. +/// +public sealed record ExportProgressDto( + long? RunId, + string Phase, + double Fraction, + int FilesDone, + int FilesTotal, + long BytesDone, + long BytesTotal, + string? CurrentFile, + string? Destination, + IReadOnlyDictionary ByState, + bool Running, + string? Error); + +/// An export job. : copy or recognize; : manual or automatic. +public sealed record ExportRunDto( + long Id, + long DestinationId, + string Destination, + string Kind, + string Origin, + string State, + LocalTimeDto StartedAt, + LocalTimeDto? CompletedAt, + string? Error, + int Total, + int Done, + bool Running = false); + +/// The files of one account in a job ( counts written and adopted files). +public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed); + +/// A file of the report that needs a look, with its reason in Italian. +public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text); + +/// The report of a job (at most 200 problems). +public sealed record ExportReportDto( + ExportRunDto Run, + IReadOnlyDictionary ByState, + long BytesCopied, + IReadOnlyList Accounts, + IReadOnlyList Problems); + +/// +/// A copy of a file of the viewer (spec §4.6, §4.10). : copied, removed, superseded, failed; +/// : whole (tappa E2 copies originals only). : with «Una copia +/// sola», the account it was copied for when it is another one. : «Copia di nuovo». +/// +public sealed record MediaCopyDto( + long CopyId, + string Destination, + bool DestinationRetired, + string State, + string Variant, + string? Format, + long? FrameAtMs, + LocalTimeDto At, + string? ForAccount, + bool CanCopyAgain); + +/// +/// «Copie esterne» of the account card. : the effective one (its own folder, else the +/// general folder), null when there is none. Counts are of due files (decision D3 of tappa E2): with the switch off +/// they are zero. +/// +public sealed record ExportAccountDto( + bool Enabled, + bool HasOwnFolder, + ExportDestinationDto? Destination, + int Due, + int NotCopied, + int RemovedOrSuperseded, + int Failed); diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs index 636764e..afb1c94 100644 --- a/src/Febe.Web/Api/FebeJsonContext.cs +++ b/src/Febe.Web/Api/FebeJsonContext.cs @@ -88,4 +88,21 @@ namespace Febe.Web.Api; [JsonSerializable(typeof(ImportModeRequest))] [JsonSerializable(typeof(ImportPlanDto))] [JsonSerializable(typeof(ImportReportDto))] +[JsonSerializable(typeof(ExportOverviewDto))] +[JsonSerializable(typeof(ExportSettingsRequest))] +[JsonSerializable(typeof(ExportFolderListDto))] +[JsonSerializable(typeof(ExportPickRequest))] +[JsonSerializable(typeof(ExportFolderCheckDto))] +[JsonSerializable(typeof(ExportNamingPreviewRequest))] +[JsonSerializable(typeof(ExportDestinationRequest))] +[JsonSerializable(typeof(ExportDestinationSavedDto))] +[JsonSerializable(typeof(ExportDestinationDto))] +[JsonSerializable(typeof(CopyJobRequestDto))] +[JsonSerializable(typeof(ExportPlanDto))] +[JsonSerializable(typeof(ExportJobDto))] +[JsonSerializable(typeof(CopyAgainRequest))] +[JsonSerializable(typeof(ExportProgressDto))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(ExportReportDto))] +[JsonSerializable(typeof(ExportAccountDto))] public sealed partial class FebeJsonContext : JsonSerializerContext; diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs index 7eca9cb..bb0b759 100644 --- a/src/Febe.Web/Api/LibraryApi.cs +++ b/src/Febe.Web/Api/LibraryApi.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Runtime.CompilerServices; using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Web.Library; @@ -41,8 +42,9 @@ public static class LibraryApi var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone); return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0), mode)); }).ToList(); + var hasDestinations = await HasDestinationsAsync(storage, ct).ConfigureAwait(false); return ApiHttp.Json( - new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files), + new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files, hasDestinations), FebeJsonContext.Default.LibraryDaysDto); }); @@ -65,7 +67,7 @@ public static class LibraryApi ct).ConfigureAwait(false); return ApiHttp.Json( new LibraryPageDto( - page.Tiles.Select(t => Tile(t, zone)).ToList(), + await TilesAsync(storage, page.Tiles, zone, ct).ConfigureAwait(false), page.Older is { } older ? ApiMapping.Cursor(older, mode) : null, page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null), FebeJsonContext.Default.LibraryPageDto); @@ -76,7 +78,7 @@ public static class LibraryApi { var ids = ParseIds(context.Request.Query["ids"].ToString()); var tiles = await storage.Entries.GetTilesAsync(ids, ct).ConfigureAwait(false); - return ApiHttp.Json(new LibraryPageDto(tiles.Select(t => Tile(t, clock.LocalZone)).ToList(), null, null), FebeJsonContext.Default.LibraryPageDto); + return ApiHttp.Json(new LibraryPageDto(await TilesAsync(storage, tiles, clock.LocalZone, ct).ConfigureAwait(false), null, null), FebeJsonContext.Default.LibraryPageDto); }); endpoints.MapGet("/api/thumbnails/{key}", (string key, HttpContext context, FebeLibrary library) => @@ -233,6 +235,7 @@ public static class LibraryApi var local = LocalCalendar.ToLocal(entry.PublishedAt, zone); var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account))); var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false); + var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false); var media = new List(stored.Media.Count); foreach (var m in stored.Media) { @@ -259,7 +262,8 @@ public static class LibraryApi m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null, path is not null, ApiMapping.State(m.State), - damaged)); + damaged, + copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false))); } return new EntryDto( @@ -279,7 +283,149 @@ public static class LibraryApi entry.DownloadedAt is { } d ? ApiMapping.Local(d, now, zone) : null, highlights.Select(h => h.Title).ToList(), entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, entry, now, highlights.FirstOrDefault()?.InstagramId), - media); + media, + copies is { Effective: not null, Enabled: true }); + } + + /// + /// The tiles of a page with the mark of the copies to external folders (spec §4.6, tappa E2): an entry tile + /// «Copiato» or «Copiato in parte 1/3», a file tile of «Tutte le foto» «Copiato». Only due files count (decision + /// D3), and without a destination in use nothing more is asked to the database. + /// + public static async Task> TilesAsync(IFebeStorage storage, IReadOnlyList tiles, TimeZoneInfo zone, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(tiles); + var list = tiles.Select(t => Tile(t, zone)).ToList(); + if (list.Count == 0 || !await HasDestinationsAsync(storage, ct).ConfigureAwait(false)) + { + return list; + } + + var fileIds = tiles.Where(t => t.FilePosition is not null && t.CoverMediaId is not null).Select(t => t.CoverMediaId!.Value).Distinct().ToList(); + var entryIds = tiles.Where(t => t.FilePosition is null).Select(t => t.EntryId).Distinct().ToList(); + var fileMarks = fileIds.Count == 0 ? null : await storage.Exports.GetFileMarksAsync(fileIds, ct).ConfigureAwait(false); + var entryCopies = entryIds.Count == 0 ? null : await storage.Exports.GetEntryCopyCountsAsync(entryIds, ct).ConfigureAwait(false); + for (var i = 0; i < list.Count; i++) + { + var tile = tiles[i]; + if (tile.FilePosition is not null) + { + if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark) && mark == ExportMark.Copied) + { + list[i] = list[i] with { Copies = "copied" }; + } + } + else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies)) + { + list[i] = copies.Mark switch + { + ExportMark.Copied => list[i] with { Copies = "copied" }, + ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due }, + _ => list[i], + }; + } + } + + return list; + } + + /// Whether any destination of the copies is in use (the marks and the «Copie» filter make sense). + public static async Task HasDestinationsAsync(IFebeStorage storage, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + return (await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false)).Count > 0; + } + + /// + /// What the viewer needs to list the copies of the files of one entry (spec §4.6, §4.10): every destination, retired + /// ones too (an old copy keeps its name), the effective destination of the account and its switch, and «Lo stesso + /// post in due account». Null when no destination was ever added. + /// + private sealed record EntryCopiesContext( + Account Account, + IReadOnlyDictionary Destinations, + ExportDestination? Effective, + bool Enabled, + SamePostCopies SamePost, + IReadOnlyDictionary Usernames) + { + /// Copies shown for one file, newest first. + public const int MaxShown = 6; + + public static async Task LoadAsync(IFebeStorage storage, Account account, CancellationToken ct) + { + var exports = storage.Exports; + var destinations = await exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false); + if (destinations.Count == 0) + { + return null; + } + + var effective = await exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false) + ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false); + var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(account.Id, ct).ConfigureAwait(false)); + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var usernames = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + return new EntryCopiesContext(account, destinations.ToDictionary(d => d.Id), effective, enabled, settings.SamePost, usernames); + } + + public async Task> CopiesAsync(IFebeStorage storage, Media media, DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct) + { + if (media.Sha256 is not { Length: > 0 } sha) + { + return []; + } + + var present = EntryStateRules.IsPresent(media.State); + var rows = await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false); + var shown = new List(); + foreach (var copy in rows.OrderByDescending(c => c.StateChangedAt ?? c.CopiedAt).ThenByDescending(c => c.Id)) + { + if (!Destinations.TryGetValue(copy.DestinationId, out var destination)) + { + continue; + } + + // The copies made for this account; with «Una copia sola», also the ones made for another account in a + // folder still in use (that is why this file is «Già copiato»). + var own = copy.AccountId == Account.Id; + if (!own && !(SamePost == SamePostCopies.OneOnly && copy.State == ExportCopyState.Copied && !destination.IsRetired)) + { + continue; + } + + var canCopyAgain = own + && copy.State is ExportCopyState.Removed or ExportCopyState.Superseded + && present + && !destination.IsRetired + && Enabled + && Effective?.Id == destination.Id + && !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && c.Variant == copy.Variant); + shown.Add(new MediaCopyDto( + copy.Id, + ExportDestinations.Label(destination), + destination.IsRetired, + ExportApi.CopyState(copy.State), + copy.Variant switch + { + ExportVariant.Whole => "whole", + ExportVariant.Converted => "converted", + _ => "frame", + }, + copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(), + copy.FrameAt is { } frame ? (long)frame.TotalMilliseconds : null, + ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone), + own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null, + canCopyAgain)); + if (shown.Count == MaxShown) + { + break; + } + } + + return shown; + } } /// diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs index 8f38d92..14c621d 100644 --- a/src/Febe.Web/Api/SettingsApi.cs +++ b/src/Febe.Web/Api/SettingsApi.cs @@ -306,7 +306,7 @@ public static class SettingsApi } /// The account whose name the preview shows: the first one followed (or any), as in mockup 08. - private static async Task SampleAccountAsync(IFebeStorage storage, CancellationToken ct) + internal static async Task SampleAccountAsync(IFebeStorage storage, CancellationToken ct) { var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false); return accounts.Where(a => !a.IsMine && a.State is AccountState.UpToDate or AccountState.Backfilling).OrderBy(a => a.Id).Select(a => a.Username).FirstOrDefault() @@ -342,6 +342,19 @@ public static class SettingsApi throw new BadRequestException("La libreria non può stare dentro la cartella dei dati, né contenerla."); } + // Nor inside, or around, a folder of the copies (spec §4.10): only what the new root adds counts. + if (d.Services.GetService(typeof(Export.ExportHub)) is Export.ExportHub exports) + { + var destinations = (await exports.GetAsync(ct).ConfigureAwait(false)).Destinations; + var already = (await destinations.RecheckAsync(null, ct).ConfigureAwait(false)).Select(c => c.Destination.Id).ToHashSet(); + var conflicts = await destinations.RecheckAgainstAsync([new Core.Export.ProtectedFolder(root, Core.Export.ProtectedFolderKind.Library, null)], ct).ConfigureAwait(false); + if (conflicts.FirstOrDefault(c => !already.Contains(c.Destination.Id)) is { } conflict) + { + throw new BadRequestException( + $"La libreria non può stare dentro la cartella di esportazione «{Core.Export.ExportDestinations.Label(conflict.Destination)}», né contenerla: scegline un'altra."); + } + } + try { Directory.CreateDirectory(root); diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs index 2d9ed64..87555f5 100644 --- a/src/Febe.Web/Demo/DemoEngine.cs +++ b/src/Febe.Web/Demo/DemoEngine.cs @@ -374,7 +374,10 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat public bool IsSeparateWindow => Desktop; public Task PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => - Task.FromResult(Desktop ? Path.Combine(root, "altre-cartelle", Path.GetFileName(Path.TrimEndingDirectorySeparator(initialFolder ?? "cartella"))) : null); + Task.FromResult(!Desktop ? null + // The folders of the copies are checked against the demo's /esporta: an empty one there. + : string.Equals(title, Api.ExportApi.PickTitle, StringComparison.Ordinal) ? Path.Combine(root, "esporta", DemoExport.PickedFolder) + : Path.Combine(root, "altre-cartelle", Path.GetFileName(Path.TrimEndingDirectorySeparator(initialFolder ?? "cartella")))); public Task ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(Desktop); diff --git a/src/Febe.Web/Demo/DemoExport.cs b/src/Febe.Web/Demo/DemoExport.cs new file mode 100644 index 0000000..215d677 --- /dev/null +++ b/src/Febe.Web/Demo/DemoExport.cs @@ -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; + +/// +/// 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 /esporta: the counts, the marks and the «Copie» filter come from the same rows the engine wrote. +/// +public static class DemoExport +{ + /// The general folder of the demo. + public const string GeneralFolder = "Disco USB"; + + /// The own folder of @studio.lumen.demo. + public const string OwnFolder = "Studio Lumen"; + + /// The empty folder the demo's picker gives (desktop look). + public const string PickedFolder = "Chiavetta"; + + /// The account whose copies the demo shows in every state. + public const string CopiedAccount = "marta.demo"; + + /// The account with an own folder. + public const string OwnFolderAccount = "studio.lumen.demo"; + + /// The account with «Esporta questo account» off. + public const string NotExportedAccount = "il.porto.demo"; + + /// The demo's /esporta: a mounted, writable folder of the temporary root, shown as «/esporta». + public static ExportRootOptions Root(string root) + { + var folder = Path.Combine(root, "esporta"); + return ExportRootOptions.Docker(folder, declared: true, new DemoExportMounts(folder)) with { ShownAs = "/esporta" }; + } + + /// Creates the folders and the copies. A failure leaves the demo without copies, never without the demo. + 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); + } + + /// One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto». + private static async Task HistoryAsync( + FebeDatabase database, + DemoWorld world, + ExportDestination general, + Account marta, + IReadOnlyList photos, + IReadOnlyList 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); + } + } + + /// The present photos of an account, one per picture (newest first), with how many files show that picture. + private static async Task> PhotosAsync(FebeDatabase database, Account account, DemoWorld world, CancellationToken ct) + { + var seen = new Dictionary(StringComparer.Ordinal); + var ids = new List(); + 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; + } +} + +/// The demo's mount table: its /esporta is a mounted, writable ext4 folder. +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 All() => [_mount]; +} + +/// The demo's disks: 1,8 TB free, no file size limit. +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; +} diff --git a/src/Febe.Web/Demo/DemoHost.cs b/src/Febe.Web/Demo/DemoHost.cs index 62f8741..0774c2c 100644 --- a/src/Febe.Web/Demo/DemoHost.cs +++ b/src/Febe.Web/Demo/DemoHost.cs @@ -1,5 +1,6 @@ using Febe.Core.Abstractions; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Library; using Febe.Core.Storage; @@ -71,6 +72,8 @@ public sealed class DemoHost : IAsyncDisposable await database.Settings.SetAsync(SettingKeys.LibraryRoot, layout.Root, ct).ConfigureAwait(false); var world = await DemoSeeder.SeedAsync(database, data, layout, clock, ct).ConfigureAwait(false); import = await DemoImport.PrepareAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false); + await DemoExport.SeedAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false); + var exportRoot = DemoExport.Root(root); var demoImport = import; var library = new FebeLibrary(database, data, layout, clock); var web = new FebeWebOptions @@ -103,6 +106,9 @@ public sealed class DemoHost : IAsyncDisposable services.AddSingleton(); services.AddSingleton(); services.AddSingleton(demoImport); + services.AddSingleton(exportRoot); + services.AddSingleton(); + services.AddSingleton(NoEngineSession.Instance); }); await app.StartAsync(ct).ConfigureAwait(false); return new DemoHost(root, database, import, app, world, FebeWebHost.BoundAddress(app)); diff --git a/src/Febe.Web/Export/ExportHub.cs b/src/Febe.Web/Export/ExportHub.cs new file mode 100644 index 0000000..df73e1e --- /dev/null +++ b/src/Febe.Web/Export/ExportHub.cs @@ -0,0 +1,129 @@ +using Febe.Core.Abstractions; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Web.Demo; +using Febe.Web.Import; +using Febe.Web.Library; +using Microsoft.AspNetCore.Http; + +namespace Febe.Web.Export; + +/// +/// The copies to external folders of the web host (spec §4.10, tappa E2): one over the +/// library of the web host, built at the first use and never rebuilt (the library layout is read at every use, so a +/// new library folder on Windows needs nothing here). At the first use the jobs left running by the last stop become +/// «interrotto» (). When a job ends, the open pages refresh tiles and filter through the +/// libreria event. +/// +public sealed class ExportHub : IAsyncDisposable +{ + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly IFebeStorage _storage; + private readonly FebeLibrary _library; + private readonly IClock _clock; + private readonly IMediaFileResolver _files; + private readonly FebeWebOptions _options; + private readonly LongWorkGate _longWork; + private readonly IEngineSessionState _session; + private readonly IExportDisk _disk; + private readonly LibraryChanges _changes; + private readonly ImportHub _import; + private ExportService? _service; + + public ExportHub( + IFebeStorage storage, + FebeLibrary library, + IClock clock, + IMediaFileResolver files, + ExportRootOptions root, + FebeWebOptions options, + LongWorkGate longWork, + IEngineSessionState session, + IExportDisk disk, + LibraryChanges changes, + ImportHub import) + { + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _library = library ?? throw new ArgumentNullException(nameof(library)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _files = files ?? throw new ArgumentNullException(nameof(files)); + Root = root ?? throw new ArgumentNullException(nameof(root)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _longWork = longWork ?? throw new ArgumentNullException(nameof(longWork)); + _session = session ?? throw new ArgumentNullException(nameof(session)); + _disk = disk ?? throw new ArgumentNullException(nameof(disk)); + _changes = changes ?? throw new ArgumentNullException(nameof(changes)); + _import = import ?? throw new ArgumentNullException(nameof(import)); + } + + /// Where destinations may be chosen (Docker: /esporta), as the composition registered it. + public ExportRootOptions Root { get; } + + /// Jobs that the first use found running and made «interrotto» (the last stop interrupted them). + public int Recovered { get; private set; } + + /// + /// The root as a request sees it: in the demo the desktop look shows any folder (with the native picker of the + /// demo shell), the Docker look the subfolders of the demo's /esporta. Elsewhere, . + /// + public ExportRootOptions RootFor(HttpContext? context) => + _options.Demo && DemoRequest.Edition(context) != FebeEdition.Docker ? ExportRootOptions.AnyFolder : Root; + + /// The service, built at the first use (with the recovery of interrupted jobs). + public async Task GetAsync(CancellationToken ct = default) + { + if (_service is { } ready) + { + return ready; + } + + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + if (_service is null) + { + var service = new ExportService(new ExportEnvironment + { + Storage = _storage, + Layout = () => _library.Layout, + DataFolder = _library.Data.Root, + Clock = _clock, + ImportRoot = _import.SourceRoot, + Root = Root, + ResolveSource = (account, media) => _files.Resolve(account, media), + Disk = _disk, + Session = _session, + Gate = _longWork, + }); + service.JobFinished += OnJobFinished; + Recovered = await service.RecoverAsync(ct).ConfigureAwait(false); + _service = service; + } + + return _service; + } + finally + { + _gate.Release(); + } + } + + public async ValueTask DisposeAsync() + { + if (_service is { } service) + { + service.JobFinished -= OnJobFinished; + await service.DisposeAsync().ConfigureAwait(false); + } + + _gate.Dispose(); + } + + private void OnJobFinished(object? sender, ExportJobFinished finished) + { + if (finished.CopiesChanged) + { + _changes.Publish(new LibraryChange(_clock.Now, null, "export")); + } + } +} diff --git a/src/Febe.Web/FebeWeb.cs b/src/Febe.Web/FebeWeb.cs index 67a4354..013624c 100644 --- a/src/Febe.Web/FebeWeb.cs +++ b/src/Febe.Web/FebeWeb.cs @@ -2,12 +2,14 @@ using System.Net; using Febe.Core.Abstractions; using Febe.Core.Alerts; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Storage; using Febe.Web.Api; using Febe.Web.Connection; using Febe.Web.Demo; using Febe.Web.Engine; +using Febe.Web.Export; using Febe.Web.Hosting; using Febe.Web.Import; using Febe.Web.Library; @@ -80,6 +82,14 @@ public static class FebeWeb services.TryAddSingleton(sp => sp.GetService() is { } import ? new ImportHub(import, sp.GetRequiredService(), sp.GetRequiredService()) : new ImportHub(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService(), sp.GetRequiredService())); + // Copies to external folders (spec §4.10, tappa E2). Docker: only below /esporta, and only when declared and + // mounted (the composition registers the declared state); elsewhere any folder. + services.TryAddSingleton(NoEngineSession.Instance); + services.TryAddSingleton(_ => options.Edition == FebeEdition.Docker + ? ExportRootOptions.Docker(Path.GetFullPath("/esporta"), declared: false) + : ExportRootOptions.AnyFolder); + services.TryAddSingleton(sp => new SystemExportDisk(sp.GetRequiredService().Mounts)); + services.TryAddSingleton(); services.AddHttpContextAccessor(); if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password)) { @@ -141,6 +151,7 @@ public static class FebeWeb ActivityApi.Map(endpoints); SettingsApi.Map(endpoints); ImportApi.Map(endpoints); + ExportApi.Map(endpoints); DuplicatesApi.Map(endpoints); SearchApi.Map(endpoints); RemoteViewSocket.Map(endpoints); diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index b83f3b0..0e764a5 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -72,6 +72,11 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri | `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione (`Febe.App`, le due vesti): `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` | | `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop: `DesktopDataFolderChange` registra la scelta e `DataFolderMove` sposta la cartella al prossimo avvio, con copia verificata (SHA-256) | | `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (decodificatore dei fotogrammi, cartella sorgente) | +| `LongWorkGate` | Uno nuovo: importazione, copie esterne e ricostruzione non girano mai insieme | `Febe.App`: lo stesso che usa la sua `ImportService` | +| `ExportRootOptions` (Core, copie esterne §4.10) | Docker: `/esporta` **non dichiarata** (nulla si scrive); desktop: qualsiasi cartella | Server: `--esporta`/`FEBE_ESPORTA` (attiva solo se c'è un montaggio su `/esporta` o sotto); dimostrazione: la sua `esporta`, mostrata come `/esporta` (`ShownAs`) | +| `IExportDisk` (Core) | `SystemExportDisk` (spazio libero delle lettere di unità, FAT32 dal tipo del file system) | Desktop: `WindowsExportDisk` (anche le condivisioni di rete come `\\nas\foto`); prove e dimostrazione: misure fisse | +| `IEngineSessionState` (Core) | `NoEngineSession`: le copie non aspettano mai | `Febe.App`: `RuntimeSessionState` sul motore (fra una sessione e l'altra, D10) | +| `ExportHub` (`Export/`) | Costruisce l'unico `ExportService` al primo uso (e segna «interrotto» ciò che l'arresto ha fermato, `Recovered`); a lavoro finito pubblica `LibraryChange` con motivo `export` | Nessuno | - `ImportHub.LibrarySettingsChanged()` va chiamato quando cambiano cartella o schema dei nomi (lo fa già `PUT /api/settings/general`); a copia finita pubblica `LibraryChange` con motivo `import`. @@ -108,7 +113,7 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `POST /api/browser/show`, `/api/browser/used` | «Apri il browser» (desktop), uso del browser | | `GET /api/eventi` | SSE: `motore` (istantanea, al massimo ogni 300 ms, comunque ogni 60 s), `libreria` (al massimo ogni 1,5 s), commento ogni 25 s | | `GET /api/library/days?mode=grouped\|files` | Totali (sempre elementi: `entries`, `accounts`) e giorni con conteggio e cursore (per la finestra del mosaico); con `mode=files` («Tutte le foto») i giorni contano i file presenti in libreria e `files` è la loro somma (altrimenti `null`). Un altro valore di `mode` dà 400. Stessi filtri di `/api/library` | -| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 | +| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`, `copies=notCopied\|copied\|removedOrSuperseded` (solo i file dovuti; un altro valore 400). Con una cartella delle copie in uso le tessere hanno `copies` (`copied`, `partly` con `copiesDone`/`copiesDue`) e `/days` ha `hasDestinations`; il visualizzatore dà le copie di ogni file (`copies`, al più 6) e `canCopy`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 | | `GET /api/library/tiles?ids=` | Tessere per chiave | | `GET /api/thumbnails/{chiave}`, `GET /api/media/{id}/file[?download=1]` | Miniature (immutabili) e file (con range) | | `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) | @@ -134,6 +139,12 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `GET /api/import/{id}/progress`, `POST /{id}/interrupt`, `/resume` | Passi 2 e 4: avanzamento, interruzione e ripresa | | `GET /api/import/{id}/review`, `PUT /{id}/folders`, `PUT /{id}/mode`, `GET /{id}/duplicates?after=&all=`, `POST /{id}/duplicates/{pairId}`, `GET /api/import/files/{fileId}/preview` | Passo 3: contatori, cartelle → account, Copia/Sposta, doppioni con anteprime | | `POST /api/import/{id}/copy`, `GET /{id}/report`, `GET /{id}/report.csv`, `POST /{id}/discard` | Copia, resoconto, CSV (UTF-8 con BOM, `;`), abbandono di un'importazione non copiata | +| `GET /api/export`, `PUT /api/export/settings` (`{ samePost: "onePerAccount"\|"oneOnly" }`) | Copie esterne (§4.10, `Api/ExportApi.cs`): radice (`docker`, `active`, `root`, `problem`, `pickFolder`), cartella generale, cartelle proprie, lavori in corso e da riprendere (`unfinishedRuns`), schemi della libreria | +| `GET /api/export/folders?path=`, `POST /api/export/pick-folder` (`{ destinationId }`), `/check-folder` (`{ path }`), `/naming-preview` | Scelta della cartella: in Docker l'elenco sotto `/esporta` (solo se attiva; `..` è 400), sul desktop la finestra del sistema; controllo con spazio libero e FAT32; «Risultato» dei nomi | +| `POST /api/export/destinations`, `PUT/DELETE /api/export/destinations/{id}`, `GET /{id}/status`, `POST /{id}/resume`, `/{id}/check` | Cartelle: tipi `postFoto`, `postVideo`, `storie`, `evidenza`, `taggati`, `profilo`; un cambio di cartella dà un id nuovo; togliere non cancella nulla; «Riprova» (sonda, poi riprende i lavori in pausa); «Controlla le copie» | +| `POST /api/export/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId, copyAgain }`, uno solo), `POST /api/export/copy-again` (`{ copyId }`) | «Copia in…»: riepilogo, avvio (`runIds`, il piano, un messaggio), «Copia di nuovo» di un file tolto o superato | +| `GET /api/export/progress`, `GET /api/export/runs?limit=`, `POST /api/export/interrupt`, `/resume`, `/runs/{id}/resume`, `/runs/{id}/discard`, `GET /runs/{id}/report` | Scheda Esportazione della Dashboard: avanzamento, lavori, interruzione, ripresa, annullamento (i file copiati restano), resoconto (al più 200 problemi) | +| `POST /api/accounts/{id}/export-enabled` (`{ value }`) | «Esporta questo account»: spento, nessuna copia dell'account, neanche da «Copia in…». La scheda (`GET /api/accounts/{id}`) ha `export` con i conteggi dei file dovuti | | `GET /icone/tutte.svg` | Tutte le icone di `wwwroot/icone` (disegnate per Febe) in un solo sprite (``) | Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON. @@ -250,6 +261,10 @@ scrive mai nella libreria vera e non usa la rete. - Ricerca dei profili (`Demo/DemoProfileSearch.cs`): nessun browser; dopo 750 ms profili dimostrativi il cui nome contiene il testo e qualche nome inventato, con foto disegnate 300 ms dopo. Con `fermo`, `scollegato` e `alvolante` risponde `ferma`, `non-pronto` e `non-possibile`. +- Copie esterne (`Demo/DemoExport.cs`): `esporta/Disco USB` (cartella generale), `esporta/Studio Lumen` (cartella + propria di @studio.lumen.demo), `esporta/Chiavetta` (quella che dà la finestra di scelta); @il.porto.demo non si + esporta; di @marta.demo circa due terzi delle foto copiati dal motore vero (un lavoro concluso con resoconto), un file + tolto, uno superato, uno con errore e un lavoro interrotto da riprendere. In veste Docker la radice si chiama `/esporta`. - I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i conti tornino. diff --git a/src/Febe.Web/Library/DataFolderServices.cs b/src/Febe.Web/Library/DataFolderServices.cs index b89dc15..c53ad7e 100644 --- a/src/Febe.Web/Library/DataFolderServices.cs +++ b/src/Febe.Web/Library/DataFolderServices.cs @@ -159,7 +159,7 @@ public sealed class FolderSizes(IClock clock) /// one at a time, never together with an import or a copy to external folders (the shared , /// spec §4.10). It never moves, renames or deletes a file (rule 12). /// -public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes, LongWorkGate gate) +public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes, LongWorkGate gate, Export.ExportHub? exports = null) { private readonly Lock _gate = new(); private Task? _task; @@ -220,6 +220,7 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false); State = State with { Running = false, Report = report, FinishedAt = clock.Now }; changes.Publish(new LibraryChange(clock.Now, null, "rebuild")); + await RecheckExportsAsync().ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) { @@ -227,6 +228,27 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock } } + /// + /// After a rebuild the account folders may be others: a destination of the copies that now sits inside one of them, + /// or around it, is paused with the reason (spec §4.10). A failure here leaves the rebuild done. + /// + private async Task RecheckExportsAsync() + { + if (exports is null) + { + return; + } + + try + { + await (await exports.GetAsync().ConfigureAwait(false)).Destinations.RecheckAndPauseAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) + { + // Nothing is lost: every copy checks its destination again before writing (and pauses it). + } + } + /// Progress reported on the calling thread (no synchronization context to post to). private sealed class SyncProgress(Action action) : IProgress { diff --git a/tests/Febe.Tests/Web/ExportApiDemoCommandTests.cs b/tests/Febe.Tests/Web/ExportApiDemoCommandTests.cs new file mode 100644 index 0000000..dd7453b --- /dev/null +++ b/tests/Febe.Tests/Web/ExportApiDemoCommandTests.cs @@ -0,0 +1,134 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The commands of the copies to external folders over the demo (tappa E2): an own folder added with the picker and +/// taken away, the switch of an account, «Lo stesso post in due account», «Copia di nuovo» of a file «Tolto» and the +/// resume of the interrupted job. One demo for the whole sequence, which changes it. +/// +[TestClass] +public sealed class ExportApiDemoCommandTests +{ + [TestMethod] + public async Task TheCommandsChangeWhatTheCardTheFilterAndTheJobsShow() + { + using var temp = new TempFolder("demo-export-commands"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) }; + var origin = $"{demo.Address.Scheme}://{demo.Address.Authority}"; + + async Task<(HttpStatusCode Status, JsonElement Body)> SendAsync(HttpMethod method, string path, object? body = null) + { + using var request = new HttpRequestMessage(method, path); + if (body is not null) + { + request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); + } + + request.Headers.Add("Origin", origin); + using var response = await client.SendAsync(request); + var text = await response.Content.ReadAsStringAsync(); + return (response.StatusCode, text.Length == 0 ? default : JsonDocument.Parse(text).RootElement.Clone()); + } + + async Task OkAsync(HttpMethod method, string path, object? body = null) + { + var (status, answer) = await SendAsync(method, path, body); + Assert.AreEqual(HttpStatusCode.OK, status, $"{method} {path}: {answer}"); + return answer; + } + + async Task WaitIdleAsync() + { + for (var i = 0; i < 300; i++) + { + if (!(await OkAsync(HttpMethod.Get, "/api/export/progress")).Bool("running")) + { + return; + } + + await Task.Delay(100); + } + + Assert.Fail("the copy did not end"); + } + + var accounts = (await OkAsync(HttpMethod.Get, "/api/accounts")).Items("accounts").ToList(); + long Id(string username) => accounts.First(a => a.Str("username") == username).Long("id"); + var marta = Id(DemoExport.CopiedAccount); + var giulia = Id("giulia.corre.demo"); + + // An own folder for @giulia.corre.demo with the demo's picker, then taken away (the copies would stay). + var picked = (await OkAsync(HttpMethod.Post, "/api/export/pick-folder", new { })).Str("path"); + var saved = await OkAsync(HttpMethod.Post, "/api/export/destinations", new + { + scope = "account", + accountId = giulia, + path = picked, + label = (string?)null, + types = new[] { "postFoto", "storie" }, + namingScheme = (string?)null, + highlightNamingScheme = (string?)null, + profileNamingScheme = (string?)null, + }); + var destination = saved.GetProperty("destination"); + Assert.AreEqual(DemoExport.PickedFolder, destination.Str("label")); + Assert.AreEqual("giulia.corre.demo", destination.Str("username")); + Assert.IsTrue((await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Bool("hasOwnFolder")); + var status = await OkAsync(HttpMethod.Get, $"/api/export/destinations/{destination.Long("id")}/status"); + Assert.IsTrue(status.Bool("reachable"), status.ToString()); + var (twice, _) = await SendAsync(HttpMethod.Post, "/api/export/destinations", new { scope = "account", accountId = giulia, path = picked, types = new[] { "postFoto" } }); + Assert.AreEqual(HttpStatusCode.BadRequest, twice, "one own folder per account"); + Assert.Contains("restano", (await OkAsync(HttpMethod.Delete, $"/api/export/destinations/{destination.Long("id")}")).Str("message")); + Assert.IsFalse((await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Bool("hasOwnFolder")); + + // The switch of an account acts at once on its card. + await OkAsync(HttpMethod.Post, $"/api/accounts/{giulia}/export-enabled", new { value = false }); + Assert.AreEqual(0, (await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Int("due")); + await OkAsync(HttpMethod.Post, $"/api/accounts/{giulia}/export-enabled", new { value = true }); + Assert.IsGreaterThan(0, (await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Int("due")); + + // «Lo stesso post in due account». + await OkAsync(HttpMethod.Put, "/api/export/settings", new { samePost = "oneOnly" }); + Assert.AreEqual("oneOnly", (await OkAsync(HttpMethod.Get, "/api/export")).Str("samePost")); + await OkAsync(HttpMethod.Put, "/api/export/settings", new { samePost = "onePerAccount" }); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Put, "/api/export/settings", new { samePost = "tutti" })).Status); + + // «Copia di nuovo» of the file «Tolto» from the viewer: the copy is written again. + var before = (await OkAsync(HttpMethod.Get, $"/api/accounts/{marta}")).GetProperty("export"); + var tiles = (await OkAsync(HttpMethod.Get, $"/api/library?accounts={marta}&mode=files&copies=removedOrSuperseded&limit=600")).Items("tiles").ToList(); + long? removedCopy = null; + foreach (var tile in tiles) + { + var file = (await OkAsync(HttpMethod.Get, $"/api/entries/{tile.Long("id")}")).Items("media").First(m => m.Long("id") == tile.GetProperty("cover").Long("mediaId")); + if (file.Items("copies").FirstOrDefault(c => c.Str("state") == "removed" && c.Bool("canCopyAgain")) is { ValueKind: JsonValueKind.Object } copy) + { + removedCopy = copy.Long("copyId"); + break; + } + } + + Assert.IsNotNull(removedCopy, "the demo has a file «Tolto»"); + var job = await OkAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removedCopy }); + Assert.HasCount(1, job.Items("runIds").ToList()); + await WaitIdleAsync(); + var after = (await OkAsync(HttpMethod.Get, $"/api/accounts/{marta}")).GetProperty("export"); + Assert.IsLessThan(before.Int("removedOrSuperseded"), after.Int("removedOrSuperseded")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removedCopy })).Status, "a copied file is not copied again"); + + // «Riprendi» of the job left interrupted: it ends, and nothing is left to resume. + Assert.AreEqual(1, (await OkAsync(HttpMethod.Get, "/api/export")).Int("unfinishedRuns")); + await OkAsync(HttpMethod.Post, "/api/export/resume"); + await WaitIdleAsync(); + Assert.AreEqual(0, (await OkAsync(HttpMethod.Get, "/api/export")).Int("unfinishedRuns")); + var runs = (await OkAsync(HttpMethod.Get, "/api/export/runs")).EnumerateArray().ToList(); + Assert.IsFalse(runs.Any(r => r.Str("state") is "interrupted" or "running" or "paused")); + Assert.IsLessThan(after.Int("notCopied"), (await OkAsync(HttpMethod.Get, $"/api/accounts/{marta}")).GetProperty("export").Int("notCopied")); + } +} diff --git a/tests/Febe.Tests/Web/ExportApiDemoTests.cs b/tests/Febe.Tests/Web/ExportApiDemoTests.cs new file mode 100644 index 0000000..6248097 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportApiDemoTests.cs @@ -0,0 +1,253 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The copies to external folders over the API of the demo (spec §4.10, §10.6, tappa E2): destinations, the account +/// card, marks and the «Copie» filter, the viewer's copies, jobs and their report, and the folders of each look. The +/// demo's copies were written by the real engine into its temporary «esporta», so every number here comes from rows +/// and files that agree. Only reads and plans: nothing here changes the demo. +/// +[TestClass] +public sealed class ExportApiDemoTests +{ + private static TempFolder? s_temp; + private static DemoHost? s_demo; + private static HttpClient? s_client; + + private static DemoHost Demo => s_demo ?? throw new InvalidOperationException("demo not started"); + + private static HttpClient Client => s_client ?? throw new InvalidOperationException("demo not started"); + + [ClassInitialize] + public static async Task StartDemoAsync(TestContext context) + { + s_temp = new TempFolder("demo-export"); + s_demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, s_temp.Path)); + s_client = new HttpClient { BaseAddress = s_demo.Address, Timeout = TimeSpan.FromSeconds(60) }; + } + + [ClassCleanup] + public static async Task StopDemoAsync() + { + s_client?.Dispose(); + if (s_demo is not null) + { + await s_demo.DisposeAsync(); + } + + s_temp?.Dispose(); + } + + [TestMethod] + public async Task TheOverviewListsTheDemoFoldersInBothLooks() + { + var desktop = await GetAsync("/api/export"); + Assert.IsFalse(desktop.GetProperty("root").Bool("docker")); + Assert.IsTrue(desktop.GetProperty("root").Bool("active")); + Assert.IsTrue(desktop.GetProperty("root").Bool("pickFolder")); + var general = desktop.GetProperty("general"); + Assert.AreEqual("Disco USB", general.Str("label")); + Assert.AreEqual("general", general.Str("scope")); + Assert.HasCount(6, general.Items("types").ToList()); + Assert.IsGreaterThan(0, general.GetProperty("counts").Int("copied")); + Assert.AreEqual(1, general.GetProperty("counts").Int("removed")); + Assert.AreEqual(1, general.GetProperty("counts").Int("superseded")); + Assert.AreEqual(1, general.GetProperty("counts").Int("failed")); + var own = desktop.Items("own").Single(); + Assert.AreEqual("studio.lumen.demo", own.Str("username")); + Assert.AreEqual("Studio Lumen", own.Str("label")); + CollectionAssert.AreEquivalent(new[] { "postFoto", "postVideo" }, own.Items("types").Select(t => t.GetString()).ToArray()); + Assert.AreEqual(1, desktop.Int("unfinishedRuns"), "the job left interrupted by the demo"); + Assert.AreEqual("onePerAccount", desktop.Str("samePost")); + + var docker = await GetAsync("/api/export?veste=docker"); + Assert.IsTrue(docker.GetProperty("root").Bool("docker")); + Assert.IsTrue(docker.GetProperty("root").Bool("active")); + Assert.IsFalse(docker.GetProperty("root").Bool("pickFolder")); + Assert.AreEqual("/esporta", docker.GetProperty("root").Str("root")); + Assert.AreEqual("/esporta/Disco USB", docker.GetProperty("general").Str("display")); + } + + [TestMethod] + public async Task TheFoldersAreListedInDockerAndPickedOnTheDesktop() + { + var list = await GetAsync("/api/export/folders?veste=docker"); + CollectionAssert.IsSubsetOf(new[] { "Chiavetta", "Disco USB", "Studio Lumen" }, list.Items("folders").Select(f => f.Str("name")).ToArray()); + Assert.AreEqual("/esporta", list.Str("display")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/export/folders?veste=docker&path=..")).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/export/folders")).Status, "the desktop uses the picker"); + + var check = await PostAsync("/api/export/check-folder?veste=docker", new { path = "Chiavetta" }); + Assert.IsTrue(check.Bool("accepted"), check.ToString()); + Assert.AreEqual("/esporta/Chiavetta", check.Str("display")); + Assert.AreEqual(DemoExportDisk.Free, check.Long("freeBytes")); + Assert.IsFalse(check.Bool("fat32")); + var outside = await SendAsync(HttpMethod.Post, "/api/export/check-folder?veste=docker", new { path = "../fuori" }); + Assert.IsTrue(outside.Status == HttpStatusCode.BadRequest || !JsonDocument.Parse(outside.Body).RootElement.Bool("accepted"), outside.Body); + + var picked = await PostAsync("/api/export/pick-folder", new { destinationId = (long?)null }); + Assert.EndsWith("Chiavetta", picked.Str("path")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/pick-folder?veste=docker", new { })).Status); + } + + [TestMethod] + public async Task TheAccountCardCountsOnlyDueFilesAndTheSwitchOffCountsNothing() + { + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + long Id(string username) => accounts.First(a => a.Str("username") == username).Long("id"); + + var marta = (await GetAsync($"/api/accounts/{Id(DemoExport.CopiedAccount)}")).GetProperty("export"); + Assert.IsTrue(marta.Bool("enabled")); + Assert.IsFalse(marta.Bool("hasOwnFolder")); + Assert.AreEqual("Disco USB", marta.GetProperty("destination").Str("label")); + Assert.IsGreaterThan(0, marta.Int("due")); + Assert.IsGreaterThan(0, marta.Int("notCopied")); + Assert.IsLessThan(marta.Int("due"), marta.Int("notCopied"), "about two thirds are copied"); + Assert.IsGreaterThan(0, marta.Int("removedOrSuperseded")); + Assert.IsGreaterThan(0, marta.Int("failed")); + Assert.IsGreaterThan(marta.Int("notCopied") + marta.Int("removedOrSuperseded") + marta.Int("failed"), marta.Int("due"), "the rest is copied"); + + var studio = (await GetAsync($"/api/accounts/{Id(DemoExport.OwnFolderAccount)}")).GetProperty("export"); + Assert.IsTrue(studio.Bool("hasOwnFolder")); + Assert.AreEqual("Studio Lumen", studio.GetProperty("destination").Str("label")); + + var porto = (await GetAsync($"/api/accounts/{Id(DemoExport.NotExportedAccount)}")).GetProperty("export"); + Assert.IsFalse(porto.Bool("enabled")); + Assert.AreEqual(0, porto.Int("due")); + Assert.AreEqual(0, porto.Int("notCopied")); + } + + [TestMethod] + public async Task TheFilterTheMarksAndTheViewerAgree() + { + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + var marta = accounts.First(a => a.Str("username") == DemoExport.CopiedAccount).Long("id"); + + var card = (await GetAsync($"/api/accounts/{marta}")).GetProperty("export"); + var days = await GetAsync($"/api/library/days?accounts={marta}&mode=files&copies=removedOrSuperseded"); + Assert.IsTrue(days.Bool("hasDestinations")); + Assert.AreEqual(card.Int("removedOrSuperseded"), days.Int("files"), "the card and the filter count the same files"); + Assert.AreEqual(card.Int("notCopied"), (await GetAsync($"/api/library/days?accounts={marta}&mode=files&copies=notCopied")).Int("files")); + var copied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=copied&limit=600")).Items("tiles").ToList(); + Assert.IsNotEmpty(copied); + Assert.IsTrue(copied.All(t => t.Str("copies") == "copied"), "every file the filter finds copied carries the mark"); + var notCopied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=notCopied&limit=600")).Items("tiles").ToList(); + Assert.IsNotEmpty(notCopied); + Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "a file not copied has no mark"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/library?copies=tutti")).Status); + + var grouped = (await GetAsync($"/api/library?accounts={marta}&limit=600")).Items("tiles").ToList(); + foreach (var partly in grouped.Where(t => t.Str("copies") == "partly")) + { + Assert.IsLessThan(partly.Int("copiesDue"), partly.Int("copiesDone")); + Assert.IsGreaterThan(0, partly.Int("copiesDone")); + } + + // The viewer of a file «Tolto o superato»: its copy, with «Copia di nuovo». + var replaced = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=removedOrSuperseded&limit=600")).Items("tiles").ToList(); + Assert.HasCount(card.Int("removedOrSuperseded"), replaced); + var states = new HashSet(); + foreach (var tile in replaced) + { + var entry = await GetAsync($"/api/entries/{tile.Long("id")}"); + Assert.IsTrue(entry.Bool("canCopy")); + var file = entry.Items("media").First(m => m.Long("id") == tile.GetProperty("cover").Long("mediaId")); + var copy = file.Items("copies").First(c => c.Str("state") is "removed" or "superseded"); + Assert.IsTrue(copy.Bool("canCopyAgain"), copy.ToString()); + Assert.AreEqual("Disco USB", copy.Str("destination")); + Assert.AreEqual("whole", copy.Str("variant")); + states.Add(copy.Str("state")); + } + + CollectionAssert.AreEquivalent(new[] { "removed", "superseded" }, states.ToArray()); + } + + [TestMethod] + public async Task TheJobsHaveTheirReportAndThePlanSaysWhatWouldBeCopied() + { + var runs = await GetAsync("/api/export/runs"); + var list = runs.EnumerateArray().ToList(); + var completed = list.First(r => r.Str("state") == "completed" && r.Str("destination") == "Disco USB"); + Assert.IsTrue(list.Any(r => r.Str("state") == "interrupted" && r.Int("done") == 0 && r.Int("total") > 0)); + Assert.AreEqual(completed.Int("total"), completed.Int("done")); + + var report = await GetAsync($"/api/export/runs/{completed.Long("id")}/report"); + Assert.IsGreaterThan(0, report.GetProperty("byState").Int("copied")); + Assert.AreEqual(0, report.GetProperty("byState").Int("failed")); + Assert.IsGreaterThan(0L, report.Long("bytesCopied")); + Assert.AreEqual(DemoExport.CopiedAccount, report.Items("accounts").Single().Str("username")); + + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + var marta = accounts.First(a => a.Str("username") == DemoExport.CopiedAccount).Long("id"); + var card = (await GetAsync($"/api/accounts/{marta}")).GetProperty("export"); + var plan = await PostAsync("/api/export/plan", new { accountId = marta }); + // One write per picture of the account: the other files with the same picture are «Già copiato». + Assert.IsGreaterThan(0, plan.Int("files")); + Assert.IsLessThanOrEqualTo(card.Int("notCopied") + card.Int("failed"), plan.Int("files")); + Assert.IsGreaterThan(0, plan.Int("alreadyCopied")); + Assert.IsGreaterThan(0, plan.Int("removedOrSuperseded"), "skipped unless «Copia di nuovo»"); + Assert.IsLessThanOrEqualTo(card.Int("removedOrSuperseded"), plan.Int("removedOrSuperseded")); + Assert.AreEqual("Disco USB", plan.Items("destinations").Single().Str("label")); + var again = await PostAsync("/api/export/plan", new { accountId = marta, copyAgain = true }); + Assert.IsGreaterThan(plan.Int("files"), again.Int("files")); + + var porto = accounts.First(a => a.Str("username") == DemoExport.NotExportedAccount).Long("id"); + var off = await PostAsync("/api/export/plan", new { accountId = porto }); + Assert.AreEqual(0, off.Int("files")); + Assert.IsGreaterThan(0, off.Int("notExported")); + + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta, mediaIds = new[] { 1L } })).Status, "exactly one selection"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/plan", new { })).Status); + + var progress = await GetAsync("/api/export/progress"); + Assert.IsFalse(progress.Bool("running")); + } + + [TestMethod] + public async Task CommandsWithoutTheOriginOfThePageAreRefused() + { + using var request = new HttpRequestMessage(HttpMethod.Post, "/api/export/interrupt") { Content = new StringContent("{}", Encoding.UTF8, "application/json") }; + request.Headers.Add("Origin", "http://altro.example"); + using var response = await Client.SendAsync(request); + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } + + private static string Origin => $"{Demo.Address.Scheme}://{Demo.Address.Authority}"; + + private static async Task GetAsync(string path) + { + var (status, body) = await SendAsync(HttpMethod.Get, path); + Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {body}"); + return JsonDocument.Parse(body).RootElement.Clone(); + } + + private static async Task PostAsync(string path, object body) + { + var (status, text) = await SendAsync(HttpMethod.Post, path, body); + Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {text}"); + return JsonDocument.Parse(text).RootElement.Clone(); + } + + private static async Task<(HttpStatusCode Status, string Body)> SendAsync(HttpMethod method, string path, object? body = null) + { + using var request = new HttpRequestMessage(method, path); + if (body is not null) + { + request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); + } + + if (method != HttpMethod.Get) + { + request.Headers.Add("Origin", Origin); + } + + using var response = await Client.SendAsync(request); + return (response.StatusCode, await response.Content.ReadAsStringAsync()); + } +}