Interfaccia, parte 2: Attività, Impostazioni, collegamento, Importa, doppioni, primo avvio ed errori di configurazione

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 20:27:34 +00:00
1 parent 0515776b04
commit d614050ee5
90 files changed
+7825 -49

No files matched your search

+106
View File
@@ -0,0 +1,106 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Engine;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// What the Attività page needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the
/// stops, the still frame of the browser, the probable duplicates waiting for Alberto.
/// </summary>
public static class ActivityApi
{
/// <summary>Days of stops shown by the page.</summary>
public const int HistoryDays = 14;
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/engine/incidents", async (IIncidentHistory history, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await IncidentsAsync(history, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.IncidentListDto));
endpoints.MapGet("/api/browser/preview", async (IBrowserPreview preview, CancellationToken ct) =>
{
var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
var dto = frame is null
? new BrowserPreviewDto(false, null, null, null)
: new BrowserPreviewDto(true, WithoutQuery(frame.Url), frame.At.ToUnixTimeMilliseconds(), "/api/browser/preview/frame?v=" + frame.At.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture));
return ApiHttp.Json(dto, FebeJsonContext.Default.BrowserPreviewDto);
});
endpoints.MapGet("/api/browser/preview/frame", async (HttpContext context, IBrowserPreview preview, CancellationToken ct) =>
{
var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
if (frame is null)
{
throw new NotFoundException("Nessuna immagine del browser in questo momento.");
}
context.Response.Headers.CacheControl = "no-store";
return Results.Bytes(frame.Jpeg, "image/jpeg");
});
endpoints.MapGet("/api/duplicates/count", async (IFebeStorage storage, CancellationToken ct) =>
{
var download = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Download, ct).ConfigureAwait(false);
var import = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct).ConfigureAwait(false);
return ApiHttp.Json(new DuplicateCountsDto(download, import), FebeJsonContext.Default.DuplicateCountsDto);
});
}
public static async Task<IncidentListDto> IncidentsAsync(IIncidentHistory history, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(history);
ArgumentNullException.ThrowIfNull(clock);
var now = clock.Now;
var zone = clock.LocalZone;
var items = await history.ListAsync(now - TimeSpan.FromDays(HistoryDays), now + TimeSpan.FromMinutes(1), ct).ConfigureAwait(false);
var dtos = items.Select(i => new IncidentDto(
i.Id,
ApiMapping.Local(i.At, now, zone),
Level(i.Level),
Title(i.Level),
i.Signal,
WithoutQuery(i.Url),
i.StoppedUntil is { } until ? ApiMapping.Local(until, now, zone) : null,
i.ResolvedAt is { } resolved ? ApiMapping.Local(resolved, now, zone) : null,
i.IsOpen,
i.Note)).ToList();
var throttles = items.Count(i => i.Level == SignalLevel.Throttle && i.At >= now - TimeSpan.FromDays(7));
var advice = throttles >= 3
? $"{ItalianText.Count(throttles, "rallentamento", "rallentamenti")} negli ultimi sette giorni: conviene passare a un profilo più prudente o seguire meno account (Impostazioni, Limiti e comportamento)."
: null;
return new IncidentListDto(dtos, throttles, advice);
}
public static string Level(SignalLevel level) => level switch
{
SignalLevel.Throttle => "throttle",
SignalLevel.Challenge => "challenge",
_ => "disconnect",
};
public static string Title(SignalLevel level) => level switch
{
SignalLevel.Throttle => "Rallentamento",
SignalLevel.Challenge => "Verifica richiesta",
_ => "Disconnessione",
};
/// <summary>An address without its query string and fragment (signed addresses never reach the page).</summary>
public static string? WithoutQuery(string? url)
{
if (string.IsNullOrWhiteSpace(url))
{
return null;
}
var cut = url.IndexOfAny(['?', '#']);
return cut < 0 ? url : url[..cut];
}
}
+8 -1
View File
@@ -34,7 +34,7 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger<ApiErrorMid
var (status, message) = ex switch
{
BadRequestException => (StatusCodes.Status400BadRequest, ex.Message),
ArgumentException => (StatusCodes.Status400BadRequest, ex.Message),
ArgumentException a => (StatusCodes.Status400BadRequest, CleanMessage(a)),
JsonException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
@@ -53,6 +53,13 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger<ApiErrorMid
await context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
}
}
/// <summary>The Italian message of an argument error, without the « (Parameter 'x')» that .NET appends.</summary>
public static string CleanMessage(ArgumentException exception)
{
ArgumentNullException.ThrowIfNull(exception);
return exception.ParamName is { } name ? exception.Message.Replace($" (Parameter '{name}')", string.Empty, StringComparison.Ordinal) : exception.Message;
}
}
/// <summary>Small helpers of the endpoints.</summary>
+65
View File
@@ -0,0 +1,65 @@
using Febe.Core.Abstractions;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// The link to Instagram (spec §4.1, §10.3; contract in <c>Connection/PROTOCOLLO.md</c>) over <see cref="IConnectionService"/>.
/// Commands pass the Origin check of the security middleware like every other command (§13.1). Opening the login page
/// is not an engine action: Alberto uses the browser and the engine is still.
/// </summary>
public static class ConnectionApi
{
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/connection", async (IConnectionService connection, CancellationToken ct) =>
ApiHttp.Json(ToDto(await connection.GetStatusAsync(ct).ConfigureAwait(false)), FebeJsonContext.Default.ConnectionStatusDto));
endpoints.MapPost("/api/connection/begin", async (HttpContext context, IConnectionService connection, CancellationToken ct) =>
{
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false)
: new BeginDrivingRequest(false);
await connection.BeginUserDrivingAsync(body.OpenLogin, ct).ConfigureAwait(false);
return Results.NoContent();
});
// «Ho finito» counts as having used the browser: «Riprendi» after a verification becomes active (mockup 11).
endpoints.MapPost("/api/connection/finish", async (IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
{
var result = await connection.FinishAsync(ct).ConfigureAwait(false);
tracker.MarkUsed(clock.Now);
return ApiHttp.Json(new FinishDto(result.Connected, result.Message), FebeJsonContext.Default.FinishDto);
});
endpoints.MapPost("/api/connection/cancel", async (IConnectionService connection, CancellationToken ct) =>
{
await connection.CancelAsync(ct).ConfigureAwait(false);
return Results.NoContent();
});
endpoints.MapPost("/api/connection/disconnect", async (IConnectionService connection, CancellationToken ct) =>
{
await connection.DisconnectAsync(ct).ConfigureAwait(false);
return Results.NoContent();
});
}
public static ConnectionStatusDto ToDto(ConnectionStatus status)
{
ArgumentNullException.ThrowIfNull(status);
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl);
}
public static string State(ConnectionState state) => state switch
{
ConnectionState.NotConnected => "notConnected",
ConnectionState.Connected => "connected",
ConnectionState.VerificationRequired => "verificationRequired",
_ => "browserUnavailable",
};
}
+2 -1
View File
@@ -31,7 +31,8 @@ public sealed record CapabilitiesDto(
string? Scene,
IReadOnlyList<string> Scenes,
long Now,
string Today);
string Today,
IReadOnlyList<Febe.Web.Connection.ConfigurationProblem> Problems);
public sealed record PreferencesDto(string Theme);
+106
View File
@@ -0,0 +1,106 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Web.Library;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// The review of the probable duplicates found after a download (spec §9.5, §10.3): the same comparison as mockup 09
/// for pairs with origin «download». Nothing is decided in advance; a file leaves the library only on Alberto's choice
/// (rule 12).
/// </summary>
public static class DuplicatesApi
{
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/duplicates", async (long? after, FebeLibrary library, IClock clock, CancellationToken ct) =>
{
var review = library.DownloadDuplicates;
var cases = await review.ListAsync(after ?? 0, 50, ct).ConfigureAwait(false);
var pending = await review.CountPendingAsync(ct).ConfigureAwait(false);
return ApiHttp.Json(new DuplicatePageDto([.. cases.Select(c => Case(c, clock))], pending), FebeJsonContext.Default.DuplicatePageDto);
});
endpoints.MapPost("/api/duplicates/{pairId:long}", async (long pairId, HttpContext context, FebeLibrary library, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.DecideRequest).ConfigureAwait(false);
var decision = ParseDecision(body.Decision);
if (decision == DuplicateDecision.Pending)
{
throw new BadRequestException("Scegli che cosa tenere: il più grande, quello già in libreria oppure entrambi.");
}
var review = library.DownloadDuplicates;
DownloadDecisionResult result;
try
{
result = await review.DecideAsync(pairId, decision, body.ApplyToAll, ct).ConfigureAwait(false);
}
catch (KeyNotFoundException ex)
{
throw new NotFoundException(ex.Message, ex);
}
if (result.FilesRemoved > 0)
{
changes.Publish(new LibraryChange(clock.Now, null, "deleted"));
}
var pending = await review.CountPendingAsync(ct).ConfigureAwait(false);
var message = result.FilesRemoved switch
{
0 => result.Decided == 1 ? "Fatto: restano entrambi i file." : $"Fatto per {ItalianText.Count(result.Decided, "doppione", "doppioni")}.",
_ => $"Fatto: {ItalianText.Count(result.FilesRemoved, "file tolto", "file tolti")} dalla libreria (Febe ricorda la scelta e non li riscarica).",
};
if (result.Problems.Count > 0)
{
message += " Alcuni file non si sono potuti cancellare e restano sul disco.";
}
return ApiHttp.Json(new DecideDto(result.Decided, result.FilesRemoved, result.Problems, message, pending), FebeJsonContext.Default.DecideDto);
});
}
public static DuplicateCaseDto Case(DownloadDuplicateCase item, IClock clock)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentNullException.ThrowIfNull(clock);
DuplicateSideDto Side(DownloadDuplicateSide s) => new(
true,
s.MediaId,
null,
s.Username,
s.RelativePath,
ApiMapping.Media(s.Kind),
s.Width,
s.Height,
s.Bytes,
ApiMapping.Local(s.PublishedAt, clock.Now, clock.LocalZone),
s.HasThumbnail && s.Sha256 is { } sha ? "/api/thumbnails/" + sha : null);
return new DuplicateCaseDto(item.Pair.Id, Reason(item.Pair.Reason), Decision(item.Pair.Decision), Side(item.Existing), Side(item.Candidate), item.CandidateIsLarger, false);
}
public static string Reason(DuplicateReason reason) => reason == DuplicateReason.SameInstagramId ? "sameInstagramId" : "visuallySimilar";
public static string Decision(DuplicateDecision decision) => decision switch
{
DuplicateDecision.KeepLarger => "keepLarger",
DuplicateDecision.KeepExisting => "keepExisting",
DuplicateDecision.KeepBoth => "keepBoth",
_ => "pending",
};
public static DuplicateDecision ParseDecision(string? text) => text?.ToLowerInvariant() switch
{
"keeplarger" => DuplicateDecision.KeepLarger,
"keepexisting" => DuplicateDecision.KeepExisting,
"keepboth" => DuplicateDecision.KeepBoth,
"pending" => DuplicateDecision.Pending,
_ => throw new BadRequestException("Scelta sconosciuta: tieni il più grande, quello in libreria oppure entrambi."),
};
}
+37
View File
@@ -44,4 +44,41 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(LoginRequest))]
[JsonSerializable(typeof(LoginDto))]
[JsonSerializable(typeof(Library.LibraryChange))]
[JsonSerializable(typeof(ConnectionStatusDto))]
[JsonSerializable(typeof(BeginDrivingRequest))]
[JsonSerializable(typeof(FinishDto))]
[JsonSerializable(typeof(IncidentListDto))]
[JsonSerializable(typeof(BrowserPreviewDto))]
[JsonSerializable(typeof(DuplicateCountsDto))]
[JsonSerializable(typeof(GeneralSettingsDto))]
[JsonSerializable(typeof(GeneralSettingsRequest))]
[JsonSerializable(typeof(NamingRequest))]
[JsonSerializable(typeof(NamingPreviewDto))]
[JsonSerializable(typeof(PickFolderRequest))]
[JsonSerializable(typeof(PathDto))]
[JsonSerializable(typeof(PathRequest))]
[JsonSerializable(typeof(LimitsDto))]
[JsonSerializable(typeof(LimitsRequest))]
[JsonSerializable(typeof(NotificationSettingsDto))]
[JsonSerializable(typeof(NotificationSettingsRequest))]
[JsonSerializable(typeof(AlertTestRequest))]
[JsonSerializable(typeof(AlertTestDto))]
[JsonSerializable(typeof(DataSettingsDto))]
[JsonSerializable(typeof(RebuildRequest))]
[JsonSerializable(typeof(RebuildStatusDto))]
[JsonSerializable(typeof(AboutDto))]
[JsonSerializable(typeof(DuplicatePageDto))]
[JsonSerializable(typeof(DecideRequest))]
[JsonSerializable(typeof(DecideDto))]
[JsonSerializable(typeof(ImportRunDto))]
[JsonSerializable(typeof(ImportOverviewDto))]
[JsonSerializable(typeof(SourceListDto))]
[JsonSerializable(typeof(SourceInfoDto))]
[JsonSerializable(typeof(ImportStartRequest))]
[JsonSerializable(typeof(ImportProgressDto))]
[JsonSerializable(typeof(ImportReviewDto))]
[JsonSerializable(typeof(FolderTargetRequest))]
[JsonSerializable(typeof(ImportModeRequest))]
[JsonSerializable(typeof(ImportPlanDto))]
[JsonSerializable(typeof(ImportReportDto))]
public sealed partial class FebeJsonContext : JsonSerializerContext;
+426
View File
@@ -0,0 +1,426 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web.Import;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// Importa (spec §9, mockup 09) over <see cref="ImportService"/>: the four steps Sorgente, Analisi, Revisione, Copia.
/// The analysis and the copy run in the background; the page follows them with <c>/progress</c>. No file of the source
/// is touched before the copy, and «Sposta» deletes an original only after its copy was verified (spec §9.4).
/// </summary>
public static class ImportApi
{
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/import", async (HttpContext context, ImportHub hub, IClock clock, IServiceProvider services, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var runs = await service.ListRunsAsync(ct).ConfigureAwait(false);
var d = SettingsApi.Deps.From(services);
var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock);
var active = service.ActiveRunId;
return ApiHttp.Json(
new ImportOverviewDto([.. runs.Take(20).Select(r => Run(service, r, clock, active))], active, service.Sources.Root, hub.SourceRoot is null && caps.PickFolder),
FebeJsonContext.Default.ImportOverviewDto);
});
endpoints.MapGet("/api/import/sources", async (string? path, ImportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var root = service.Sources.Root ?? throw new BadRequestException("Qui la cartella si sceglie con la finestra del sistema.");
var folders = Guard(() => service.BrowseSources(path));
var relative = string.IsNullOrWhiteSpace(path) ? null : path.Trim('/', '\\');
var parent = relative is null ? null : relative.Contains('/', StringComparison.Ordinal) ? relative[..relative.LastIndexOf('/')] : string.Empty;
return ApiHttp.Json(
new SourceListDto(relative, parent, relative is null ? root : LibraryLayout.ToStored(Path.Combine(root, relative)), [.. folders.Select(f => new SourceFolderDto(f.Name, f.Path, f.HasSubfolders))]),
FebeJsonContext.Default.SourceListDto);
});
endpoints.MapPost("/api/import/pick-folder", async (ImportHub hub, INativeShell shell, CancellationToken ct) =>
{
if (hub.SourceRoot is not null || !shell.CanPickFolder)
{
throw new BadRequestException("Qui la cartella da importare si sceglie dall'elenco delle cartelle di /importa.");
}
var picked = await shell.PickFolderAsync("Cartella da importare", null, ct).ConfigureAwait(false);
return ApiHttp.Json(new PathDto(picked), FebeJsonContext.Default.PathDto);
});
endpoints.MapPost("/api/import/inspect", async (HttpContext context, ImportHub hub, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PathRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var info = Guard(() => service.InspectSource(body.Path));
return ApiHttp.Json(
new SourceInfoDto(body.Path, info.DisplayPath, info.Name, info.ReadOnly, info.CanMove, info.LooksLikeFebeLibrary, info.LooksLikeStogram, info.Folders),
FebeJsonContext.Default.SourceInfoDto);
});
endpoints.MapPost("/api/import/start", async (HttpContext context, ImportHub hub, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ImportStartRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var run = await GuardAsync(() => service.StartAsync(body.Path, new ImportAnalysisOptions { StogramHypothesis = body.Stogram }, ct)).ConfigureAwait(false);
return ApiHttp.Json(Run(service, run, clock, service.ActiveRunId), FebeJsonContext.Default.ImportRunDto);
});
endpoints.MapGet("/api/import/{id:long}/progress", async (long id, ImportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var run = await GetRunAsync(service, id, ct).ConfigureAwait(false);
var progress = await GuardAsync(() => service.GetProgressAsync(id)).ConfigureAwait(false);
return ApiHttp.Json(Progress(progress, run, service.ActiveRunId == id), FebeJsonContext.Default.ImportProgressDto);
});
endpoints.MapPost("/api/import/{id:long}/interrupt", async (long id, ImportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GetRunAsync(service, id, ct).ConfigureAwait(false);
await service.InterruptAsync(id).ConfigureAwait(false);
return ApiHttp.Message("Interrotta: quello che è stato fatto resta, e riprendi da qui quando vuoi.");
});
endpoints.MapPost("/api/import/{id:long}/resume", async (long id, ImportHub hub, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var run = await GuardAsync(() => service.ResumeAsync(id, ct)).ConfigureAwait(false);
return ApiHttp.Json(Run(service, run, clock, service.ActiveRunId), FebeJsonContext.Default.ImportRunDto);
});
endpoints.MapGet("/api/import/{id:long}/review", async (long id, ImportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
return ApiHttp.Json(await ReviewAsync(service, storage, id, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ImportReviewDto);
});
endpoints.MapPut("/api/import/{id:long}/folders", async (long id, HttpContext context, ImportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FolderTargetRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var target = body.Kind?.ToLowerInvariant() switch
{
"none" => FolderTarget.None,
"existing" => FolderTarget.Existing(body.AccountId ?? throw new BadRequestException("Scegli l'account.")),
"newarchiveaccount" => FolderTarget.NewArchiveAccount(body.Username ?? throw new BadRequestException("Scrivi il nome del nuovo account.")),
_ => throw new BadRequestException("Destinazione sconosciuta."),
};
await GuardAsync(async () =>
{
await service.SetFolderTargetAsync(id, body.Folder ?? string.Empty, target, ct).ConfigureAwait(false);
return true;
}).ConfigureAwait(false);
return ApiHttp.Json(await ReviewAsync(service, storage, id, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ImportReviewDto);
});
endpoints.MapPut("/api/import/{id:long}/mode", async (long id, HttpContext context, ImportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ImportModeRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GuardAsync(() => service.SetModeAsync(id, ParseMode(body.Mode), ct)).ConfigureAwait(false);
return ApiHttp.Json(Plan(await GuardAsync(() => service.GetPlanAsync(id, ct)).ConfigureAwait(false)), FebeJsonContext.Default.ImportPlanDto);
});
endpoints.MapGet("/api/import/{id:long}/duplicates", async (long id, long? after, bool? all, ImportHub hub, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GetRunAsync(service, id, ct).ConfigureAwait(false);
var cases = await GuardAsync(() => service.ListDuplicatesAsync(id, pendingOnly: all != true, after ?? 0, 50, ct)).ConfigureAwait(false);
var review = await GuardAsync(() => service.GetReviewAsync(id, ct)).ConfigureAwait(false);
return ApiHttp.Json(new DuplicatePageDto([.. cases.Select(c => Case(c, clock))], review.PendingDuplicates), FebeJsonContext.Default.DuplicatePageDto);
});
endpoints.MapPost("/api/import/{id:long}/duplicates/{pairId:long}", async (long id, long pairId, HttpContext context, ImportHub hub, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.DecideRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var decision = DuplicatesApi.ParseDecision(body.Decision);
int decided;
if (decision == DuplicateDecision.Pending)
{
await GuardAsync(async () =>
{
await service.Review.UndecideAsync(id, pairId, ct).ConfigureAwait(false);
return true;
}).ConfigureAwait(false);
decided = 1;
}
else
{
decided = await GuardAsync(() => service.DecideAsync(id, pairId, decision, body.ApplyToAll ? DecisionScope.AllPending : DecisionScope.ThisPair, ct)).ConfigureAwait(false);
}
var review = await GuardAsync(() => service.GetReviewAsync(id, ct)).ConfigureAwait(false);
var message = decided == 1 ? "Scelta registrata: vale quando importi." : $"Scelta registrata per {ItalianTextCount(decided)}: vale quando importi.";
return ApiHttp.Json(new DecideDto(decided, 0, [], message, review.PendingDuplicates), FebeJsonContext.Default.DecideDto);
});
endpoints.MapGet("/api/import/files/{fileId:long}/preview", async (long fileId, HttpContext context, ImportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var jpeg = await GuardAsync(() => service.Review.RenderPreviewAsync(fileId, 640, ct)).ConfigureAwait(false)
?? throw new NotFoundException("Anteprima non disponibile per questo file.");
context.Response.Headers.CacheControl = "private, max-age=600";
return Results.Bytes(jpeg, "image/jpeg");
});
endpoints.MapPost("/api/import/{id:long}/copy", async (long id, HttpContext context, ImportHub hub, IClock clock, CancellationToken ct) =>
{
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ImportModeRequest).ConfigureAwait(false)
: null;
var service = await hub.GetAsync(ct).ConfigureAwait(false);
ImportMode? mode = body?.Mode is { Length: > 0 } m ? ParseMode(m) : null;
var run = await GuardAsync(() => service.StartCopyAsync(id, mode, ct)).ConfigureAwait(false);
return ApiHttp.Json(Run(service, run, clock, service.ActiveRunId), FebeJsonContext.Default.ImportRunDto);
});
endpoints.MapGet("/api/import/{id:long}/report", async (long id, ImportHub hub, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var report = await GuardAsync(() => service.GetReportAsync(id, ct)).ConfigureAwait(false);
return ApiHttp.Json(Report(service, report, clock), FebeJsonContext.Default.ImportReportDto);
});
endpoints.MapGet("/api/import/{id:long}/report.csv", async (long id, HttpContext context, ImportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var run = await GetRunAsync(service, id, ct).ConfigureAwait(false);
var name = service.Reports.CsvFileName(run);
context.Response.ContentType = "text/csv; charset=utf-8";
context.Response.Headers.ContentDisposition = $"attachment; filename=\"{name}\"";
context.Response.Headers.CacheControl = "no-store";
await service.WriteCsvAsync(id, context.Response.Body, ct).ConfigureAwait(false);
});
endpoints.MapPost("/api/import/{id:long}/discard", async (long id, ImportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GetRunAsync(service, id, ct).ConfigureAwait(false);
await service.DiscardAsync(id, ct).ConfigureAwait(false);
return ApiHttp.Message("Importazione annullata: nessun file della sorgente è stato toccato.");
});
}
// ---------------------------------------------------------------------------------------------- mapping
public static ImportRunDto Run(ImportService service, ImportRun run, IClock clock, long? active)
{
ArgumentNullException.ThrowIfNull(service);
ArgumentNullException.ThrowIfNull(run);
ArgumentNullException.ThrowIfNull(clock);
return new ImportRunDto(
run.Id,
run.SourcePath,
service.Sources.DisplayPath(run.SourcePath),
State(run.State),
run.Mode == ImportMode.Move ? "move" : "copy",
run.SourceReadOnly,
ApiMapping.Local(run.StartedAt, clock.Now, clock.LocalZone),
run.CompletedAt is { } done ? ApiMapping.Local(done, clock.Now, clock.LocalZone) : null,
run.LastError,
active == run.Id);
}
public static string State(ImportRunState state) => state switch
{
ImportRunState.Analyzing => "analyzing",
ImportRunState.AnalysisInterrupted => "analysisInterrupted",
ImportRunState.Reviewing => "reviewing",
ImportRunState.Copying => "copying",
ImportRunState.CopyInterrupted => "copyInterrupted",
ImportRunState.Completed => "completed",
_ => "cancelled",
};
public static OutcomeCountsDto Outcomes(IReadOnlyDictionary<ImportOutcome, int> counts)
{
ArgumentNullException.ThrowIfNull(counts);
int Of(ImportOutcome o) => counts.TryGetValue(o, out var n) ? n : 0;
return new OutcomeCountsDto(Of(ImportOutcome.New), Of(ImportOutcome.AlreadyInLibrary), Of(ImportOutcome.ProbableDuplicate), Of(ImportOutcome.Unrecognized), Of(ImportOutcome.IdenticalInSource));
}
public static ImportProgressDto Progress(ImportProgress progress, ImportRun run, bool running)
{
ArgumentNullException.ThrowIfNull(progress);
ArgumentNullException.ThrowIfNull(run);
var phase = progress.Phase switch
{
ImportPhase.Listing => "listing",
ImportPhase.Analyzing => "analyzing",
ImportPhase.Copying => "copying",
_ => "finished",
};
return new ImportProgressDto(
progress.RunId,
phase,
State(run.State),
running,
progress.FilesDone,
progress.FilesTotal,
progress.BytesDone,
progress.BytesTotal,
progress.Fraction,
progress.CurrentFile,
Outcomes(progress.Outcomes),
progress.Copied,
run.LastError);
}
public static ImportPlanDto Plan(ImportPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
return new ImportPlanDto(
plan.ToImport,
plan.ToReplace,
plan.Skipped,
plan.LeftOutNoAccount,
plan.FoldersWithoutAccount,
plan.LeftOutUndecided,
plan.AlreadyDone,
plan.Bytes,
plan.Mode == ImportMode.Move ? "move" : "copy",
plan.ButtonLabel,
plan.LeftOutLabel);
}
public static FolderTargetDto Target(FolderTarget target)
{
ArgumentNullException.ThrowIfNull(target);
return new FolderTargetDto(
target.Kind switch { FolderTargetKind.Existing => "existing", FolderTargetKind.NewArchiveAccount => "newArchiveAccount", _ => "none" },
target.AccountId,
target.Username);
}
public static async Task<ImportReviewDto> ReviewAsync(ImportService service, IFebeStorage storage, long runId, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(service);
ArgumentNullException.ThrowIfNull(storage);
var review = await GuardAsync(() => service.GetReviewAsync(runId, ct)).ConfigureAwait(false);
var plan = await GuardAsync(() => service.GetPlanAsync(runId, ct)).ConfigureAwait(false);
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
return new ImportReviewDto(
Run(service, review.Run, clock, service.ActiveRunId),
review.DisplayPath,
review.Headline,
review.Files,
review.Bytes,
Outcomes(review.ByOutcome),
review.Recognized,
review.PendingDuplicates,
[.. review.Folders.Select(f => new ImportFolderDto(f.Folder, f.DisplayName, f.ProbableAccount, f.Files, f.Bytes, f.New, f.AlreadyInLibrary, f.ProbableDuplicates, f.Unrecognized, f.Recognized, Target(f.Target), f.IsBlocked))],
Plan(plan),
review.CanMove,
review.StogramHypothesis,
review.Copied,
[.. accounts.OrderBy(a => a.Username, StringComparer.Ordinal).Select(a => new AccountChoiceDto(a.Id, a.Username, ApiMapping.State(a.State)))]);
}
public static DuplicateCaseDto Case(DuplicateCase item, IClock clock)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentNullException.ThrowIfNull(clock);
DuplicateSideDto Side(DuplicateSide s) => new(
s.InLibrary,
s.MediaId,
s.ImportFileId,
s.Username,
s.Path,
s.Kind is { } k ? ApiMapping.Media(k) : null,
s.Width,
s.Height,
s.Bytes,
s.Date is { } date ? ApiMapping.Local(date, clock.Now, clock.LocalZone) : null,
s.InLibrary
? (s.HasThumbnail && s.Sha256 is { } sha ? "/api/thumbnails/" + sha : null)
: s.ImportFileId is { } f && s.Kind == MediaKind.Photo ? "/api/import/files/" + f.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/preview" : null);
return new DuplicateCaseDto(
item.Pair.Id,
DuplicatesApi.Reason(item.Pair.Reason),
DuplicatesApi.Decision(item.Pair.Decision),
Side(item.Existing),
Side(item.Candidate),
item.CandidateIsLarger,
item.InsideSource);
}
public static ImportReportDto Report(ImportService service, ImportReport report, IClock clock)
{
ArgumentNullException.ThrowIfNull(service);
ArgumentNullException.ThrowIfNull(report);
return new ImportReportDto(
Run(service, report.Run, clock, service.ActiveRunId),
report.DisplayPath,
report.Files,
report.Bytes,
Outcomes(report.ByOutcome),
report.Copied,
report.Moved,
report.Replaced,
report.Skipped,
report.LeftOut,
report.Failed,
report.BytesCopied,
[.. report.ImportedByAccount.Select(a => new ImportCountDto(a.Username, a.Files))],
[.. report.AlreadyInLibraryByAccount.Select(a => new ImportCountDto(a.Username, a.Files))],
report.Unrecognized,
[.. report.Problems.Select(p => new ImportNoteDto(p.Path, p.Note))]);
}
private static ImportMode ParseMode(string? text) => text?.ToLowerInvariant() switch
{
"copy" => ImportMode.Copy,
"move" => ImportMode.Move,
_ => throw new BadRequestException("Modo sconosciuto: copia o sposta."),
};
private static string ItalianTextCount(int n) => Core.Engine.ItalianText.Count(n, "doppione", "doppioni");
private static async Task<ImportRun> GetRunAsync(ImportService service, long id, CancellationToken ct) =>
await service.GetRunAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa importazione non esiste più.");
// ---------------------------------------------------------------------------------------------- errors
/// <summary>The import's own exceptions become Italian answers: 400 for a refused request, 404 for a missing import.</summary>
internal static T Guard<T>(Func<T> action)
{
try
{
return action();
}
catch (Exception ex) when (Translate(ex) is { } translated)
{
throw translated;
}
}
internal static async Task<T> GuardAsync<T>(Func<Task<T>> 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
{
ImportSourceException => 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,
};
}
+296
View File
@@ -0,0 +1,296 @@
namespace Febe.Web.Api;
// JSON shapes of the second part of the interface (Attività, Impostazioni, Importa, Collegamento, Browser, doppioni).
// Same conventions as Dtos.cs: English camelCase names, Italian texts, times as Unix milliseconds or LocalTimeDto.
// ---------------------------------------------------------------- connection (PROTOCOLLO.md)
/// <summary><c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, verificationRequired, browserUnavailable.</summary>
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl);
/// <summary><c>POST /api/connection/begin</c>.</summary>
public sealed record BeginDrivingRequest(bool OpenLogin);
/// <summary><c>POST /api/connection/finish</c>.</summary>
public sealed record FinishDto(bool Connected, string Message);
// ---------------------------------------------------------------- activity
/// <summary>A stop of the circuit breaker. <see cref="Level"/>: throttle, challenge, disconnect.</summary>
public sealed record IncidentDto(
long Id,
LocalTimeDto At,
string Level,
string Title,
string Signal,
string? Url,
LocalTimeDto? StoppedUntil,
LocalTimeDto? ResolvedAt,
bool Open,
string? Note);
/// <param name="Advice">«Tre rallentamenti in sette giorni»: the proposal of spec §7.6, or null.</param>
public sealed record IncidentListDto(IReadOnlyList<IncidentDto> Items, int ThrottlesLastWeek, string? Advice);
/// <summary>The preview of Febe's browser: <see cref="Frame"/> is the address of the JPEG (with a version), or null.</summary>
public sealed record BrowserPreviewDto(bool HasFrame, string? Url, long? At, string? Frame);
/// <summary>Probable duplicates waiting for a decision, by origin.</summary>
public sealed record DuplicateCountsDto(int Download, int Import);
// ---------------------------------------------------------------- settings: general
/// <summary>A folder with the free space of its disk and the space it uses (measured in the background).</summary>
public sealed record FolderInfoDto(string Path, long? FreeBytes, long? UsedBytes, bool Measuring);
public sealed record NamingPreviewFileDto(string Name, string Kind);
public sealed record NamingPreviewFolderDto(IReadOnlyList<string> Path, IReadOnlyList<NamingPreviewFileDto> Files);
/// <summary>The «Risultato» tree of mockup 08 and the problems of the two schemes.</summary>
public sealed record NamingPreviewDto(string AccountFolder, IReadOnlyList<NamingPreviewFolderDto> Folders, IReadOnlyList<string> Errors, IReadOnlyList<string> Warnings);
/// <summary>Impostazioni, Generali (mockup 08).</summary>
/// <param name="Autostart">Windows: «Avvia Febe all'accensione del computer»; null where it does not exist.</param>
/// <param name="KeepInTray">Windows: «Chiudendo la finestra, Febe resta attivo nell'area di notifica».</param>
public sealed record GeneralSettingsDto(
FolderInfoDto Library,
FolderInfoDto Data,
bool FoldersReadOnly,
bool CanPickFolder,
bool CanChangeDataFolder,
string NamingScheme,
string HighlightScheme,
string DefaultNamingScheme,
string DefaultHighlightScheme,
IReadOnlyList<string> Placeholders,
bool SetFileTime,
NamingPreviewDto Preview,
bool? Autostart,
bool KeepInTray,
string Language);
/// <summary>Saves Impostazioni, Generali. A null <see cref="LibraryFolder"/> keeps the library folder.</summary>
public sealed record GeneralSettingsRequest(string? LibraryFolder, string NamingScheme, string HighlightScheme, bool SetFileTime, bool? Autostart, bool? KeepInTray);
public sealed record NamingRequest(string? NamingScheme, string? HighlightScheme);
/// <summary><see cref="Which"/>: library or data.</summary>
public sealed record PickFolderRequest(string Which);
/// <summary>A path; null or empty when Alberto cancelled the picker.</summary>
public sealed record PathDto(string? Path);
public sealed record PathRequest(string Path);
// ---------------------------------------------------------------- settings: limits (mockup 07)
/// <summary>A budget of a category (ActionKind names, as in the engine snapshot) with the most the interface accepts.</summary>
public sealed record BudgetValueDto(string Kind, string Label, int PerHour, int PerDay, int MaxPerHour, int MaxPerDay);
/// <summary>The values of a caution profile. <see cref="Kind"/>: prudent, balanced, fast, custom. Times «07:30».</summary>
public sealed record ProfileValuesDto(
string Kind,
string Name,
string WindowStart,
string WindowEnd,
int JitterMinutes,
int SessionMinMinutes,
int SessionMaxMinutes,
int PauseMinMinutes,
int PauseMaxMinutes,
IReadOnlyList<BudgetValueDto> Budgets,
double DataPerDayGb,
int BackfillPerAccount,
int RampUpDays);
/// <summary>The limits of spec §7.5 that the interface enforces.</summary>
public sealed record LimitRulesDto(int MinPauseMinutes, int MaxSessionMinutes, int MaxWindowHours, int MaxJitterMinutes, double MaxDataPerDayGb, int MaxBackfillPerAccount, int MaxRampUpDays);
/// <summary>Impostazioni, Limiti e comportamento. <see cref="Pace"/>: slow, natural, brisk. Days: 0 Sunday … 6 Saturday.</summary>
/// <param name="Stops">The fixed stops after throttles, informative only: «1 ora», «6 ore», «24 ore».</param>
public sealed record LimitsDto(
string Profile,
IReadOnlyList<ProfileValuesDto> Presets,
ProfileValuesDto Current,
string Pace,
bool GradualStart,
IReadOnlyList<int> ActiveDays,
LimitRulesDto Rules,
IReadOnlyList<string> Stops);
/// <summary>Saves the limits; <see cref="Values"/> is read when <see cref="Profile"/> is custom.</summary>
public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList<int> ActiveDays);
// ---------------------------------------------------------------- settings: notifications (spec §13.3)
public sealed record AlertEventsDto(bool Verification, bool Disconnection, bool Throttle, bool BackfillDone, bool DiskLow, bool UnknownFormat);
/// <summary>The token is never sent back: only whether it is set.</summary>
public sealed record NotificationSettingsDto(AlertEventsDto Events, bool Windows, bool WindowsAvailable, string? TelegramChatId, bool TelegramTokenSet, bool TelegramAvailable);
/// <summary>
/// Saves the notifications. <see cref="TelegramToken"/>: null or empty keeps the stored token, a value replaces it;
/// <see cref="RemoveTelegramToken"/> removes it.
/// </summary>
public sealed record NotificationSettingsRequest(AlertEventsDto Events, bool Windows, string? TelegramChatId, string? TelegramToken, bool RemoveTelegramToken);
/// <summary><see cref="Channel"/>: telegram or windows.</summary>
public sealed record AlertTestRequest(string Channel);
public sealed record AlertTestDto(bool Sent, string Message);
// ---------------------------------------------------------------- settings: data and backups (spec §8.2, §8.5)
public sealed record BackupDto(string Day, string Name, long Bytes, LocalTimeDto Modified);
/// <summary>The rebuild of the database: progress while running, then the report as Italian lines.</summary>
public sealed record RebuildStatusDto(bool Running, string? Folder, int FoldersDone, int FoldersTotal, int FilesChecked, IReadOnlyList<string> Lines, string? Error, LocalTimeDto? FinishedAt);
public sealed record DataSettingsDto(FolderInfoDto Data, string Database, long? DatabaseBytes, string BackupsFolder, IReadOnlyList<BackupDto> Backups, int KeepDays, RebuildStatusDto Rebuild);
/// <summary>«Ricostruisci»: <see cref="Confirm"/> must be the word «ricostruisci» typed by Alberto.</summary>
public sealed record RebuildRequest(string Confirm);
/// <summary>Impostazioni, Informazioni.</summary>
public sealed record AboutDto(string Version, string Edition, string DataFolder, string LibraryFolder, string Guide, string Repository);
// ---------------------------------------------------------------- probable duplicates (mockup 09, spec §9.5)
/// <summary>One side of a probable duplicate. <see cref="Image"/> is the address of its picture (thumbnail or preview).</summary>
public sealed record DuplicateSideDto(
bool InLibrary,
long? MediaId,
long? ImportFileId,
string? Username,
string? Path,
string? Kind,
int? Width,
int? Height,
long? Bytes,
LocalTimeDto? Date,
string? Image);
/// <summary>A probable duplicate. <see cref="Reason"/>: sameInstagramId, visuallySimilar. <see cref="Decision"/>: pending, keepLarger, keepExisting, keepBoth.</summary>
public sealed record DuplicateCaseDto(long PairId, string Reason, string Decision, DuplicateSideDto Existing, DuplicateSideDto Candidate, bool CandidateIsLarger, bool InsideSource);
public sealed record DuplicatePageDto(IReadOnlyList<DuplicateCaseDto> Cases, int Pending);
/// <summary>A decision. <see cref="ApplyToAll"/>: «Applica a tutti i casi simili» (every pending pair).</summary>
public sealed record DecideRequest(string Decision, bool ApplyToAll);
public sealed record DecideDto(int Decided, int FilesRemoved, IReadOnlyList<string> Problems, string Message, int Pending);
// ---------------------------------------------------------------- import (spec §9, mockup 09)
/// <summary>An import. <see cref="State"/>: analyzing, analysisInterrupted, reviewing, copying, copyInterrupted, completed, cancelled.</summary>
public sealed record ImportRunDto(long Id, string Source, string DisplayPath, string State, string Mode, bool ReadOnly, LocalTimeDto Started, LocalTimeDto? Completed, string? Error, bool Running);
/// <param name="SourceRoot">Docker: the root of the sources (the page lists its subfolders); null: the native picker.</param>
public sealed record ImportOverviewDto(IReadOnlyList<ImportRunDto> Runs, long? ActiveRunId, string? SourceRoot, bool PickFolder);
public sealed record SourceFolderDto(string Name, string Path, bool HasSubfolders);
/// <param name="Path">The folder listed (relative to the root), null for the root itself.</param>
/// <param name="Parent">The folder above, or null at the root.</param>
public sealed record SourceListDto(string? Path, string? Parent, string DisplayPath, IReadOnlyList<SourceFolderDto> Folders);
public sealed record SourceInfoDto(string Path, string DisplayPath, string Name, bool ReadOnly, bool CanMove, bool LooksLikeFebeLibrary, bool LooksLikeStogram, IReadOnlyList<string> Folders);
public sealed record ImportStartRequest(string Path, bool Stogram);
public sealed record OutcomeCountsDto(int New, int AlreadyInLibrary, int ProbableDuplicates, int Unrecognized, int IdenticalInSource);
/// <summary>Step 2 and 4. <see cref="Phase"/>: listing, analyzing, copying, finished.</summary>
public sealed record ImportProgressDto(
long RunId,
string Phase,
string State,
bool Running,
int FilesDone,
int FilesTotal,
long BytesDone,
long BytesTotal,
double Fraction,
string? CurrentFile,
OutcomeCountsDto Outcomes,
int Copied,
string? Error);
/// <summary>Where a folder goes. <see cref="Kind"/>: none, existing, newArchiveAccount.</summary>
public sealed record FolderTargetDto(string Kind, long? AccountId, string? Username);
public sealed record ImportFolderDto(
string Folder,
string DisplayName,
string? ProbableAccount,
int Files,
long Bytes,
int New,
int AlreadyInLibrary,
int ProbableDuplicates,
int Unrecognized,
int Recognized,
FolderTargetDto Target,
bool Blocked);
public sealed record ImportPlanDto(
int ToImport,
int ToReplace,
int Skipped,
int LeftOutNoAccount,
int FoldersWithoutAccount,
int LeftOutUndecided,
int AlreadyDone,
long Bytes,
string Mode,
string ButtonLabel,
string? LeftOutLabel);
public sealed record AccountChoiceDto(long Id, string Username, string State);
/// <summary>Step 3 (mockup 09).</summary>
public sealed record ImportReviewDto(
ImportRunDto Run,
string DisplayPath,
string Headline,
int Files,
long Bytes,
OutcomeCountsDto Outcomes,
int Recognized,
int PendingDuplicates,
IReadOnlyList<ImportFolderDto> Folders,
ImportPlanDto Plan,
bool CanMove,
bool StogramHypothesis,
int Copied,
IReadOnlyList<AccountChoiceDto> Accounts);
/// <summary>Sets where a folder goes. <see cref="Kind"/>: none, existing (with <see cref="AccountId"/>), newArchiveAccount (with <see cref="Username"/>).</summary>
public sealed record FolderTargetRequest(string Folder, string Kind, long? AccountId, string? Username);
/// <summary><see cref="Mode"/>: copy or move.</summary>
public sealed record ImportModeRequest(string Mode);
public sealed record ImportCountDto(string Username, int Files);
public sealed record ImportNoteDto(string Path, string Note);
/// <summary>Step 4: the final report.</summary>
public sealed record ImportReportDto(
ImportRunDto Run,
string DisplayPath,
int Files,
long Bytes,
OutcomeCountsDto Outcomes,
int Copied,
int Moved,
int Replaced,
int Skipped,
int LeftOut,
int Failed,
long BytesCopied,
IReadOnlyList<ImportCountDto> ImportedByAccount,
IReadOnlyList<ImportCountDto> AlreadyInLibraryByAccount,
IReadOnlyList<string> Unrecognized,
IReadOnlyList<ImportNoteDto> Problems);
+634
View File
@@ -0,0 +1,634 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web.Engine;
using Febe.Web.Import;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// Impostazioni (spec §4.7, §7.5, §8.2, §8.5, §13.3; mockups 07 and 08): Generali, Limiti e comportamento, Notifiche,
/// Dati e copie di sicurezza, Informazioni. Collegamento a Instagram is <see cref="ConnectionApi"/>.
/// </summary>
public static class SettingsApi
{
/// <summary>Where the guide lives (wiki of the repository).</summary>
public const string GuideUrl = "https://gitea.encke-hake.ts.net/Alby96/Febe/wiki";
public const string RepositoryUrl = "https://gitea.encke-hake.ts.net/Alby96/Febe";
private const double GiB = 1024d * 1024 * 1024;
public static void Map(IEndpointRouteBuilder endpoints)
{
// ------------------------------------------------------------------------------------------ Generali
endpoints.MapGet("/api/settings/general", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
ApiHttp.Json(await GeneralAsync(context, Deps.From(services), ct).ConfigureAwait(false), FebeJsonContext.Default.GeneralSettingsDto));
endpoints.MapPut("/api/settings/general", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
{
var d = Deps.From(services);
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.GeneralSettingsRequest).ConfigureAwait(false);
var general = Validate(NamingScheme.Validate(body.NamingScheme, forHighlights: false), "Schema");
var highlight = Validate(NamingScheme.Validate(body.HighlightScheme, forHighlights: true), "Schema per le raccolte in evidenza");
var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock);
var root = d.Library.Layout.Root;
if (!string.IsNullOrWhiteSpace(body.LibraryFolder) && !SamePath(body.LibraryFolder, root))
{
if (caps.FoldersReadOnly)
{
throw new BadRequestException("In Docker la cartella della libreria si cambia dal contenitore (volume /libreria), non dall'interfaccia.");
}
root = await ChangeLibraryRootAsync(d, body.LibraryFolder, ct).ConfigureAwait(false);
}
await new LibrarySettings(root, new LibraryNaming(general, highlight), body.SetFileTime).SaveAsync(d.Storage.Settings, ct).ConfigureAwait(false);
if (caps.Autostart && body.Autostart is { } autostart)
{
await d.Shell.SetAutostartAsync(autostart, ct).ConfigureAwait(false);
}
if (body.KeepInTray is { } tray)
{
await d.Storage.Settings.SetBoolAsync(DesktopSettingKeys.KeepInTray, tray, ct).ConfigureAwait(false);
}
d.Import.LibrarySettingsChanged();
d.Changes.Publish(new LibraryChange(d.Clock.Now, null, "settings"));
return ApiHttp.Json(await GeneralAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.GeneralSettingsDto);
});
endpoints.MapPost("/api/settings/naming-preview", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.NamingRequest).ConfigureAwait(false);
var sample = await SampleAccountAsync(storage, ct).ConfigureAwait(false);
return ApiHttp.Json(Preview(NamingPreview.Build(body.NamingScheme, body.HighlightScheme, clock.LocalZone, sample)), FebeJsonContext.Default.NamingPreviewDto);
});
endpoints.MapPost("/api/settings/pick-folder", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
{
var d = Deps.From(services);
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PickFolderRequest).ConfigureAwait(false);
if (!d.Shell.CanPickFolder)
{
throw new BadRequestException("Qui le cartelle si cambiano dal contenitore, non dall'interfaccia.");
}
var data = string.Equals(body.Which, "data", StringComparison.OrdinalIgnoreCase);
var picked = await d.Shell.PickFolderAsync(
data ? "Cartella dei dati di Febe" : "Cartella della libreria",
data ? d.Library.Data.Root : d.Library.Layout.Root,
ct).ConfigureAwait(false);
return ApiHttp.Json(new PathDto(picked), FebeJsonContext.Default.PathDto);
});
endpoints.MapPost("/api/settings/data-folder", async (HttpContext context, IDataFolderChange change, FebeLibrary library, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PathRequest).ConfigureAwait(false);
if (!change.CanChange)
{
throw new BadRequestException("La cartella dei dati qui non si cambia dall'interfaccia: si sceglie quando si avvia Febe (in Docker, con il volume /dati).");
}
if (string.IsNullOrWhiteSpace(body.Path) || !Path.IsPathFullyQualified(body.Path))
{
throw new BadRequestException("Serve il percorso completo di una cartella.");
}
if (IsSameOrInside(body.Path, library.Layout.Root) || IsSameOrInside(library.Layout.Root, body.Path))
{
throw new BadRequestException("La cartella dei dati non può stare dentro la libreria, né contenerla.");
}
return ApiHttp.Message(await change.RequestChangeAsync(body.Path, ct).ConfigureAwait(false));
});
// ------------------------------------------------------------------------------------------ Limiti e comportamento
endpoints.MapGet("/api/settings/limits", async (IFebeStorage storage, CancellationToken ct) =>
ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto));
endpoints.MapPut("/api/settings/limits", async (HttpContext context, IFebeStorage storage, IEngineSettingsControl engine, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.LimitsRequest).ConfigureAwait(false);
var stored = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var settings = ToSettings(body, stored);
var errors = CautionProfileRules.Validate(settings.EffectiveProfile);
if (errors.Count > 0)
{
throw new BadRequestException(string.Join(" ", errors));
}
await engine.ApplyAsync(settings, ct).ConfigureAwait(false);
return ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto);
});
// ------------------------------------------------------------------------------------------ Notifiche
endpoints.MapGet("/api/settings/notifications", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
{
var d = Deps.From(services);
return ApiHttp.Json(await NotificationsAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.NotificationSettingsDto);
});
endpoints.MapPut("/api/settings/notifications", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
{
var d = Deps.From(services);
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.NotificationSettingsRequest).ConfigureAwait(false);
var stored = await AlertSettingsStore.LoadAsync(d.Storage.Settings, ct).ConfigureAwait(false);
var chat = string.IsNullOrWhiteSpace(body.TelegramChatId) ? null : body.TelegramChatId.Trim();
if (chat is not null && (chat.Length > 64 || !chat.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '@')))
{
throw new BadRequestException("L'identificativo della chat è un numero (anche negativo, per i gruppi) o un nome come @canale.");
}
var token = body.RemoveTelegramToken ? null : string.IsNullOrWhiteSpace(body.TelegramToken) ? stored.TelegramToken : body.TelegramToken.Trim();
if (token is not null && (token.Length > 200 || token.Any(char.IsWhiteSpace)))
{
throw new BadRequestException("Il gettone del bot non è valido: copialo per intero dal messaggio di BotFather, senza spazi.");
}
var e = body.Events;
await AlertSettingsStore.SaveAsync(
d.Storage.Settings,
new AlertSettings(new AlertEvents(e.Verification, e.Disconnection, e.Throttle, e.BackfillDone, e.DiskLow, e.UnknownFormat), body.Windows, chat, token),
ct).ConfigureAwait(false);
return ApiHttp.Json(await NotificationsAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.NotificationSettingsDto);
});
endpoints.MapPost("/api/settings/notifications/test", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
{
var d = Deps.From(services);
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AlertTestRequest).ConfigureAwait(false);
var settings = await AlertSettingsStore.LoadAsync(d.Storage.Settings, ct).ConfigureAwait(false);
if (string.Equals(body.Channel, "windows", StringComparison.OrdinalIgnoreCase))
{
if (!SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock).Notifications)
{
throw new BadRequestException("Le notifiche di Windows esistono solo nella versione per Windows.");
}
await d.Shell.NotifyAsync("Febe", "Prova di notifica: gli avvisi di Febe arriveranno così.", ct).ConfigureAwait(false);
return ApiHttp.Json(new AlertTestDto(true, "Notifica di prova inviata: dovresti vederla nell'angolo dello schermo."), FebeJsonContext.Default.AlertTestDto);
}
if (!settings.TelegramConfigured)
{
throw new BadRequestException("Scrivi il gettone del bot e l'identificativo della chat, salva, poi invia la prova.");
}
var sender = d.Services.GetService(typeof(IAlertTestSender)) as IAlertTestSender ?? new TelegramNotAvailableYet();
var result = await sender.SendTelegramTestAsync(settings, ct).ConfigureAwait(false);
return ApiHttp.Json(new AlertTestDto(result.Sent, result.Message), FebeJsonContext.Default.AlertTestDto);
});
// ------------------------------------------------------------------------------------------ Dati e copie
endpoints.MapGet("/api/settings/data", (IServiceProvider services) =>
ApiHttp.Json(Data(Deps.From(services)), FebeJsonContext.Default.DataSettingsDto));
endpoints.MapPost("/api/settings/backups", async (IServiceProvider services, CancellationToken ct) =>
{
var d = Deps.From(services);
var backup = new DailyBackup(d.Storage.Maintenance, d.Clock, d.Library.Data.Backups);
var result = await backup.RunNowAsync(ct).ConfigureAwait(false);
d.Sizes.Invalidate(d.Library.Data.Root);
var created = result.Created!;
return ApiHttp.Message($"Copia fatta: {Path.GetFileName(created.Path)}, {ItalianText.Bytes(created.Bytes)}. Se ce n'era già una di oggi, questa la sostituisce.");
});
endpoints.MapPost("/api/settings/rebuild", async (HttpContext context, RebuildJob job, ImportHub import, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.RebuildRequest).ConfigureAwait(false);
if (!string.Equals(body.Confirm?.Trim(), "ricostruisci", StringComparison.OrdinalIgnoreCase))
{
throw new BadRequestException("Per confermare scrivi la parola «ricostruisci».");
}
if ((await import.GetAsync(ct).ConfigureAwait(false)).ActiveRunId is not null)
{
throw new BadRequestException("C'è un'importazione al lavoro: aspetta che finisca, poi ricostruisci.");
}
if (!job.TryStart())
{
throw new BadRequestException("La ricostruzione è già in corso.");
}
return ApiHttp.Message("Ricostruzione avviata: Febe rilegge le cartelle degli account e i loro file _febe.jsonl. Nessun file viene spostato o cancellato.");
});
endpoints.MapGet("/api/settings/rebuild", (RebuildJob job, IClock clock) =>
ApiHttp.Json(Rebuild(job.State, clock), FebeJsonContext.Default.RebuildStatusDto));
// ------------------------------------------------------------------------------------------ Informazioni
endpoints.MapGet("/api/about", (HttpContext context, IServiceProvider services) =>
{
var d = Deps.From(services);
var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock);
return ApiHttp.Json(
new AboutDto(d.Options.Version, caps.Edition == "desktop" ? "Windows" : "Docker", d.Library.Data.Root, d.Library.Layout.Root, GuideUrl, RepositoryUrl),
FebeJsonContext.Default.AboutDto);
});
}
// ---------------------------------------------------------------------------------------------- Generali
public static async Task<GeneralSettingsDto> GeneralAsync(HttpContext context, Deps d, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(d);
var settings = await LibrarySettings.LoadAsync(d.Storage.Settings, d.Library.Layout.Root, ct).ConfigureAwait(false);
var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock);
var sample = await SampleAccountAsync(d.Storage, ct).ConfigureAwait(false);
var library = d.Library.Layout.Root;
var data = d.Library.Data.Root;
var (used, measuring) = d.Sizes.Get(data);
bool? autostart = caps.Autostart ? await d.Shell.GetAutostartAsync(ct).ConfigureAwait(false) : null;
var tray = await d.Storage.Settings.GetBoolAsync(DesktopSettingKeys.KeepInTray, true, ct).ConfigureAwait(false);
var dataChange = d.Services.GetService(typeof(IDataFolderChange)) as IDataFolderChange;
return new GeneralSettingsDto(
new FolderInfoDto(library, FolderSizes.FreeBytes(library), null, false),
new FolderInfoDto(data, FolderSizes.FreeBytes(data), used, measuring),
caps.FoldersReadOnly,
caps.PickFolder,
!caps.FoldersReadOnly && (dataChange?.CanChange ?? false),
settings.Naming.General.Text,
settings.Naming.Highlight.Text,
NamingScheme.DefaultGeneral,
NamingScheme.DefaultHighlight,
NamingScheme.Placeholders,
settings.SetFileTimeToPublication,
Preview(NamingPreview.Build(settings.Naming.General.Text, settings.Naming.Highlight.Text, d.Clock.LocalZone, sample)),
autostart,
tray,
"it");
}
public static NamingPreviewDto Preview(NamingPreview preview)
{
ArgumentNullException.ThrowIfNull(preview);
return new NamingPreviewDto(
preview.AccountFolder,
[.. preview.Folders.Select(f => new NamingPreviewFolderDto(f.Path, [.. f.Files.Select(x => new NamingPreviewFileDto(x.Name, ApiMapping.Media(x.Kind)))]))],
preview.Errors,
preview.Warnings);
}
/// <summary>The account whose name the preview shows: the first one followed (or any), as in mockup 08.</summary>
private static async Task<string> 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()
?? accounts.OrderBy(a => a.Id).Select(a => a.Username).FirstOrDefault()
?? "nome.utente";
}
private static NamingScheme Validate(NamingSchemeValidation validation, string name)
{
if (validation.IsValid)
{
return validation.Scheme!;
}
throw new BadRequestException(string.Join(" ", validation.Errors.Select(e => $"{name}: {e}")));
}
/// <summary>
/// A new library folder (desktop). Accounts whose files are in their default folder of the old library keep it
/// (their folder becomes an absolute path), so nothing has to move; new accounts go in the new folder.
/// </summary>
private static async Task<string> ChangeLibraryRootAsync(Deps d, string requested, CancellationToken ct)
{
if (!Path.IsPathFullyQualified(requested))
{
throw new BadRequestException("Serve il percorso completo di una cartella.");
}
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(requested));
var data = d.Library.Data.Root;
if (IsSameOrInside(root, data) || IsSameOrInside(data, root))
{
throw new BadRequestException("La libreria non può stare dentro la cartella dei dati, né contenerla.");
}
try
{
Directory.CreateDirectory(root);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
throw new BadRequestException($"Febe non riesce a usare questa cartella ({ex.Message}). Scegline un'altra, su un disco collegato e scrivibile.");
}
var old = d.Library.Layout;
foreach (var account in await d.Storage.Accounts.ListAsync(ct).ConfigureAwait(false))
{
if (account.Folder is { } folder && Path.IsPathFullyQualified(folder))
{
continue;
}
var current = old.AccountFolder(account);
if (Directory.Exists(current))
{
await d.Storage.Accounts.UpdateAsync(account with { Folder = current }, ct).ConfigureAwait(false);
}
}
d.Library.UseLibraryRoot(root);
return root;
}
// ---------------------------------------------------------------------------------------------- Limiti
public static LimitsDto Limits(EngineSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
var rules = new LimitRulesDto(
(int)CautionProfile.Limits.MinPause.TotalMinutes,
(int)CautionProfile.Limits.MaxSession.TotalMinutes,
(int)CautionProfile.Limits.MaxWindow.TotalHours,
(int)CautionProfileRules.MaxJitter.TotalMinutes,
CautionProfile.Limits.MaxDataPerDayBytes / GiB,
CautionProfile.Fast.BackfillPostsPerAccountPerDay * 2,
CautionProfileRules.MaxRampUpDays);
return new LimitsDto(
ProfileName(settings.ProfileKind),
[Values(CautionProfile.Prudent), Values(CautionProfile.Balanced), Values(CautionProfile.Fast)],
Values(settings.EffectiveProfile),
Pace(settings.Pace),
settings.GradualStart,
[.. settings.ActiveDays.Select(d => (int)d).Order()],
rules,
["1 ora", "6 ore", "24 ore"]);
}
public static ProfileValuesDto Values(CautionProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
var budgets = SnapshotParts.All.Where(k => k != ActionKind.DataDownload).Select(k =>
{
var budget = profile.Budgets.TryGetValue(k, out var b) ? b : CautionProfile.Prudent.Budgets[k];
var max = CautionProfile.Limits.MaxBudget(k);
return new BudgetValueDto(k.ToString(), ItalianText.CategoryLabel(k), budget.PerHour, budget.PerDay, max.PerHour, max.PerDay);
}).ToList();
return new ProfileValuesDto(
ProfileName(profile.Kind),
ItalianText.Profile(profile.Kind),
profile.WindowStart.ToString("HH:mm", CultureInfo.InvariantCulture),
profile.WindowEnd.ToString("HH:mm", CultureInfo.InvariantCulture),
(int)Math.Round(profile.WindowJitter.TotalMinutes),
(int)Math.Round(profile.SessionMin.TotalMinutes),
(int)Math.Round(profile.SessionMax.TotalMinutes),
(int)Math.Round(profile.PauseMin.TotalMinutes),
(int)Math.Round(profile.PauseMax.TotalMinutes),
budgets,
Math.Round(profile.DataPerDayBytes / GiB, 2),
profile.BackfillPostsPerAccountPerDay,
profile.RampUpDays);
}
private static EngineSettings ToSettings(LimitsRequest body, EngineSettings stored)
{
var kind = ParseProfile(body.Profile) ?? throw new BadRequestException("Profilo di prudenza sconosciuto.");
var pace = body.Pace?.ToLowerInvariant() switch
{
"slow" => GesturePace.Slow,
"natural" => GesturePace.Natural,
"brisk" => GesturePace.Brisk,
_ => throw new BadRequestException("Ritmo dei gesti sconosciuto: lento, naturale o svelto."),
};
var days = new HashSet<DayOfWeek>();
foreach (var day in body.ActiveDays ?? [])
{
if (day is < 0 or > 6)
{
throw new BadRequestException("Giorno della settimana non valido.");
}
days.Add((DayOfWeek)day);
}
if (days.Count == 0)
{
throw new BadRequestException("Serve almeno un giorno attivo.");
}
var custom = stored.Custom;
if (kind == CautionProfileKind.Custom)
{
custom = FromValues(body.Values ?? throw new BadRequestException("Mancano i valori del profilo «Su misura»."));
}
return new EngineSettings { ProfileKind = kind, Custom = custom, Pace = pace, GradualStart = body.GradualStart, ActiveDays = days };
}
private static CautionProfile FromValues(ProfileValuesDto v)
{
var budgets = new Dictionary<ActionKind, Budget>();
foreach (var budget in v.Budgets ?? [])
{
if (!Enum.TryParse<ActionKind>(budget.Kind, ignoreCase: false, out var kind) || kind == ActionKind.DataDownload)
{
throw new BadRequestException("Tetto di una categoria sconosciuta.");
}
budgets[kind] = new Budget(budget.PerHour, budget.PerDay);
}
foreach (var kind in SnapshotParts.All.Where(k => k != ActionKind.DataDownload && !budgets.ContainsKey(k)))
{
throw new BadRequestException($"Manca il tetto delle {ItalianText.Category(kind)}.");
}
if (double.IsNaN(v.DataPerDayGb) || v.DataPerDayGb < 0 || v.DataPerDayGb > 1_000)
{
throw new BadRequestException("I dati scaricati al giorno sono un numero di GB.");
}
return new CautionProfile
{
Kind = CautionProfileKind.Custom,
WindowStart = ParseTime(v.WindowStart, "L'inizio della fascia"),
WindowEnd = ParseTime(v.WindowEnd, "La fine della fascia"),
WindowJitter = TimeSpan.FromMinutes(v.JitterMinutes),
SessionMin = TimeSpan.FromMinutes(v.SessionMinMinutes),
SessionMax = TimeSpan.FromMinutes(v.SessionMaxMinutes),
PauseMin = TimeSpan.FromMinutes(v.PauseMinMinutes),
PauseMax = TimeSpan.FromMinutes(v.PauseMaxMinutes),
Budgets = budgets,
DataPerDayBytes = (long)Math.Round(v.DataPerDayGb * GiB),
BackfillPostsPerAccountPerDay = v.BackfillPerAccount,
RampUpDays = v.RampUpDays,
};
}
private static TimeOnly ParseTime(string? text, string what)
{
var value = text?.Trim().Replace('.', ':');
if (value == "24:00")
{
return new TimeOnly(0, 0);
}
return TimeOnly.TryParseExact(value, ["H:mm", "HH:mm"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var time)
? time
: throw new BadRequestException($"{what} va scritto come ora e minuti, per esempio 07:30.");
}
public static string ProfileName(CautionProfileKind kind) => kind switch
{
CautionProfileKind.Prudent => "prudent",
CautionProfileKind.Balanced => "balanced",
CautionProfileKind.Fast => "fast",
_ => "custom",
};
public static CautionProfileKind? ParseProfile(string? text) => text?.ToLowerInvariant() switch
{
"prudent" => CautionProfileKind.Prudent,
"balanced" => CautionProfileKind.Balanced,
"fast" => CautionProfileKind.Fast,
"custom" => CautionProfileKind.Custom,
_ => null,
};
public static string Pace(GesturePace pace) => pace switch
{
GesturePace.Slow => "slow",
GesturePace.Brisk => "brisk",
_ => "natural",
};
// ---------------------------------------------------------------------------------------------- Notifiche
private static async Task<NotificationSettingsDto> NotificationsAsync(HttpContext context, Deps d, CancellationToken ct)
{
var settings = await AlertSettingsStore.LoadAsync(d.Storage.Settings, ct).ConfigureAwait(false);
var e = settings.Events;
var sender = d.Services.GetService(typeof(IAlertTestSender));
return new NotificationSettingsDto(
new AlertEventsDto(e.Verification, e.Disconnection, e.Throttle, e.BackfillDone, e.DiskLow, e.UnknownFormat),
settings.WindowsNotifications,
SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock).Notifications,
settings.TelegramChatId,
!string.IsNullOrWhiteSpace(settings.TelegramToken),
sender is not null and not TelegramNotAvailableYet);
}
// ---------------------------------------------------------------------------------------------- Dati
public static DataSettingsDto Data(Deps d)
{
ArgumentNullException.ThrowIfNull(d);
var data = d.Library.Data;
var (used, measuring) = d.Sizes.Get(data.Root);
var now = d.Clock.Now;
var zone = d.Clock.LocalZone;
var backups = new DailyBackup(d.Storage.Maintenance, d.Clock, data.Backups).List()
.Select(b => new BackupDto(
ApiMapping.Day(b.Day),
Path.GetFileName(b.Path),
b.Bytes,
ApiMapping.Local(new DateTimeOffset(File.GetLastWriteTimeUtc(b.Path), TimeSpan.Zero), now, zone)))
.ToList();
long? databaseBytes = null;
var database = d.Storage.Maintenance.DatabasePath;
try
{
databaseBytes = new FileInfo(database).Length + (File.Exists(database + "-wal") ? new FileInfo(database + "-wal").Length : 0);
}
catch (IOException)
{
// size unknown
}
return new DataSettingsDto(
new FolderInfoDto(data.Root, FolderSizes.FreeBytes(data.Root), used, measuring),
database,
databaseBytes,
data.Backups,
backups,
DailyBackup.DefaultKeepDays,
Rebuild(d.Rebuild.State, d.Clock));
}
public static RebuildStatusDto Rebuild(RebuildState state, IClock clock)
{
ArgumentNullException.ThrowIfNull(state);
ArgumentNullException.ThrowIfNull(clock);
var lines = new List<string>();
if (state.Report is { } r)
{
lines.Add($"Cartelle di account lette: {ItalianText.Number(r.AccountFolders)}.");
lines.Add($"Account ritrovati: {ItalianText.Number(r.AccountsMatched)}; ricreati: {ItalianText.Number(r.AccountsCreated)}"
+ (r.AccountsCreated > 0 ? " (sono «In pausa»: riattivali dalla pagina Account)." : "."));
lines.Add($"Elementi aggiunti al database: {ItalianText.Number(r.EntriesCreated)}; già presenti: {ItalianText.Number(r.EntriesAlreadyPresent)}; eliminazioni rispettate: {ItalianText.Number(r.EntriesDeleted)}.");
lines.Add($"File controllati: {ItalianText.Number(r.FilesVerified)}; mancanti sul disco: {ItalianText.Number(r.FilesMissing)}; diversi da quanto annotato: {ItalianText.Number(r.HashMismatches)}; non annotati nel giornale: {ItalianText.Number(r.UntrackedFiles)}.");
if (r.InvalidLines > 0)
{
lines.Add($"Righe illeggibili nei file _febe.jsonl: {ItalianText.Number(r.InvalidLines)}.");
}
if (r.FoldersWithoutJournal.Count > 0)
{
lines.Add($"Cartelle senza _febe.jsonl, non lette: {string.Join(", ", r.FoldersWithoutJournal.Take(20))}{(r.FoldersWithoutJournal.Count > 20 ? "…" : string.Empty)}. Per portarle in libreria usa Importa.");
}
lines.AddRange(r.Notes);
}
return new RebuildStatusDto(
state.Running,
state.Folder,
state.FoldersDone,
state.FoldersTotal,
state.FilesChecked,
lines,
state.Error is null ? null : $"La ricostruzione si è fermata: {state.Error}. Nessun file è stato toccato; puoi riprovare.",
state.FinishedAt is { } at ? ApiMapping.Local(at, clock.Now, clock.LocalZone) : null);
}
// ---------------------------------------------------------------------------------------------- helpers
private static bool SamePath(string a, string b) =>
string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(a)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
private static bool IsSameOrInside(string path, string folder)
{
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
var p = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
var f = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
return string.Equals(p, f, comparison) || p.StartsWith(f + Path.DirectorySeparatorChar, comparison);
}
/// <summary>The services the settings endpoints share.</summary>
public sealed record Deps(
IServiceProvider Services,
FebeWebOptions Options,
IFebeStorage Storage,
FebeLibrary Library,
IClock Clock,
INativeShell Shell,
IBrowserWindow Browser,
FolderSizes Sizes,
RebuildJob Rebuild,
ImportHub Import,
LibraryChanges Changes)
{
public static Deps From(IServiceProvider services)
{
ArgumentNullException.ThrowIfNull(services);
T Get<T>() where T : notnull => (T)(services.GetService(typeof(T)) ?? throw new InvalidOperationException(typeof(T).Name + " non è registrato."));
return new Deps(services, Get<FebeWebOptions>(), Get<IFebeStorage>(), Get<FebeLibrary>(), Get<IClock>(), Get<INativeShell>(), Get<IBrowserWindow>(), Get<FolderSizes>(), Get<RebuildJob>(), Get<ImportHub>(), Get<LibraryChanges>());
}
}
}
+4 -1
View File
@@ -2,12 +2,14 @@ using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
using Febe.Web.Connection;
using Febe.Web.Demo;
using Febe.Web.Hosting;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Web.Api;
@@ -77,7 +79,8 @@ public static class SystemApi
options.Demo ? DemoRequest.SceneName(DemoRequest.Scene(context)) : null,
options.Demo ? DemoRequest.SceneNames : [],
clock.Now.ToUnixTimeMilliseconds(),
ApiMapping.Day(LocalCalendar.Today(clock.Now, clock.LocalZone)));
ApiMapping.Day(LocalCalendar.Today(clock.Now, clock.LocalZone)),
context.RequestServices.GetService<IConfigurationProblems>()?.Current ?? []);
}
/// <summary>The sprite: each Lucide file's drawing inside a symbol; stroke and fill come from the CSS of <c>svg.ic</c>.</summary>