Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account

Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi.

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 19:14:35 +00:00
1 parent 6ff11ac8e3
commit e33540246e
76 files changed
+12503 -17

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 676 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 454 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 658 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 534 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

+47
View File
@@ -0,0 +1,47 @@
# Schermate dell'interfaccia e differenze dai mockup
Schermate prese il 13 ottobre 2026 dalla modalità dimostrativa (`dotnet run --project src/Febe.Server -- --demo`),
con Chromium senza finestra a 1440 × 900 in scala 1,25 (come i mockup), salvo dove indicato. Il senza finestra si usa
solo per l'interfaccia di Febe (§10.7).
| Schermata | Indirizzo | Mockup |
|---|---|---|
| `01-libreria.png` | `/libreria?tema=chiaro`, puntatore su una tessera | `docs/mockup/01-libreria.png` |
| `02-visualizzatore.png` | `/libreria`, clic su un post con più file, seconda foto | `miniature/02-visualizzatore.png` |
| `03-account.png` | `/account?tema=chiaro` | `docs/mockup/03-account.png` |
| `03-account-telefono.png` | `/account`, 390 × 844 | (nessuno: tabella come elenco) |
| `04-aggiungi-account.png` | `/account?dialogo=aggiungi`, tre profili scelti | `miniature/04-aggiungi-account.png` |
| `05-account-impostazioni.png` | `/account/3/impostazioni` (@studio.lumen.demo) | `miniature/05-account-impostazioni.png` |
| `11-libreria-fermo-tema-scuro.png` | `/libreria?scena=fermo&tema=scuro` | striscia rossa di `miniature/11-attivita-fermo-tema-scuro.png` |
| `12-account-storie-tema-scuro.png` | `/account/2?tema=scuro&tipo=storie` (@marta.demo) | `miniature/12-account-storie-tema-scuro.png` |
| `14-finestra-stretta.png` | `/libreria`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività al telefono) |
| `account-cronologia.png` | `/account/2/cronologia` | (nessuno) |
## Differenze che restano
Disposizione, gerarchia, misure delle colonne, testi e colori corrispondono. Restano queste differenze, volute o
dovute ai dati dimostrativi:
- **Contenuti dimostrativi.** Immagini, orari, conteggi e ordine delle righe vengono dalla libreria finta generata a
ogni avvio (ora reale del computer), quindi non coincidono con quelli disegnati: ad esempio «18.274 elementi di 37
account» invece di «48.212 elementi di 38 account» (un account non raggiungibile non ha elementi), e oggi ci sono
più storie verticali che nel mockup.
- **Libreria, intestazione dei giorni.** Anche «Ieri» mostra quanti elementi ha («lunedì 12 ottobre, 61 elementi»);
nel mockup il numero c'è solo per «Oggi». Tenuto: l'informazione è utile e coerente con gli altri giorni.
- **Libreria, tessere.** Il segno della storia (cerchio tratteggiato) compare su tutte le storie; nel mockup su poche
perché i dati sono diversi. La tessera con il puntatore sopra mostra avatar, nome e ora come nel mockup.
- **Avatar.** I colori di fondo delle iniziali sono più scuri di quelli del mockup, per avere contrasto di almeno 4,5:1
con il testo bianco (§10.5).
- **Visualizzatore.** La scheda mostra anche «Codice» e «Posizione» del file; il nome del file va a capo quando è
lungo (nel mockup sta su una riga perché il nome disegnato è più corto). Il segno «Profilo privato» compare solo per
gli account privati.
- **Account.** L'ordine delle righe segue l'ultimo controllo reale dei dati dimostrativi; nel mockup i tempi sono
«8 min fa», «12 min fa». Con nuovi post e nuove storie insieme la riga dice «1 nuovo post e 2 nuove storie oggi».
- **Scheda account, impostazioni.** La cartella mostra il percorso della cartella temporanea della dimostrazione.
Il riquadro «Con queste impostazioni» usa i testi del calcolatore del motore, più lunghi di quelli del mockup.
- **Storie in tema scuro.** Le tessere delle storie non hanno l'anello attorno all'elemento scelto: nel mockup c'è
una tessera selezionata, qui la schermata è senza selezione.
- **Telefono.** Il mockup del telefono mostra la pagina Attività, che fa parte della seconda metà dell'interfaccia;
qui c'è la libreria. I filtri a pastiglia vanno a capo su due righe.
- **Pagine non ancora fatte.** Attività, Importa, Impostazioni e Browser mostrano un segnaposto: sono della parte 2.
+13 -4
View File
@@ -19,6 +19,14 @@ public sealed record AccountPlanInput
public int ArchivedPosts { get; init; }
public EngineOptions Options { get; init; } = EngineOptions.Default;
/// <summary>
/// Start of the gradual start in force (<c>motore.avvio-graduale-dal</c>) and the current time: the warning about
/// halved budgets is given only while the ramp lasts. Null (unknown) keeps the warning.
/// </summary>
public DateTimeOffset? GradualStartSince { get; init; }
public DateTimeOffset? Now { get; init; }
}
/// <summary>A line of the panel: «Nuovi post» — «controllati ogni 3 ore circa, tra le 7:30 e le 23:30».</summary>
@@ -160,8 +168,8 @@ public static class AccountPlanCalculator
if (overBudget)
{
warnings.Add(
$"Con {ItalianText.Count(contactable.Count, "account", "account")} e queste frequenze servirebbero circa {ItalianText.Number((long)Math.Round(totalDemand))} aperture di profili al giorno, "
+ $"ma il tetto è {ItalianText.Number(budget)}: i controlli si diradano (circa {ItalianText.Decimal(thinning, 1)} volte più radi), non si forzano.");
$"Con {ItalianText.Count(contactable.Count, "account", "account")} e queste frequenze servirebbero circa {ItalianText.Number((long)Math.Ceiling(totalDemand))} aperture di profili al giorno, "
+ $"ma il tetto è {ItalianText.Number(budget)}: i controlli si diradano ({(thinning < 1.15 ? "un po' più radi" : $"circa {ItalianText.Decimal(thinning, 1)} volte più radi")}), non si forzano.");
}
var sessionsPerDay = SessionsPerDay(profile, window);
@@ -171,7 +179,8 @@ public static class AccountPlanCalculator
warnings.Add($"Il tetto della home ({ItalianText.Number(homeBudget)} al giorno) è più basso del numero di sessioni: alcuni giri dei seguiti salteranno e i nuovi post arriveranno più tardi.");
}
if (profile.GradualStart && profile.RampUpDays > 0)
var rampOver = input.GradualStartSince is { } since && input.Now is { } at && at - since >= TimeSpan.FromDays(profile.RampUpDays);
if (profile.GradualStart && profile.RampUpDays > 0 && !rampOver)
{
warnings.Add($"Con l'avvio graduale, nei primi {ItalianText.Count(profile.RampUpDays, "giorno", "giorni")} dopo il collegamento i tetti partono dalla metà: tutto è più lento.");
}
@@ -292,7 +301,7 @@ public static class AccountPlanCalculator
var days = (int)Math.Ceiling(remaining / perDay);
var text = $"mancano {ItalianText.Count(remaining, "post", "post")}, servono circa {ItalianText.Count(days, "giorno", "giorni")} ({ItalianText.Number((long)Math.Floor(perDay))} post al giorno"
+ (sharing > 1 ? $", a turno con altri {ItalianText.Number(sharing - 1)} account" : string.Empty) + ").";
+ (sharing switch { <= 1 => string.Empty, 2 => ", a turno con un altro account", _ => $", a turno con altri {ItalianText.Number(sharing - 1)} account" }) + ").";
return (text, remaining, days);
}
+122
View File
@@ -0,0 +1,122 @@
using System.Globalization;
using System.Runtime.InteropServices;
using Febe.Web;
using Febe.Web.Demo;
namespace Febe.Server;
/// <summary>
/// <c>--demo [--porta 8480] [--fuso Europe/Rome]</c> (spec §10.6): the interface with demo data, without browser and
/// without network, on 127.0.0.1 only and without password. Everything lives in a temporary folder that is removed
/// at the end (Ctrl+C). Exit code 0 at the end, 2 for wrong arguments.
/// </summary>
internal static class DemoCommand
{
public const string Flag = "--demo";
public static bool Matches(string[] args) => args.Any(a => string.Equals(a, Flag, StringComparison.OrdinalIgnoreCase));
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error)
{
if (!TryParse(args, out var options, out var problem))
{
await error.WriteLineAsync(problem).ConfigureAwait(false);
await error.WriteLineAsync("Uso: --demo [--porta 8480] [--fuso Europe/Rome]").ConfigureAwait(false);
return 2;
}
using var stop = new CancellationTokenSource();
ConsoleCancelEventHandler onCancel = (_, e) =>
{
e.Cancel = true;
stop.Cancel();
};
Console.CancelKeyPress += onCancel;
// A container or a service manager stops with SIGTERM: the temporary folder must go away then too.
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, context =>
{
context.Cancel = true;
stop.Cancel();
});
try
{
await output.WriteLineAsync("Febe, modalità dimostrativa: preparo una libreria finta in una cartella temporanea…").ConfigureAwait(false);
DemoHost demo;
try
{
demo = await DemoHost.StartAsync(options, stop.Token).ConfigureAwait(false);
}
catch (IOException ex) when (ex.InnerException is not null || ex.Message.Contains("address", StringComparison.OrdinalIgnoreCase))
{
await error.WriteLineAsync($"La porta {options.Port} è già occupata: chiudi l'altro programma che la usa, oppure scegline un'altra con --porta.").ConfigureAwait(false);
return 1;
}
await using var running = demo;
var address = new Uri(demo.Address, "/libreria");
await output.WriteLineAsync($"Pronto: {demo.World.Accounts} account e {Febe.Core.Engine.ItalianText.Number(demo.World.Entries)} elementi dimostrativi.").ConfigureAwait(false);
await output.WriteLineAsync($"Apri {address}").ConfigureAwait(false);
await output.WriteLineAsync("Scene: ?scena=normale, sessione, fermo, scollegato; tema: ?tema=chiaro o scuro; veste: ?veste=desktop o docker.").ConfigureAwait(false);
await output.WriteLineAsync("Premi Ctrl+C per chiudere: la cartella temporanea viene cancellata.").ConfigureAwait(false);
try
{
await Task.Delay(Timeout.Infinite, stop.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
await output.WriteLineAsync("Chiudo la dimostrazione.").ConfigureAwait(false);
return 0;
}
finally
{
Console.CancelKeyPress -= onCancel;
}
}
internal static bool TryParse(string[] args, out DemoOptions options, out string problem)
{
var port = FebeListen.DefaultPort;
TimeZoneInfo? zone = null;
problem = string.Empty;
options = new DemoOptions();
for (var i = 0; i < args.Length; i++)
{
switch (args[i].ToLowerInvariant())
{
case Flag:
break;
case "--porta" when i + 1 < args.Length:
if (!int.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port) || port is < 0 or > 65535)
{
problem = "Porta non valida: un numero fra 1 e 65535.";
return false;
}
break;
case "--fuso" when i + 1 < args.Length:
try
{
zone = TimeZoneInfo.FindSystemTimeZoneById(args[++i]);
}
catch (TimeZoneNotFoundException)
{
problem = $"Fuso orario sconosciuto: {args[i]}.";
return false;
}
break;
default:
problem = $"Opzione sconosciuta: {args[i]}.";
return false;
}
}
// Development: FEBE_INTERFACCIA=src/Febe.Web/wwwroot serves the pages from the sources (edit, reload).
var folder = Environment.GetEnvironmentVariable("FEBE_INTERFACCIA");
options = new DemoOptions(port, zone, null, string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder) ? null : folder);
return true;
}
}
+8 -1
View File
@@ -1,11 +1,18 @@
// Composition root for Linux and Docker. Filled in by milestones M3–M5.
using Febe.Server;
Console.OutputEncoding = System.Text.Encoding.UTF8;
if (SimulateCommand.Matches(args))
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
return await SimulateCommand.RunAsync(args, Console.Out, Console.Error);
}
if (DemoCommand.Matches(args))
{
return await DemoCommand.RunAsync(args, Console.Out, Console.Error);
}
Console.WriteLine("Febe");
Console.WriteLine("Comandi: --demo (interfaccia con dati dimostrativi), --simula 30g --profilo prudente (simulazione del motore).");
return 0;
+64
View File
@@ -0,0 +1,64 @@
using Febe.Web.Security;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Web.Api;
/// <summary>Login and logout of the Docker interface (spec §13.1). The page is <c>/accesso</c> (wwwroot/accesso.html).</summary>
public static class AccessApi
{
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/accesso", (HttpContext context) =>
{
var options = context.RequestServices.GetRequiredService<FebeWebOptions>();
var files = options.InterfaceFolder is { Length: > 0 } folder ? new Hosting.EmbeddedWwwroot(folder) : new Hosting.EmbeddedWwwroot();
var page = files.ReadText("accesso.html") ?? "Febe";
context.Response.Headers.CacheControl = "no-cache";
return Results.Text(page, "text/html; charset=utf-8");
});
endpoints.MapPost("/api/accesso", async (HttpContext context, FebeWebOptions options) =>
{
var passwords = context.RequestServices.GetService<PasswordAccess>();
if (options.Access != AccessMode.Password || passwords is null)
{
return ApiHttp.Json(new LoginDto(true, "Qui non serve una password.", null), FebeJsonContext.Default.LoginDto);
}
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.LoginRequest).ConfigureAwait(false);
var client = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
var result = passwords.TryLogin(body.Password, client);
switch (result.Status)
{
case LoginStatus.Accepted:
context.Response.Cookies.Append(PasswordAccess.CookieName, result.SessionId!, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = context.Request.IsHttps,
Path = "/",
IsEssential = true,
MaxAge = passwords.SessionLifetime,
});
return ApiHttp.Json(new LoginDto(true, "Accesso riuscito.", null), FebeJsonContext.Default.LoginDto);
case LoginStatus.Locked:
return ApiHttp.Json(
new LoginDto(false, "Troppi tentativi sbagliati: l'accesso è bloccato per qualche minuto. Riprova più tardi.", result.LockedUntil?.ToUnixTimeMilliseconds()),
FebeJsonContext.Default.LoginDto,
StatusCodes.Status429TooManyRequests);
default:
return ApiHttp.Json(new LoginDto(false, "Password sbagliata.", null), FebeJsonContext.Default.LoginDto, StatusCodes.Status401Unauthorized);
}
});
endpoints.MapPost("/api/uscita", (HttpContext context) =>
{
context.RequestServices.GetService<PasswordAccess>()?.Logout(context.Request.Cookies[PasswordAccess.CookieName]);
context.Response.Cookies.Delete(PasswordAccess.CookieName, new CookieOptions { Path = "/", SameSite = SameSiteMode.Strict, HttpOnly = true });
return ApiHttp.Message("Sei uscito da Febe.");
});
}
}
+199
View File
@@ -0,0 +1,199 @@
using System.Globalization;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
namespace Febe.Web.Api;
/// <summary>The settings of an account (spec §4.4, mockup 05) between the domain and the form of the page.</summary>
public static class AccountSettingsMapper
{
public const double MinCustomPostHours = 1;
public const double MaxCustomPostHours = 48;
public const double MinCustomStoryHours = 1;
public const double MaxCustomStoryHours = 24;
/// <summary>Largest «Storico, massimo al giorno» the form accepts: twice the «Rapido» value (spec §7.5).</summary>
public static int MaxBackfillPerDay => CautionProfile.Fast.BackfillPostsPerAccountPerDay * 2;
public static AccountSettingsDto ToDto(Account account)
{
ArgumentNullException.ThrowIfNull(account);
var reference = account with { IsFollowed = false, Frequency = account.Frequency == Frequency.Custom ? Frequency.Custom : account.Frequency };
return new AccountSettingsDto(
account.KeepUpdated,
ApiMapping.Frequency(account.Frequency),
Math.Round((account.CustomPostInterval ?? CheckPolicy.ProfileCheckInterval(reference)).TotalHours, 2),
Math.Round((account.CustomStoryInterval ?? CheckPolicy.StoryMaxInterval(reference)).TotalHours, 2),
ApiMapping.Types(account.ContentTypes),
ApiMapping.Depth(account.Limits.Depth),
account.Limits.LastPosts,
account.Limits.FromDate is { } from ? from.UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : null,
account.Limits.BackfillPostsPerDay,
account.Limits.MaxVideoBytes is { } bytes ? Math.Round(bytes / 1024d / 1024d, 1) : null,
account.Limits.StoryVideos,
account.Folder);
}
/// <summary>
/// Applies the form to an account, with Italian errors for values out of range. «Tieni aggiornato» moves the state:
/// off on an up-to-date account pauses it (the single download is done), on reactivates a paused one.
/// </summary>
/// <param name="account">The stored account.</param>
/// <param name="dto">The form.</param>
/// <param name="zone">Alberto's zone (dates of «Da una data»).</param>
/// <param name="now">Now (state change time).</param>
/// <param name="folder">The folder value already resolved by the caller (null: default).</param>
public static Account Apply(Account account, AccountSettingsDto dto, TimeZoneInfo zone, DateTimeOffset now, string? folder)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(dto);
ArgumentNullException.ThrowIfNull(zone);
var frequency = ApiMapping.ParseFrequency(dto.Frequency) ?? throw new BadRequestException("Frequenza sconosciuta.");
TimeSpan? customPost = account.CustomPostInterval;
TimeSpan? customStory = account.CustomStoryInterval;
if (frequency == Frequency.Custom)
{
if (dto.CustomPostHours is not { } postHours || double.IsNaN(postHours) || postHours < MinCustomPostHours || postHours > MaxCustomPostHours)
{
throw new BadRequestException($"Su misura: i post si controllano fra ogni {Number(MinCustomPostHours)} e ogni {Number(MaxCustomPostHours)} ore.");
}
if (dto.CustomStoryHours is not { } storyHours || double.IsNaN(storyHours) || storyHours < MinCustomStoryHours || storyHours > MaxCustomStoryHours)
{
throw new BadRequestException($"Su misura: fra due controlli delle storie passano da {Number(MinCustomStoryHours)} a {Number(MaxCustomStoryHours)} ore.");
}
customPost = TimeSpan.FromMinutes(Math.Round(postHours * 60));
customStory = TimeSpan.FromMinutes(Math.Round(storyHours * 60));
}
var types = ApiMapping.Types(dto.Types ?? throw new BadRequestException("Manca «Cosa scaricare»."));
var depth = ApiMapping.ParseDepth(dto.Depth) ?? throw new BadRequestException("«Quanto indietro nel tempo» non valido.");
int? lastPosts = null;
DateTimeOffset? fromDate = null;
if (depth == HistoryDepth.LastPosts)
{
if (dto.LastPosts is not { } n || n < 1 || n > 1_000_000)
{
throw new BadRequestException("Indica quanti post tenere: almeno 1.");
}
lastPosts = n;
}
else if (depth == HistoryDepth.FromDate)
{
var day = ApiMapping.ParseDay(dto.FromDate) ?? throw new BadRequestException("Indica la data da cui partire.");
if (day > LocalCalendar.Today(now, zone))
{
throw new BadRequestException("La data da cui partire non può essere nel futuro.");
}
fromDate = LocalCalendar.StartOfDay(day, zone);
}
if (dto.BackfillPerDay < 1 || dto.BackfillPerDay > MaxBackfillPerDay)
{
throw new BadRequestException($"Storico, massimo al giorno: fra 1 e {ItalianText.Number(MaxBackfillPerDay)} post.");
}
long? maxVideo = null;
if (dto.MaxVideoMb is { } mb)
{
if (double.IsNaN(mb) || mb < 1 || mb > 100_000)
{
throw new BadRequestException("Salta i video oltre: un numero di MB da 1 in su, oppure vuoto per nessun limite.");
}
maxVideo = (long)Math.Round(mb * 1024 * 1024);
}
var state = account.State;
var changedAt = account.StateChangedAt;
if (account.KeepUpdated && !dto.KeepUpdated && state == AccountState.UpToDate)
{
state = AccountState.Paused;
changedAt = now;
}
else if (!account.KeepUpdated && dto.KeepUpdated && state == AccountState.Paused)
{
state = ReactivatedState(account, depth);
changedAt = now;
}
return account with
{
KeepUpdated = dto.KeepUpdated,
Frequency = frequency,
CustomPostInterval = customPost,
CustomStoryInterval = customStory,
ContentTypes = types,
Limits = account.Limits with
{
Depth = depth,
LastPosts = lastPosts,
FromDate = fromDate,
BackfillPostsPerDay = dto.BackfillPerDay,
MaxVideoBytes = maxVideo,
StoryVideos = dto.StoryVideos,
},
Folder = folder,
State = state,
StateChangedAt = changedAt,
};
}
/// <summary>State of a paused account that comes back: backfilling while its history is not complete.</summary>
public static AccountState ReactivatedState(Account account, HistoryDepth? depth = null)
{
ArgumentNullException.ThrowIfNull(account);
var d = depth ?? account.Limits.Depth;
return account.BackfillCompletedAt is null && d != HistoryDepth.FromDate && CheckPolicy.WantsProfileChecks(account)
? AccountState.Backfilling
: AccountState.UpToDate;
}
/// <summary>«Nuovi post ogni 3 ore circa, storie almeno ogni 6 ore» beside the frequency buttons.</summary>
public static string FrequencyHint(Account account)
{
ArgumentNullException.ThrowIfNull(account);
var parts = new List<string>();
if (CheckPolicy.WantsProfileChecks(account))
{
parts.Add(account.IsFollowed
? "nuovi post dal giro dei profili che segui, profilo riaperto " + ItalianText.Every(CheckPolicy.ProfileCheckInterval(account))
: "nuovi post " + ItalianText.Every(CheckPolicy.ProfileCheckInterval(account)) + " circa");
}
if (CheckPolicy.WantsStories(account))
{
parts.Add("storie almeno " + ItalianText.Every(CheckPolicy.StoryMaxInterval(account)));
}
return parts.Count == 0 ? "Niente da controllare con queste scelte." : ItalianText.Capitalize(string.Join(", ", parts));
}
/// <summary>The note under the panel: what being followed or not means for this account.</summary>
public static string? Note(Account account)
{
ArgumentNullException.ThrowIfNull(account);
if (account.State == AccountState.ArchiveOnly || account.IsMine)
{
return null;
}
if (!account.IsFollowed && !account.IsPrivate)
{
return "È un profilo pubblico che non segui: per vedere le novità Febe deve aprire la sua pagina. Se diventa privato, Febe si ferma e ti avvisa.";
}
if (account.IsFollowed)
{
return "Lo segui: le novità arrivano dal giro dei profili che segui, senza aprire ogni volta la sua pagina.";
}
return null;
}
private static string Number(double value) => ItalianText.Decimal(value, 1);
}
+617
View File
@@ -0,0 +1,617 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web.Engine;
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>Accounts (spec §4.2, §4.4, §7.8; mockups 03, 04, 05, 12).</summary>
public static class AccountsApi
{
public static void Map(IEndpointRouteBuilder endpoints)
{
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.MapPost("/api/accounts/{id:long}/plan", async (long id, HttpContext context, IFebeStorage storage, 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 edited = AccountSettingsMapper.Apply(account, body, clock.LocalZone, clock.Now, account.Folder);
return ApiHttp.Json(await PlanAsync(storage, edited, clock.Now, ct).ConfigureAwait(false), FebeJsonContext.Default.PlanDto);
});
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) =>
{
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 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);
});
// «Tieni aggiornato» of the table: acts at once.
endpoints.MapPost("/api/accounts/{id:long}/keep-updated", async (long id, HttpContext context, IFebeStorage storage, IEngineControl engine, 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);
if (account.State == AccountState.ArchiveOnly)
{
throw new BadRequestException($"{ItalianText.Handle(account.Username)} è «Solo archivio»: Febe non lo contatta.");
}
var edited = AccountSettingsMapper.Apply(account, AccountSettingsMapper.ToDto(account) with { KeepUpdated = body.Value }, clock.LocalZone, clock.Now, account.Folder);
await storage.Accounts.UpdateAsync(edited, ct).ConfigureAwait(false);
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, id, "account"));
return ApiHttp.Message(body.Value
? $"{ItalianText.Handle(account.Username)} si tiene aggiornato."
: $"{ItalianText.Handle(account.Username)} non si tiene più aggiornato.");
});
endpoints.MapPost("/api/accounts/{id:long}/pause", async (long id, IFebeStorage storage, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var account = await GetAsync(storage, id, ct).ConfigureAwait(false);
if (account.State is AccountState.ArchiveOnly or AccountState.Paused)
{
throw new BadRequestException($"{ItalianText.Handle(account.Username)} non è attivo: non c'è nulla da mettere in pausa.");
}
await storage.Accounts.UpdateAsync(account with { State = AccountState.Paused, StateChangedAt = clock.Now, KeepUpdated = false }, ct).ConfigureAwait(false);
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, id, "account"));
return ApiHttp.Message($"{ItalianText.Handle(account.Username)} in pausa: Febe non lo controlla finché non lo riattivi.");
});
endpoints.MapPost("/api/accounts/{id:long}/resume", async (long id, IFebeStorage storage, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var account = await GetAsync(storage, id, ct).ConfigureAwait(false);
if (account.State != AccountState.Paused)
{
throw new BadRequestException($"{ItalianText.Handle(account.Username)} non è in pausa.");
}
await storage.Accounts.UpdateAsync(account with { State = AccountSettingsMapper.ReactivatedState(account), StateChangedAt = clock.Now, KeepUpdated = true }, ct).ConfigureAwait(false);
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, id, "account"));
return ApiHttp.Message($"{ItalianText.Handle(account.Username)} di nuovo attivo.");
});
endpoints.MapPost("/api/accounts/{id:long}/check-now", async (long id, HttpContext context, IEngineControl engine, CancellationToken ct) =>
{
var body = context.Request.ContentLength is > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CheckNowRequest).ConfigureAwait(false)
: new CheckNowRequest(null);
var result = await engine.CheckNowAsync(id, body.Token, ct).ConfigureAwait(false);
var status = result.Status switch
{
CheckNowStatus.Queued => "queued",
CheckNowStatus.NeedsConfirmation => "needsConfirmation",
_ => "refused",
};
return ApiHttp.Json(new CheckNowDto(status, result.Message, result.ConfirmationToken), FebeJsonContext.Default.CheckNowDto);
});
endpoints.MapPost("/api/accounts/{id:long}/remove", async (long id, HttpContext context, IFebeStorage storage, FebeLibrary library, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.RemoveAccountRequest).ConfigureAwait(false);
var result = await RemoveAsync(id, body.DeleteFiles, storage, library, clock, ct).ConfigureAwait(false);
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, id, "account"));
return ApiHttp.Json(result, FebeJsonContext.Default.RemoveAccountDto);
});
endpoints.MapGet("/api/accounts/{id:long}/history", async (long id, HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
_ = await GetAsync(storage, id, ct).ConfigureAwait(false);
long? before = long.TryParse(context.Request.Query["before"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var b) ? b : null;
var events = await storage.Events.ListAsync(new EventQuery { AccountId = id, BeforeId = before, Limit = 100 }, ct).ConfigureAwait(false);
var items = events.Select(e => new HistoryItemDto(e.Id, ApiMapping.Local(e.At, clock.Now, clock.LocalZone), e.Severity.ToString().ToLowerInvariant(), e.Code, e.Message)).ToList();
return ApiHttp.Json(new HistoryDto(items, items.Count == 100 ? items[^1].Id : null), FebeJsonContext.Default.HistoryDto);
});
endpoints.MapPost("/api/accounts/{id:long}/pick-folder", async (long id, HttpContext context, IFebeStorage storage, FebeLibrary library, INativeShell shell, CancellationToken ct) =>
{
var account = await GetAsync(storage, id, ct).ConfigureAwait(false);
if (!shell.CanPickFolder)
{
throw new BadRequestException("Qui le cartelle si cambiano dal contenitore, non dall'interfaccia.");
}
var picked = await shell.PickFolderAsync($"Cartella di {ItalianText.Handle(account.Username)}", library.Layout.AccountFolder(account), ct).ConfigureAwait(false);
return ApiHttp.Json(new MessageDto(picked ?? string.Empty), FebeJsonContext.Default.MessageDto);
});
endpoints.MapPost("/api/accounts/{id:long}/open-on-instagram", async (long id, IFebeStorage storage, INativeShell shell, CancellationToken ct) =>
{
var account = await GetAsync(storage, id, ct).ConfigureAwait(false);
if (!await shell.OpenUrlAsync(new Uri(InstagramLinks.Profile(account.Username)), ct).ConfigureAwait(false))
{
throw new BadRequestException("Qui il collegamento si apre direttamente dalla pagina.");
}
return ApiHttp.Message("Aperto nel tuo browser.");
});
endpoints.MapGet("/api/following", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await FollowingAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.FollowingDto));
endpoints.MapPost("/api/following/read", async (IFebeStorage storage, IEngineControl engine, IClock clock, CancellationToken ct) =>
{
await engine.RequestFollowingListAsync(ct).ConfigureAwait(false);
return ApiHttp.Json(await FollowingAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.FollowingDto);
});
endpoints.MapPost("/api/accounts/parse", async (HttpContext context, IFebeStorage storage, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ParseRequest).ConfigureAwait(false);
return ApiHttp.Json(await ParseAsync(storage, body.Text, ct).ConfigureAwait(false), FebeJsonContext.Default.ParseResultDto);
});
endpoints.MapPost("/api/accounts", async (HttpContext context, IFebeStorage storage, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AddAccountsRequest).ConfigureAwait(false);
var result = await AddAsync(storage, body, clock, ct).ConfigureAwait(false);
if (result.Added > 0)
{
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, null, "account"));
}
return ApiHttp.Json(result, FebeJsonContext.Default.AddAccountsDto);
});
}
// ------------------------------------------------------------------------------------------ list and detail
public static async Task<AccountListDto> ListAsync(IFebeStorage storage, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
var now = clock.Now;
var zone = clock.LocalZone;
var (todayStart, todayEnd) = LocalCalendar.DayBounds(now, zone);
var summaries = await storage.Accounts.ListSummariesAsync(todayStart, ct).ConfigureAwait(false);
var avatars = await AvatarsAsync(storage, ct).ConfigureAwait(false);
var profile = (await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).EffectiveProfile;
var rows = new List<AccountRowDto>(summaries.Count);
foreach (var summary in summaries)
{
var resumesTomorrow = false;
if (summary.Account.State == AccountState.Backfilling)
{
var today = await storage.Entries.CountDiscoveredAsync(summary.Account.Id, EntryKind.Post, todayStart, todayEnd, ct).ConfigureAwait(false);
resumesTomorrow = today >= Math.Min(summary.Account.Limits.BackfillPostsPerDay, profile.BackfillPostsPerAccountPerDay);
}
rows.Add(Row(summary.Account, summary, avatars.GetValueOrDefault(summary.Account.Id), resumesTomorrow, now, zone));
}
var counts = new AccountCountsDto(
rows.Count,
rows.Count(r => r.State == "upToDate"),
rows.Count(r => r.State == "backfilling"),
rows.Count(r => r.State == "paused"),
rows.Count(r => r.State == "archiveOnly"),
rows.Count(r => r.NeedsAttention),
rows.Count(r => r.KeptUpdated));
return new AccountListDto(now.ToUnixTimeMilliseconds(), counts, rows);
}
public static AccountRowDto Row(Account account, AccountSummary? summary, string? avatar, bool resumesTomorrow, DateTimeOffset now, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(account);
var last = Max(account.LastProfileCheckAt, account.LastStoriesCheckAt);
DateTimeOffset? next = CheckPolicy.IsContactable(account) ? Min(account.NextProfileCheckAt, account.NextStoriesCheckAt) : null;
if (next is { } n && n < now)
{
next = now;
}
var notices = new List<string>();
if ((account.Notices & AccountNotices.Renamed) != 0)
{
notices.Add("renamed");
}
if ((account.Notices & AccountNotices.UnrecognizedFormat) != 0)
{
notices.Add("unrecognizedFormat");
}
return new AccountRowDto(
account.Id,
account.Username,
account.DisplayName,
account.IsPrivate,
account.IsFollowed,
account.IsMine,
ApiMapping.State(account.State),
account.UnreachableReason switch
{
UnreachableReason.PrivateNotFollowed => "privateNotFollowed",
UnreachableReason.NotFound => "notFound",
UnreachableReason.Blocked => "blocked",
UnreachableReason.Renamed => "renamed",
_ => null,
},
account.NeedsAttention,
notices,
account.KeepUpdated,
account.KeepUpdated && account.State is AccountState.UpToDate or AccountState.Backfilling,
ApiMapping.Frequency(account.Frequency),
ApiMapping.Types(account.ContentTypes),
summary?.EntriesInLibrary ?? 0,
summary?.Posts ?? 0,
account.PostCount,
summary?.NewPostsSince ?? 0,
summary?.NewStoriesSince ?? 0,
resumesTomorrow,
last?.ToUnixTimeMilliseconds(),
next is { } nx ? ApiMapping.Local(nx, now, zone) : null,
account.StateChangedAt is { } changed ? ApiMapping.Local(changed, now, zone) : null,
account.AddedAt.ToUnixTimeMilliseconds(),
avatar,
account.PreviousUsername);
}
public static async Task<AccountDetailDto> DetailAsync(long id, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(library);
ArgumentNullException.ThrowIfNull(clock);
var account = await GetAsync(storage, id, ct).ConfigureAwait(false);
var now = clock.Now;
var zone = clock.LocalZone;
var (todayStart, todayEnd) = LocalCalendar.DayBounds(now, zone);
var summaries = await storage.Accounts.ListSummariesAsync(todayStart, ct).ConfigureAwait(false);
var summary = summaries.FirstOrDefault(s => s.Account.Id == id);
var stats = await storage.Accounts.GetStatsAsync(id, ct).ConfigureAwait(false);
var avatar = await AvatarAsync(storage, id, ct).ConfigureAwait(false);
var resumesTomorrow = false;
if (account.State == AccountState.Backfilling)
{
var profile = (await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).EffectiveProfile;
var today = await storage.Entries.CountDiscoveredAsync(id, EntryKind.Post, todayStart, todayEnd, ct).ConfigureAwait(false);
resumesTomorrow = today >= Math.Min(account.Limits.BackfillPostsPerDay, profile.BackfillPostsPerAccountPerDay);
}
var highlights = new List<HighlightDto>();
foreach (var highlight in await storage.Highlights.ListAsync(id, includeRemoved: true, ct).ConfigureAwait(false))
{
var items = await storage.Highlights.ListItemsAsync(highlight.Id, ct).ConfigureAwait(false);
highlights.Add(new HighlightDto(highlight.Id, highlight.Title, items.Count, highlight.RemovedAt is not null, items.OrderBy(i => i.Position).Select(i => i.EntryId).ToList()));
}
return new AccountDetailDto(
Row(account, summary, avatar, resumesTomorrow, now, zone),
new AccountStatsDto(stats.EntriesInLibrary, stats.Posts, stats.Stories, stats.HighlightItems, stats.Tagged, stats.ProfilePictures, stats.HighlightCollections, stats.Bytes, stats.PendingFiles),
AccountSettingsMapper.ToDto(account),
await PlanAsync(storage, account, now, ct).ConfigureAwait(false),
library.Layout.AccountFolder(account),
account.Folder is null,
account.State == AccountState.ArchiveOnly && account.InstagramId is null && account.IsMine is false ? null : InstagramLinks.Profile(account.Username),
highlights,
AccountSettingsMapper.MaxBackfillPerDay);
}
/// <summary>«Con queste impostazioni», recomputed at every change of the form (spec §4.4).</summary>
public static async Task<PlanDto> PlanAsync(IFebeStorage storage, Account edited, DateTimeOffset now, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(edited);
var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var others = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).Where(a => a.Id != edited.Id).ToList();
var stats = edited.Id > 0 ? await storage.Accounts.GetStatsAsync(edited.Id, ct).ConfigureAwait(false) : null;
var rampStart = await storage.Settings.GetInt64Async(EngineSettingKeys.RampStart, ct).ConfigureAwait(false);
var estimate = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = edited,
OtherAccounts = others,
Profile = settings.EffectiveProfile,
ArchivedPosts = stats?.Posts ?? 0,
GradualStartSince = rampStart is { } ms ? DateTimeOffset.FromUnixTimeMilliseconds(ms) : null,
Now = now,
});
var lines = estimate.Lines.Select(l => new PlanLineDto(
l.Title switch
{
"Nuovi post" => "posts",
"Storie" => "stories",
"Storico" => "backfill",
"Carico" => "load",
_ => "checks",
},
l.Title,
l.Text)).ToList();
return new PlanDto(
lines,
estimate.Warnings,
estimate.ShareOfDailyBudget,
estimate.ProfileOpensPerDay,
estimate.DailyProfileBudget,
estimate.OverBudget,
AccountSettingsMapper.FrequencyHint(edited),
AccountSettingsMapper.Note(edited));
}
// ------------------------------------------------------------------------------------------ remove
/// <summary>
/// «Rimuovi» (spec §4.2): keeping the files (the default) makes the account «Solo archivio»; deleting them removes
/// every entry with its files (journal first, then database, then disk) and then the account.
/// </summary>
public static async Task<RemoveAccountDto> RemoveAsync(long id, bool deleteFiles, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(library);
ArgumentNullException.ThrowIfNull(clock);
var account = await GetAsync(storage, id, ct).ConfigureAwait(false);
var handle = ItalianText.Handle(account.Username);
if (account.IsMine)
{
throw new BadRequestException("Il tuo profilo resta: puoi metterlo in pausa o togliere ciò che scarica.");
}
if (!deleteFiles)
{
await storage.Accounts.UpdateAsync(account with { State = AccountState.ArchiveOnly, StateChangedAt = clock.Now, KeepUpdated = false }, ct).ConfigureAwait(false);
return new RemoveAccountDto("archived", 0, 0, $"{handle} è ora «Solo archivio»: i file restano in libreria e Febe non lo contatta più.");
}
var deleted = 0;
var problems = 0;
var deletion = library.Deletion;
while (true)
{
var batch = await storage.Entries.ListByAccountAsync(id, new EntryListOptions { Limit = 500 }, ct).ConfigureAwait(false);
if (batch.Count == 0)
{
break;
}
foreach (var entry in batch)
{
var result = await deletion.DeleteAsync(entry.Id, DeletionMode.AllowReturn, ct).ConfigureAwait(false);
deleted += result.Found ? 1 : 0;
problems += result.FailedFiles.Count;
}
}
await storage.Accounts.DeleteAsync(id, ct).ConfigureAwait(false);
var message = $"{handle} rimosso con {ItalianText.Count(deleted, "elemento", "elementi")}."
+ (problems > 0 ? $" {ItalianText.Count(problems, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: restano nella sua cartella." : string.Empty);
return new RemoveAccountDto("removed", deleted, problems, message);
}
// ------------------------------------------------------------------------------------------ following and adding
public static async Task<FollowingDto> FollowingAsync(IFebeStorage storage, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
var profiles = await storage.Following.ListAsync(ct).ConfigureAwait(false);
var lastRead = await storage.Following.GetLastReadAtAsync(ct).ConfigureAwait(false);
var started = await storage.Settings.GetAsync(RecipeRunner.FollowingKeys.StartedAt, ct).ConfigureAwait(false);
var read = (int)(await storage.Settings.GetInt64Async(RecipeRunner.FollowingKeys.Read, ct).ConfigureAwait(false) ?? 0);
var pending = (await storage.Tasks.ListPendingAsync(500, ct).ConfigureAwait(false)).Any(t => t.Kind == EngineTaskKind.FollowingList);
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
var byName = accounts.ToDictionary(a => a.Username, StringComparer.OrdinalIgnoreCase);
var byId = accounts.Where(a => a.InstagramId is not null).ToDictionary(a => a.InstagramId!, StringComparer.Ordinal);
var list = profiles.Select(p =>
{
Account? present = null;
if (p.InstagramId is not null && byId.TryGetValue(p.InstagramId, out var a))
{
present = a;
}
else if (byName.TryGetValue(p.Username, out var b))
{
present = b;
}
return new FollowingProfileDto(p.Username, p.DisplayName, p.IsPrivate, present?.Id);
}).ToList();
var profile = (await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).EffectiveProfile;
return new FollowingDto(
lastRead?.ToUnixTimeMilliseconds(),
lastRead is { } l ? ApiMapping.Day(LocalCalendar.Today(l, clock.LocalZone)) : null,
pending || !string.IsNullOrEmpty(started),
read,
list.Count,
list,
profile.BackfillPostsPerAccountPerDay);
}
public static async Task<ParseResultDto> ParseAsync(IFebeStorage storage, string? text, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
var (names, problems) = UsernameParser.Parse(text);
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
var following = await storage.Following.ListAsync(ct).ConfigureAwait(false);
var byName = accounts.ToDictionary(a => a.Username, StringComparer.OrdinalIgnoreCase);
var followed = following.GroupBy(f => f.Username, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
return new ParseResultDto(
names.Select(n =>
{
byName.TryGetValue(n.Username, out var present);
followed.TryGetValue(n.Username, out var f);
return new ParsedNameDto(n.Line, n.Username, present is not null, present?.Id, f is not null, f?.DisplayName ?? present?.DisplayName, f?.IsPrivate ?? present?.IsPrivate);
}).ToList(),
problems.Select(p => new ParseProblemDto(p.Line, p.Text, p.Reason)).ToList());
}
/// <summary>Adds accounts with one of the three starting points of spec §4.2.</summary>
public static async Task<AddAccountsDto> AddAsync(IFebeStorage storage, AddAccountsRequest request, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(clock);
var start = request.Start?.ToLowerInvariant() switch
{
"everything" => StartingPoint.EverythingAndKeepUpdated,
"newonly" => StartingPoint.OnlyNewFromToday,
"storiesonly" => StartingPoint.OnlyStories,
_ => throw new BadRequestException("Punto di partenza sconosciuto."),
};
if (request.Usernames is not { Count: > 0 })
{
throw new BadRequestException("Nessun account scelto.");
}
if (request.Usernames.Count > 500)
{
throw new BadRequestException("Troppi account in una volta: al massimo 500.");
}
var profile = (await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).EffectiveProfile;
var following = await storage.Following.ListAsync(ct).ConfigureAwait(false);
var followed = following.GroupBy(f => f.Username, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
var now = clock.Now;
var zone = clock.LocalZone;
var added = 0;
var skipped = new List<string>();
foreach (var raw in request.Usernames.Distinct(StringComparer.OrdinalIgnoreCase))
{
var username = raw.Trim().TrimStart('@').ToLowerInvariant();
if (!UsernameParser.IsValid(username))
{
skipped.Add(raw);
continue;
}
if (await storage.Accounts.FindByUsernameAsync(username, ct).ConfigureAwait(false) is not null)
{
skipped.Add(username);
continue;
}
var account = Account.Create(username, start, now, zone, profile);
if (start == StartingPoint.EverythingAndKeepUpdated)
{
var depth = ApiMapping.ParseDepth(request.Depth) ?? HistoryDepth.All;
account = account with
{
State = AccountState.Backfilling,
Limits = depth switch
{
HistoryDepth.LastPosts when request.LastPosts is > 0 => account.Limits with { Depth = HistoryDepth.LastPosts, LastPosts = request.LastPosts },
HistoryDepth.FromDate => account.Limits with { Depth = HistoryDepth.FromDate, FromDate = LocalCalendar.StartOfDay(new DateOnly(LocalCalendar.Today(now, zone).Year, 1, 1), zone) },
_ => account.Limits,
},
};
}
if (followed.TryGetValue(username, out var f))
{
account = account with
{
IsFollowed = true,
InstagramId = f.InstagramId,
DisplayName = f.DisplayName,
IsPrivate = f.IsPrivate ?? false,
};
}
try
{
await storage.Accounts.AddAsync(account, ct).ConfigureAwait(false);
added++;
}
catch (DuplicateRecordException)
{
skipped.Add(username);
}
}
var message = added == 0
? "Nessun account aggiunto: erano già tutti in Febe."
: $"{ItalianText.Count(added, "account aggiunto", "account aggiunti")}." + (skipped.Count > 0 ? $" {ItalianText.Count(skipped.Count, "era già presente", "erano già presenti o non validi")}." : string.Empty);
return new AddAccountsDto(added, skipped, message);
}
// ------------------------------------------------------------------------------------------ helpers
/// <summary>The thumbnail key of the newest profile picture of an account, if any.</summary>
public static async Task<string?> AvatarAsync(IFebeStorage storage, long accountId, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
var page = await storage.Entries.QueryLibraryAsync(
new LibraryQuery { Filter = new LibraryFilter { Kind = LibraryKindFilter.ProfilePictures, AccountIds = [accountId] }, Limit = 1 },
ct).ConfigureAwait(false);
return page.Tiles.FirstOrDefault() is { CoverHasThumbnail: true, CoverSha256: { } sha } ? sha : null;
}
private static async Task<Dictionary<long, string>> AvatarsAsync(IFebeStorage storage, CancellationToken ct)
{
var page = await storage.Entries.QueryLibraryAsync(
new LibraryQuery { Filter = new LibraryFilter { Kind = LibraryKindFilter.ProfilePictures }, Limit = 1000 },
ct).ConfigureAwait(false);
var map = new Dictionary<long, string>();
foreach (var tile in page.Tiles)
{
if (tile is { CoverHasThumbnail: true, CoverSha256: { } sha } && !map.ContainsKey(tile.AccountId))
{
map[tile.AccountId] = sha;
}
}
return map;
}
private static async Task<Account> GetAsync(IFebeStorage storage, long id, CancellationToken ct) =>
await storage.Accounts.GetAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato: forse è stato rimosso.");
/// <summary>The stored folder value for the form's folder: unchanged, default (null) or a chosen absolute path.</summary>
private static string? ResolveFolder(Account account, string? requested, FebeLibrary library, bool readOnly)
{
var current = library.Layout.AccountFolder(account);
if (string.IsNullOrWhiteSpace(requested) || string.Equals(requested, account.Folder, StringComparison.Ordinal))
{
return string.IsNullOrWhiteSpace(requested) ? (readOnly ? account.Folder : null) : account.Folder;
}
if (string.Equals(Path.TrimEndingDirectorySeparator(requested), Path.TrimEndingDirectorySeparator(current), StringComparison.Ordinal))
{
return account.Folder;
}
if (readOnly)
{
throw new BadRequestException("In Docker le cartelle si cambiano dal contenitore, non dall'interfaccia.");
}
if (!Path.IsPathFullyQualified(requested))
{
throw new BadRequestException("Scegli una cartella con il percorso completo.");
}
if (Path.GetFullPath(requested).StartsWith(Path.TrimEndingDirectorySeparator(library.Data.Root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
{
throw new BadRequestException("Le foto non vanno nella cartella dei dati di Febe: scegline un'altra.");
}
return library.Layout.FolderSetting(requested, account.Username);
}
private static DateTimeOffset? Max(DateTimeOffset? a, DateTimeOffset? b) => a is null ? b : b is null ? a : (a > b ? a : b);
private static DateTimeOffset? Min(DateTimeOffset? a, DateTimeOffset? b) => a is null ? b : b is null ? a : (a < b ? a : b);
}
+88
View File
@@ -0,0 +1,88 @@
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Febe.Core.Storage;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Febe.Web.Api;
/// <summary>
/// Turns the exceptions of the API into Italian answers: 400 for a wrong request, 404 for something missing, 409 for a
/// duplicate, 500 with a message that says what happened (never a stack trace, never a caption or a path of the request).
/// </summary>
public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger<ApiErrorMiddleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
{
await next(context).ConfigureAwait(false);
return;
}
try
{
await next(context).ConfigureAwait(false);
}
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
{
// The page went away: nothing to answer.
}
catch (Exception ex) when (!context.Response.HasStarted)
{
var (status, message) = ex switch
{
BadRequestException => (StatusCodes.Status400BadRequest, ex.Message),
ArgumentException => (StatusCodes.Status400BadRequest, ex.Message),
JsonException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
DuplicateRecordException => (StatusCodes.Status409Conflict, ex.Message),
_ => (StatusCodes.Status500InternalServerError, "Errore interno: Febe non ha completato l'operazione. Riprova; se succede ancora, guarda il registro."),
};
if (status == StatusCodes.Status500InternalServerError)
{
// Type and message only: no request data.
logger.LogError("Errore dell'API: {Type}: {Message}", ex.GetType().Name, ex.Message);
}
context.Response.Clear();
context.Response.StatusCode = status;
await context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
}
}
}
/// <summary>Small helpers of the endpoints.</summary>
public static class ApiHttp
{
/// <summary>Reads a JSON body with its source-generated metadata; an empty or unreadable body is a 400.</summary>
public static async Task<T> BodyAsync<T>(HttpContext context, JsonTypeInfo<T> type)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(type);
if (context.Request.ContentLength == 0)
{
throw new BadRequestException("Richiesta vuota.");
}
try
{
var value = await JsonSerializer.DeserializeAsync(context.Request.Body, type, context.RequestAborted).ConfigureAwait(false);
return value ?? throw new BadRequestException("Richiesta vuota.");
}
catch (JsonException)
{
throw new BadRequestException("Richiesta non leggibile.");
}
}
/// <summary>A JSON answer with its source-generated metadata.</summary>
public static IResult Json<T>(T value, JsonTypeInfo<T> type, int status = StatusCodes.Status200OK) =>
Results.Json(value, type, statusCode: status);
public static IResult Message(string message, int status = StatusCodes.Status200OK) =>
Results.Json(new MessageDto(message), FebeJsonContext.Default.MessageDto, statusCode: status);
}
+277
View File
@@ -0,0 +1,277 @@
using System.Globalization;
using Febe.Core.Domain;
using Febe.Core.Storage;
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Api;
/// <summary>Conversions between the domain and the wire: names of kinds and states, local times, filters, cursors.</summary>
public static class ApiMapping
{
public static string Kind(EntryKind kind) => kind switch
{
EntryKind.Post => "post",
EntryKind.Story => "story",
EntryKind.Highlight => "highlight",
EntryKind.Tagged => "tagged",
EntryKind.ProfilePicture => "profile",
_ => kind.ToString(),
};
public static string Media(MediaKind kind) => kind == MediaKind.Video ? "video" : "photo";
public static string Provenance(Provenance provenance) => provenance == Core.Domain.Provenance.Imported ? "imported" : "downloaded";
public static string State(EntryState state) => char.ToLowerInvariant(state.ToString()[0]) + state.ToString()[1..];
public static string State(MediaState state) => char.ToLowerInvariant(state.ToString()[0]) + state.ToString()[1..];
public static string State(AccountState state) => state switch
{
AccountState.UpToDate => "upToDate",
AccountState.Backfilling => "backfilling",
AccountState.Paused => "paused",
AccountState.ArchiveOnly => "archiveOnly",
AccountState.Unreachable => "unreachable",
_ => state.ToString(),
};
public static string Frequency(Frequency frequency) => frequency switch
{
Core.Domain.Frequency.Low => "low",
Core.Domain.Frequency.Normal => "normal",
Core.Domain.Frequency.High => "high",
Core.Domain.Frequency.Custom => "custom",
_ => frequency.ToString(),
};
public static Frequency? ParseFrequency(string? text) => text?.ToLowerInvariant() switch
{
"low" => Core.Domain.Frequency.Low,
"normal" => Core.Domain.Frequency.Normal,
"high" => Core.Domain.Frequency.High,
"custom" => Core.Domain.Frequency.Custom,
_ => null,
};
public static string Depth(HistoryDepth depth) => depth switch
{
HistoryDepth.All => "all",
HistoryDepth.LastPosts => "lastPosts",
HistoryDepth.FromDate => "fromDate",
_ => depth.ToString(),
};
public static HistoryDepth? ParseDepth(string? text) => text?.ToLowerInvariant() switch
{
"all" => HistoryDepth.All,
"lastposts" => HistoryDepth.LastPosts,
"fromdate" => HistoryDepth.FromDate,
_ => null,
};
public static ContentTypesDto Types(ContentTypes types) => new(
(types & ContentTypes.PostPhotos) != 0,
(types & ContentTypes.PostVideos) != 0,
(types & ContentTypes.Stories) != 0,
(types & ContentTypes.Highlights) != 0,
(types & ContentTypes.Tagged) != 0,
(types & ContentTypes.ProfilePicture) != 0);
public static ContentTypes Types(ContentTypesDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
var types = ContentTypes.None;
if (dto.Photos)
{
types |= ContentTypes.PostPhotos;
}
if (dto.Videos)
{
types |= ContentTypes.PostVideos;
}
if (dto.Stories)
{
types |= ContentTypes.Stories;
}
if (dto.Highlights)
{
types |= ContentTypes.Highlights;
}
if (dto.Tagged)
{
types |= ContentTypes.Tagged;
}
if (dto.ProfilePicture)
{
types |= ContentTypes.ProfilePicture;
}
return types;
}
/// <summary>An instant with its local day and clock in <paramref name="zone"/>.</summary>
public static LocalTimeDto Local(DateTimeOffset instant, DateTimeOffset now, TimeZoneInfo zone)
{
var local = LocalCalendar.ToLocal(instant, zone);
var day = DateOnly.FromDateTime(local);
var today = LocalCalendar.Today(now, zone);
return new LocalTimeDto(
instant.ToUnixTimeMilliseconds(),
Day(day),
local.Hour.ToString(CultureInfo.InvariantCulture) + ":" + local.Minute.ToString("00", CultureInfo.InvariantCulture),
day.DayNumber - today.DayNumber);
}
public static string Day(DateOnly day) => day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
public static string Clock(DateTimeOffset instant, TimeZoneInfo zone)
{
var local = LocalCalendar.ToLocal(instant, zone);
return local.Hour.ToString(CultureInfo.InvariantCulture) + ":" + local.Minute.ToString("00", CultureInfo.InvariantCulture);
}
public static string Cursor(LibraryCursor cursor) =>
cursor.PublishedAt.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + "." + cursor.EntryId.ToString(CultureInfo.InvariantCulture);
public static LibraryCursor? ParseCursor(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
var dot = text.IndexOf('.', StringComparison.Ordinal);
if (dot <= 0
|| !long.TryParse(text.AsSpan(0, dot), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms)
|| !long.TryParse(text.AsSpan(dot + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
{
throw new BadRequestException("Posizione nella libreria non valida.");
}
return new LibraryCursor(DateTimeOffset.FromUnixTimeMilliseconds(ms), id);
}
/// <summary>
/// The library filter from the query string: <c>kind</c> (all, photos, videos, stories, highlights, tagged, posts,
/// profile), <c>accounts</c> (comma-separated keys), <c>from</c>/<c>to</c> (local days, inclusive),
/// <c>provenance</c> (downloaded, imported), <c>q</c> (account name or caption).
/// </summary>
public static LibraryFilter Filter(IQueryCollection query, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(query);
ArgumentNullException.ThrowIfNull(zone);
var kind = query["kind"].ToString().ToLowerInvariant() switch
{
"" or "all" => LibraryKindFilter.All,
"photos" => LibraryKindFilter.Photos,
"videos" => LibraryKindFilter.Videos,
"stories" => LibraryKindFilter.Stories,
"highlights" => LibraryKindFilter.Highlights,
"tagged" => LibraryKindFilter.Tagged,
"posts" => LibraryKindFilter.Posts,
"profile" => LibraryKindFilter.ProfilePictures,
_ => throw new BadRequestException("Tipo di contenuto sconosciuto."),
};
List<long>? accounts = null;
var accountText = query["accounts"].ToString();
if (accountText.Length > 0)
{
accounts = [];
foreach (var part in accountText.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (!long.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
{
throw new BadRequestException("Elenco di account non valido.");
}
accounts.Add(id);
}
}
DateTimeOffset? from = ParseDay(query["from"].ToString()) is { } f ? LocalCalendar.StartOfDay(f, zone) : null;
DateTimeOffset? to = ParseDay(query["to"].ToString()) is { } t ? LocalCalendar.StartOfDay(t.AddDays(1), zone) : null;
Provenance? provenance = query["provenance"].ToString().ToLowerInvariant() switch
{
"" => null,
"downloaded" => Core.Domain.Provenance.Downloaded,
"imported" => Core.Domain.Provenance.Imported,
_ => throw new BadRequestException("Provenienza sconosciuta."),
};
var search = query["q"].ToString().Trim();
return new LibraryFilter
{
Kind = kind,
AccountIds = accounts,
From = from,
To = to,
Provenance = provenance,
Search = search.Length == 0 ? null : search,
};
}
public static DateOnly? ParseDay(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
return DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)
? day
: throw new BadRequestException("Data non valida: serve la forma anno-mese-giorno.");
}
public static AccountBriefDto Brief(Account account, string? avatar) => new(
account.Id,
account.Username,
account.DisplayName,
account.IsPrivate,
account.IsFollowed,
account.IsMine,
State(account.State),
avatar);
}
/// <summary>A request the API refuses with 400 and an Italian message.</summary>
public sealed class BadRequestException : Exception
{
public BadRequestException()
{
}
public BadRequestException(string message)
: base(message)
{
}
public BadRequestException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>Something the API cannot find (404 with an Italian message).</summary>
public sealed class NotFoundException : Exception
{
public NotFoundException()
{
}
public NotFoundException(string message)
: base(message)
{
}
public NotFoundException(string message, Exception innerException)
: base(message, innerException)
{
}
}
+236
View File
@@ -0,0 +1,236 @@
using Febe.Core.Engine;
namespace Febe.Web.Api;
// JSON shapes of the API. English names (camelCase on the wire); every text meant for Alberto is Italian.
// Times: milliseconds since the Unix epoch (UTC), plus local strings computed in Alberto's zone where the page shows a
// clock or a day, so the page never needs to know the zone of the server.
/// <summary>An error the page shows as it is.</summary>
public sealed record ProblemDto(string Message);
/// <summary>A short answer of a command.</summary>
public sealed record MessageDto(string Message);
/// <summary>An instant with its local day and clock time. <see cref="DayDelta"/>: 0 today, 1 tomorrow, -1 yesterday.</summary>
public sealed record LocalTimeDto(long Ms, string Day, string Clock, int DayDelta);
/// <summary>What this shell can do (the page adapts its buttons).</summary>
public sealed record CapabilitiesDto(
string Edition,
bool Demo,
string Access,
bool ShowInFolder,
bool PickFolder,
bool OpenUrlNative,
bool FoldersReadOnly,
bool Autostart,
bool BrowserWindow,
bool Notifications,
string Version,
string? Scene,
IReadOnlyList<string> Scenes,
long Now,
string Today);
public sealed record PreferencesDto(string Theme);
// ---------------------------------------------------------------- library
/// <summary>The cover of a tile. <see cref="Thumb"/> is the thumbnail key (null: neutral tile).</summary>
public sealed record CoverDto(long MediaId, string Kind, int? Width, int? Height, double? Duration, string? Thumb);
/// <summary>A tile of the mosaic: one entry.</summary>
public sealed record TileDto(
long Id,
long AccountId,
string Username,
string Kind,
long PublishedAt,
string Day,
string Time,
string Provenance,
string State,
int Files,
CoverDto? Cover);
/// <summary>A window of tiles; cursors continue it (null: nothing more that way).</summary>
public sealed record LibraryPageDto(IReadOnlyList<TileDto> Tiles, string? Older, string? Newer);
/// <summary>A day of the mosaic: its count and the cursor that starts at its end.</summary>
public sealed record DayDto(string Day, int Count, string Cursor);
public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList<DayDto> Days);
public sealed record AccountBriefDto(long Id, string Username, string? DisplayName, bool IsPrivate, bool IsFollowed, bool IsMine, string State, string? Avatar);
public sealed record MediaDto(
long Id,
int Position,
string Kind,
int? Width,
int? Height,
double? Duration,
long? Bytes,
string? FileName,
string? Folder,
string? Thumb,
bool Available,
string State);
/// <summary>Everything the viewer shows of an entry.</summary>
public sealed record EntryDto(
long Id,
string Kind,
AccountBriefDto Account,
long PublishedAt,
string PublishedDay,
string PublishedTime,
string? Code,
string? InstagramId,
string? Caption,
string? Author,
string Provenance,
string State,
LocalTimeDto Discovered,
LocalTimeDto? Downloaded,
IReadOnlyList<string> Highlights,
string? InstagramUrl,
IReadOnlyList<MediaDto> Media);
public sealed record EntryIdsRequest(IReadOnlyList<long> Ids, string? Mode);
public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList<string> Problems, string Message);
/// <summary>Export by keys, or by the current filter when no keys are given.</summary>
public sealed record ExportRequest(IReadOnlyList<long>? Ids, string? Query);
public sealed record MediaActionRequest(long MediaId);
// ---------------------------------------------------------------- accounts
public sealed record ContentTypesDto(bool Photos, bool Videos, bool Stories, bool Highlights, bool Tagged, bool ProfilePicture);
/// <summary>A row of the accounts table (mockup 03).</summary>
public sealed record AccountRowDto(
long Id,
string Username,
string? DisplayName,
bool IsPrivate,
bool IsFollowed,
bool IsMine,
string State,
string? UnreachableReason,
bool NeedsAttention,
IReadOnlyList<string> Notices,
bool KeepUpdated,
bool KeptUpdated,
string Frequency,
ContentTypesDto Types,
int InLibrary,
int Posts,
int? PostCount,
int NewPostsToday,
int NewStoriesToday,
bool BackfillResumesTomorrow,
long? LastCheck,
LocalTimeDto? NextCheck,
LocalTimeDto? StateChanged,
long AddedAt,
string? Avatar,
string? PreviousUsername);
public sealed record AccountCountsDto(int All, int UpToDate, int Backfilling, int Paused, int ArchiveOnly, int NeedsAttention, int KeptUpdated);
public sealed record AccountListDto(long Now, AccountCountsDto Counts, IReadOnlyList<AccountRowDto> Accounts);
public sealed record AccountStatsDto(int Entries, int Posts, int Stories, int HighlightItems, int Tagged, int ProfilePictures, int Collections, long Bytes, int PendingFiles);
/// <summary>The editable settings of an account (mockup 05).</summary>
public sealed record AccountSettingsDto(
bool KeepUpdated,
string Frequency,
double? CustomPostHours,
double? CustomStoryHours,
ContentTypesDto Types,
string Depth,
int? LastPosts,
string? FromDate,
int BackfillPerDay,
double? MaxVideoMb,
bool StoryVideos,
string? Folder);
public sealed record PlanLineDto(string Key, string Title, string Text);
/// <summary>«Con queste impostazioni» (spec §4.4).</summary>
public sealed record PlanDto(
IReadOnlyList<PlanLineDto> Lines,
IReadOnlyList<string> Warnings,
double Share,
double OpensPerDay,
int DailyBudget,
bool OverBudget,
string FrequencyHint,
string? Note);
public sealed record HighlightDto(long Id, string Title, int Count, bool Removed, IReadOnlyList<long> EntryIds);
public sealed record AccountDetailDto(
AccountRowDto Account,
AccountStatsDto Stats,
AccountSettingsDto Settings,
PlanDto Plan,
string Folder,
bool FolderIsDefault,
string? InstagramUrl,
IReadOnlyList<HighlightDto> Highlights,
int MaxBackfillPerDay);
public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message);
public sealed record HistoryDto(IReadOnlyList<HistoryItemDto> Items, long? Before);
public sealed record SwitchRequest(bool Value);
public sealed record CheckNowRequest(string? Token);
public sealed record CheckNowDto(string Status, string Message, string? Token);
public sealed record RemoveAccountRequest(bool DeleteFiles);
public sealed record RemoveAccountDto(string Outcome, int DeletedEntries, int Problems, string Message);
public sealed record ParseRequest(string Text);
public sealed record ParsedNameDto(int Line, string Username, bool Present, long? AccountId, bool Followed, string? DisplayName, bool? IsPrivate);
public sealed record ParseProblemDto(int Line, string Text, string Reason);
public sealed record ParseResultDto(IReadOnlyList<ParsedNameDto> Names, IReadOnlyList<ParseProblemDto> Problems);
public sealed record AddAccountsRequest(IReadOnlyList<string> Usernames, string Start, string? Depth, int? LastPosts);
public sealed record AddAccountsDto(int Added, IReadOnlyList<string> Skipped, string Message);
public sealed record FollowingProfileDto(string Username, string? DisplayName, bool? IsPrivate, long? AccountId);
/// <param name="BackfillPerDay">Default «Storico, massimo al giorno» of the caution profile, for the note of the dialog.</param>
public sealed record FollowingDto(long? ReadAt, string? ReadDay, bool InProgress, int ReadSoFar, int Total, IReadOnlyList<FollowingProfileDto> Profiles, int BackfillPerDay);
// ---------------------------------------------------------------- engine
/// <summary>The connected account at the bottom of the sidebar.</summary>
/// <param name="State">"connected", "notConnected", "verification", "disconnected".</param>
public sealed record ConnectionDto(string State, string? Username, string? DisplayName, string? Avatar);
/// <summary>The engine for the sidebar, the stop strip and the Attività page.</summary>
public sealed record EngineDto(long Now, EngineSnapshot Snapshot, ConnectionDto Connection, bool CanResume);
public sealed record ResumeDto(bool Resumed, string Message);
// ---------------------------------------------------------------- access
public sealed record LoginRequest(string? Password);
public sealed record LoginDto(bool Ok, string Message, long? LockedUntil);
+257
View File
@@ -0,0 +1,257 @@
using System.Text;
using System.Text.Json;
using System.Threading.Channels;
using Febe.Core.Abstractions;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Engine;
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>The engine for the interface: snapshot, «Metti in pausa», «Riprendi», the browser, and the event stream.</summary>
public static class EngineApi
{
/// <summary>Idle time after which a comment line keeps the event stream open through proxies.</summary>
public static readonly TimeSpan Heartbeat = TimeSpan.FromSeconds(25);
/// <summary>The snapshot is pushed again at least this often, so «8 min fa» and «verso le» stay current.</summary>
public static readonly TimeSpan Refresh = TimeSpan.FromSeconds(60);
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
{
await control.PauseAsync(ct).ConfigureAwait(false);
return ApiHttp.Message("Febe è in pausa: non apre nulla finché non premi «Riprendi».");
});
endpoints.MapPost("/api/engine/resume", async (IEngineControl control, CancellationToken ct) =>
{
var result = await control.ResumeAsync(ct).ConfigureAwait(false);
return ApiHttp.Json(new ResumeDto(result.Resumed, result.Message), FebeJsonContext.Default.ResumeDto);
});
// «Apri il browser» on Windows: the window of the browser comes to the front.
endpoints.MapPost("/api/browser/show", async (IBrowserWindow browser, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
{
if (!browser.IsSeparateWindow)
{
throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser.");
}
await browser.ShowAsync(ct).ConfigureAwait(false);
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Il browser di Febe è in primo piano.");
});
// The Browser page («Ho finito») and the desktop window report that Alberto used the browser: «Riprendi» activates.
endpoints.MapPost("/api/browser/used", (BrowserUseTracker tracker, IClock clock) =>
{
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Bene: ora puoi premere «Riprendi».");
});
endpoints.MapGet("/api/eventi", StreamAsync);
}
/// <summary>The engine as the interface needs it.</summary>
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(monitor);
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(tracker);
ArgumentNullException.ThrowIfNull(clock);
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
var state = snapshot.Mode switch
{
EngineMode.NotConnected => "notConnected",
EngineMode.StoppedForVerification => "verification",
EngineMode.Disconnected => "disconnected",
_ => mine is null ? "notConnected" : "connected",
};
var connection = state == "notConnected"
? new ConnectionDto(state, null, null, null)
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
bool canResume;
if (snapshot.Banner is { NeedsResume: true })
{
var since = snapshot.Breaker.LastSignal?.At ?? DateTimeOffset.MinValue;
canResume = tracker.LastUsedAt is { } used && used >= since;
}
else
{
canResume = snapshot.Mode == EngineMode.Paused;
}
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, connection, canResume);
}
/// <summary>
/// <c>/api/eventi</c>: server-sent events. <c>motore</c> carries the engine (at once, at every change, at least every
/// minute); <c>libreria</c> says the library changed (at most every second and a half); a comment line keeps the
/// stream open. Never contains captions, bodies or addresses.
/// </summary>
public static async Task StreamAsync(
HttpContext context,
IEngineMonitor monitor,
IFebeStorage storage,
BrowserUseTracker tracker,
LibraryChanges library,
IClock clock)
{
ArgumentNullException.ThrowIfNull(context);
var response = context.Response;
response.ContentType = "text/event-stream; charset=utf-8";
response.Headers.CacheControl = "no-cache, no-transform";
response.Headers["X-Accel-Buffering"] = "no";
var ct = context.RequestAborted;
var signals = Channel.CreateBounded<string>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest });
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
var engineTask = Task.Run(
async () =>
{
await foreach (var _ in monitor.SubscribeAsync(stop.Token).ConfigureAwait(false))
{
signals.Writer.TryWrite("motore");
}
},
CancellationToken.None);
var libraryTask = Task.Run(
async () =>
{
await foreach (var change in library.SubscribeAsync(stop.Token).ConfigureAwait(false))
{
signals.Writer.TryWrite("libreria:" + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange));
}
},
CancellationToken.None);
try
{
await WriteAsync(response, "retry: 3000\n\n", ct).ConfigureAwait(false);
await SendEngineAsync().ConfigureAwait(false);
var libraryGap = TimeSpan.FromMilliseconds(1500);
var lastEngine = DateTimeOffset.UtcNow;
var lastLibrary = DateTimeOffset.MinValue;
string? pendingLibrary = null;
var enginePending = false;
while (!ct.IsCancellationRequested)
{
var now = DateTimeOffset.UtcNow;
var wait = Heartbeat;
if (lastEngine + Refresh - now < wait)
{
wait = lastEngine + Refresh - now;
}
if (pendingLibrary is not null && lastLibrary + libraryGap - now < wait)
{
wait = lastLibrary + libraryGap - now;
}
var got = await WaitAsync(signals.Reader, wait < TimeSpan.Zero ? TimeSpan.Zero : wait, ct).ConfigureAwait(false);
if (got)
{
// Changes come in bursts: wait a moment and send one update for all of them.
await Task.Delay(TimeSpan.FromMilliseconds(300), ct).ConfigureAwait(false);
while (signals.Reader.TryRead(out var signal))
{
if (signal == "motore")
{
enginePending = true;
}
else
{
pendingLibrary = signal["libreria:".Length..];
}
}
}
now = DateTimeOffset.UtcNow;
var sent = false;
if (enginePending || now - lastEngine >= Refresh)
{
await SendEngineAsync().ConfigureAwait(false);
enginePending = false;
lastEngine = now;
sent = true;
}
if (pendingLibrary is not null && now - lastLibrary >= libraryGap)
{
await WriteAsync(response, "event: libreria\ndata: " + pendingLibrary + "\n\n", ct).ConfigureAwait(false);
pendingLibrary = null;
lastLibrary = now;
sent = true;
}
if (!sent && !got)
{
await WriteAsync(response, ": ancora qui\n\n", ct).ConfigureAwait(false);
}
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The page closed the stream.
}
catch (IOException)
{
// The connection dropped.
}
finally
{
await stop.CancelAsync().ConfigureAwait(false);
await Task.WhenAll(Quiet(engineTask), Quiet(libraryTask)).ConfigureAwait(false);
}
async Task SendEngineAsync()
{
var dto = await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false);
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
}
}
private static async Task<bool> WaitAsync(ChannelReader<string> reader, TimeSpan wait, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(wait);
try
{
return await reader.WaitToReadAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return false;
}
}
private static async Task WriteAsync(HttpResponse response, string text, CancellationToken ct)
{
await response.Body.WriteAsync(Encoding.UTF8.GetBytes(text), ct).ConfigureAwait(false);
await response.Body.FlushAsync(ct).ConfigureAwait(false);
}
private static async Task Quiet(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
}
+47
View File
@@ -0,0 +1,47 @@
using System.Text.Json.Serialization;
namespace Febe.Web.Api;
/// <summary>
/// Source-generated JSON for every shape of the API: no reflection, so it works in trimmed and single-file builds.
/// <see cref="FebeWeb.AddFebeWeb"/> makes it the only resolver of the minimal APIs: a type missing here fails loudly
/// in the tests instead of silently falling back to reflection. Add new DTOs here.
/// </summary>
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals)]
[JsonSerializable(typeof(ProblemDto))]
[JsonSerializable(typeof(MessageDto))]
[JsonSerializable(typeof(CapabilitiesDto))]
[JsonSerializable(typeof(PreferencesDto))]
[JsonSerializable(typeof(LibraryPageDto))]
[JsonSerializable(typeof(LibraryDaysDto))]
[JsonSerializable(typeof(EntryDto))]
[JsonSerializable(typeof(EntryIdsRequest))]
[JsonSerializable(typeof(DeleteResultDto))]
[JsonSerializable(typeof(ExportRequest))]
[JsonSerializable(typeof(MediaActionRequest))]
[JsonSerializable(typeof(AccountListDto))]
[JsonSerializable(typeof(AccountDetailDto))]
[JsonSerializable(typeof(AccountSettingsDto))]
[JsonSerializable(typeof(PlanDto))]
[JsonSerializable(typeof(HistoryDto))]
[JsonSerializable(typeof(SwitchRequest))]
[JsonSerializable(typeof(CheckNowRequest))]
[JsonSerializable(typeof(CheckNowDto))]
[JsonSerializable(typeof(RemoveAccountRequest))]
[JsonSerializable(typeof(RemoveAccountDto))]
[JsonSerializable(typeof(ParseRequest))]
[JsonSerializable(typeof(ParseResultDto))]
[JsonSerializable(typeof(AddAccountsRequest))]
[JsonSerializable(typeof(AddAccountsDto))]
[JsonSerializable(typeof(FollowingDto))]
[JsonSerializable(typeof(EngineDto))]
[JsonSerializable(typeof(ResumeDto))]
[JsonSerializable(typeof(LoginRequest))]
[JsonSerializable(typeof(LoginDto))]
[JsonSerializable(typeof(Library.LibraryChange))]
public sealed partial class FebeJsonContext : JsonSerializerContext;
+357
View File
@@ -0,0 +1,357 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
namespace Febe.Web.Api;
/// <summary>
/// The library (spec §4.6): days and windows of the mosaic with keyset paging (fluid with 200,000 entries), thumbnails
/// generated once and served from the Data folder, the files themselves, the viewer data, deletion, CSV export.
/// </summary>
public static class LibraryApi
{
/// <summary>Largest window a page can ask for.</summary>
public const int MaxWindow = 600;
private static readonly FileExtensionContentTypeProvider ContentTypes = new();
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/library/days", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var zone = clock.LocalZone;
var now = clock.Now;
var filter = ApiMapping.Filter(context.Request.Query, zone);
var totals = await storage.Entries.GetLibraryTotalsAsync(filter, ct).ConfigureAwait(false);
var days = await storage.Entries.CountLibraryByDayAsync(filter, zone, ct).ConfigureAwait(false);
var list = days.Select(d =>
{
var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone);
return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0)));
}).ToList();
return ApiHttp.Json(
new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list),
FebeJsonContext.Default.LibraryDaysDto);
});
endpoints.MapGet("/api/library", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var query = context.Request.Query;
var zone = clock.LocalZone;
var limit = int.TryParse(query["limit"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var l) ? Math.Clamp(l, 1, MaxWindow) : 200;
var direction = string.Equals(query["direction"], "newer", StringComparison.OrdinalIgnoreCase) ? LibraryDirection.Newer : LibraryDirection.Older;
var page = await storage.Entries.QueryLibraryAsync(
new LibraryQuery
{
Filter = ApiMapping.Filter(query, zone),
Cursor = ApiMapping.ParseCursor(query["cursor"]),
Direction = direction,
Limit = limit,
},
ct).ConfigureAwait(false);
return ApiHttp.Json(
new LibraryPageDto(
page.Tiles.Select(t => Tile(t, zone)).ToList(),
page.Older is { } older ? ApiMapping.Cursor(older) : null,
page.Newer is { } newer ? ApiMapping.Cursor(newer) : null),
FebeJsonContext.Default.LibraryPageDto);
});
// Tiles of given entries in the given order (the items of a highlight collection).
endpoints.MapGet("/api/library/tiles", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
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);
});
endpoints.MapGet("/api/thumbnails/{key}", (string key, HttpContext context, FebeLibrary library) =>
{
string path;
if (string.Equals(key, "video", StringComparison.Ordinal))
{
path = library.Thumbnails.NeutralVideoTile();
}
else
{
if (key.Length != 64 || !key.All(Uri.IsHexDigit))
{
throw new BadRequestException("Chiave di miniatura non valida.");
}
path = library.Thumbnails.PathFor(key);
if (!File.Exists(path))
{
throw new NotFoundException("Miniatura non trovata.");
}
}
// Content-addressed: the same key always has the same picture.
context.Response.Headers.CacheControl = "private, max-age=31536000, immutable";
return Results.File(path, "image/jpeg");
});
endpoints.MapGet("/api/media/{id:long}/file", async (long id, HttpContext context, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) =>
{
var (account, media) = await MediaAsync(storage, id, ct).ConfigureAwait(false);
var path = files.Resolve(account, media) ?? throw new NotFoundException("Il file non è sul disco.");
if (!ContentTypes.TryGetContentType(path, out var type))
{
type = "application/octet-stream";
}
var download = context.Request.Query["download"].ToString() is "1" or "true";
context.Response.Headers.CacheControl = "private, no-cache";
return download
? Results.File(path, type, Path.GetFileName(path), enableRangeProcessing: true)
: Results.File(path, type, enableRangeProcessing: true);
});
endpoints.MapPost("/api/media/show-in-folder", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, INativeShell shell, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.MediaActionRequest).ConfigureAwait(false);
var (account, media) = await MediaAsync(storage, body.MediaId, ct).ConfigureAwait(false);
var path = files.Resolve(account, media) ?? throw new NotFoundException("Il file non è sul disco: forse è stato spostato o cancellato fuori da Febe.");
if (!await shell.ShowInFolderAsync(path, ct).ConfigureAwait(false))
{
throw new BadRequestException("Qui non si può aprire la cartella: usa «Scarica».");
}
return ApiHttp.Message("Cartella aperta.");
});
endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EntryDto));
endpoints.MapPost("/api/entries/{id:long}/open-on-instagram", async (long id, IFebeStorage storage, INativeShell shell, IClock clock, CancellationToken ct) =>
{
var entry = await storage.Entries.GetAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
var highlight = entry.Kind == EntryKind.Highlight ? (await storage.Highlights.ListForEntryAsync(id, ct).ConfigureAwait(false)).FirstOrDefault()?.InstagramId : null;
var address = new Uri(InstagramLinks.For(account, entry, clock.Now, highlight));
if (!InstagramLinks.IsSiteAddress(address) || !await shell.OpenUrlAsync(address, ct).ConfigureAwait(false))
{
throw new BadRequestException("Qui il collegamento si apre direttamente dalla pagina.");
}
return ApiHttp.Message("Aperto nel tuo browser.");
});
endpoints.MapPost("/api/entries/delete", async (HttpContext context, IFebeStorage storage, FebeLibrary library, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.EntryIdsRequest).ConfigureAwait(false);
if (body.Ids.Count == 0)
{
throw new BadRequestException("Nessun elemento scelto.");
}
var mode = string.Equals(body.Mode, "allowReturn", StringComparison.OrdinalIgnoreCase) ? DeletionMode.AllowReturn : DeletionMode.Remember;
var results = await library.Deletion.DeleteManyAsync(body.Ids, mode, ct).ConfigureAwait(false);
var deleted = results.Count(r => r.Found);
var removed = results.Sum(r => r.DeletedFiles.Count);
var problems = results.SelectMany(r => r.FailedFiles).ToList();
changes.Publish(new LibraryChange(clock.Now, null, "deleted"));
var message = (deleted == 1 ? "Elemento eliminato dalla libreria" : $"{Core.Engine.ItalianText.Number(deleted)} elementi eliminati dalla libreria")
+ (mode == DeletionMode.Remember ? ": Febe non li scarica di nuovo." : ": se ricompaiono, Febe li scarica di nuovo.")
+ (problems.Count > 0 ? $" {Core.Engine.ItalianText.Count(problems.Count, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: chiudi i programmi che li usano e riprova." : string.Empty);
return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message), FebeJsonContext.Default.DeleteResultDto);
});
endpoints.MapPost("/api/entries/export", async (HttpContext context, IFebeStorage storage, IClock clock) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportRequest).ConfigureAwait(false);
var zone = clock.LocalZone;
LibraryFilter? filter = null;
if (body.Ids is not { Count: > 0 })
{
filter = ApiMapping.Filter(new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(body.Query ?? string.Empty)), zone);
}
var day = LocalCalendar.Today(clock.Now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
context.Response.ContentType = "text/csv; charset=utf-8";
context.Response.Headers.ContentDisposition = $"attachment; filename=\"febe-elementi-{day}.csv\"";
var rows = filter is null
? RowsAsync(storage, body.Ids!, clock.Now, context.RequestAborted)
: RowsAsync(storage, IdsAsync(storage, filter, context.RequestAborted), clock.Now, context.RequestAborted);
await CsvExport.WriteAsync(context.Response.Body, rows, zone, context.RequestAborted).ConfigureAwait(false);
});
}
public static TileDto Tile(LibraryTile tile, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(tile);
var local = LocalCalendar.ToLocal(tile.PublishedAt, zone);
return new TileDto(
tile.EntryId,
tile.AccountId,
tile.Username,
ApiMapping.Kind(tile.Kind),
tile.PublishedAt.ToUnixTimeMilliseconds(),
ApiMapping.Day(DateOnly.FromDateTime(local)),
local.Hour.ToString(CultureInfo.InvariantCulture) + ":" + local.Minute.ToString("00", CultureInfo.InvariantCulture),
ApiMapping.Provenance(tile.Provenance),
ApiMapping.State(tile.State),
tile.MediaCount,
tile.CoverMediaId is { } mediaId
? new CoverDto(
mediaId,
ApiMapping.Media(tile.CoverKind ?? MediaKind.Photo),
tile.CoverWidth,
tile.CoverHeight,
tile.CoverDuration?.TotalSeconds,
tile.CoverHasThumbnail && tile.CoverSha256 is not null ? tile.CoverSha256 : tile.CoverKind == MediaKind.Video ? "video" : null)
: null);
}
public static async Task<EntryDto> EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(files);
ArgumentNullException.ThrowIfNull(library);
ArgumentNullException.ThrowIfNull(clock);
var stored = await storage.Entries.GetWithMediaAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato: forse è stato eliminato.");
var entry = stored.Entry;
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
var highlights = await storage.Highlights.ListForEntryAsync(id, ct).ConfigureAwait(false);
var zone = clock.LocalZone;
var now = clock.Now;
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 media = stored.Media.Select(m =>
{
var relative = m.RelativePath;
string? folder = null;
if (relative is not null)
{
var directory = Path.GetDirectoryName(LibraryLayout.ToPlatform(relative));
folder = string.IsNullOrEmpty(directory) ? accountFolder : Path.Combine(accountFolder, directory);
}
return new MediaDto(
m.Id,
m.Position,
ApiMapping.Media(m.Kind),
m.Width,
m.Height,
m.Duration?.TotalSeconds,
m.Bytes,
relative is null ? null : Path.GetFileName(LibraryLayout.ToPlatform(relative)),
folder,
m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null,
files.Resolve(account, m) is not null,
ApiMapping.State(m.State));
}).ToList();
return new EntryDto(
entry.Id,
ApiMapping.Kind(entry.Kind),
ApiMapping.Brief(account, avatar),
entry.PublishedAt.ToUnixTimeMilliseconds(),
ApiMapping.Day(DateOnly.FromDateTime(local)),
ApiMapping.Clock(entry.PublishedAt, zone),
entry.Code,
entry.InstagramId,
entry.Caption,
entry.AuthorUsername,
ApiMapping.Provenance(entry.Provenance),
ApiMapping.State(entry.State),
ApiMapping.Local(entry.DiscoveredAt, now, zone),
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);
}
private static async Task<(Account Account, Media Media)> MediaAsync(IFebeStorage storage, long mediaId, CancellationToken ct)
{
var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
return (account, media);
}
private static List<long> ParseIds(string text)
{
var ids = new List<long>();
foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (!long.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
{
throw new BadRequestException("Elenco di elementi non valido.");
}
ids.Add(id);
}
if (ids.Count > 5000)
{
throw new BadRequestException("Troppi elementi in una richiesta.");
}
return ids;
}
private static async IAsyncEnumerable<long> IdsAsync(IFebeStorage storage, LibraryFilter filter, [EnumeratorCancellation] CancellationToken ct)
{
LibraryCursor? cursor = null;
while (true)
{
var page = await storage.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Cursor = cursor, Limit = 1000 }, ct).ConfigureAwait(false);
foreach (var tile in page.Tiles)
{
yield return tile.EntryId;
}
if (page.Older is null)
{
yield break;
}
cursor = page.Older;
}
}
private static async IAsyncEnumerable<long> Enumerate(IReadOnlyList<long> ids)
{
foreach (var id in ids)
{
yield return id;
}
await Task.CompletedTask.ConfigureAwait(false);
}
private static IAsyncEnumerable<CsvEntry> RowsAsync(IFebeStorage storage, IReadOnlyList<long> ids, DateTimeOffset now, CancellationToken ct) =>
RowsAsync(storage, Enumerate(ids), now, ct);
private static async IAsyncEnumerable<CsvEntry> RowsAsync(IFebeStorage storage, IAsyncEnumerable<long> ids, DateTimeOffset now, [EnumeratorCancellation] CancellationToken ct)
{
var accounts = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id);
await foreach (var id in ids.WithCancellation(ct).ConfigureAwait(false))
{
var stored = await storage.Entries.GetWithMediaAsync(id, ct).ConfigureAwait(false);
if (stored is null || !accounts.TryGetValue(stored.Entry.AccountId, out var account))
{
continue;
}
var highlights = await storage.Highlights.ListForEntryAsync(id, ct).ConfigureAwait(false);
yield return new CsvEntry(
account,
stored.Entry,
stored.Media,
highlights.Select(h => h.Title).ToList(),
stored.Entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, stored.Entry, now, highlights.FirstOrDefault()?.InstagramId));
}
}
}
+112
View File
@@ -0,0 +1,112 @@
using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
using Febe.Web.Demo;
using Febe.Web.Hosting;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>Capabilities of the shell, preferences of the interface, the icon sprite.</summary>
public static class SystemApi
{
/// <summary>Setting key of the theme: «chiaro», «scuro» or «sistema».</summary>
public const string ThemeKey = "interfaccia.tema";
public static readonly IReadOnlyList<string> Themes = ["chiaro", "scuro", "sistema"];
public static void Map(IEndpointRouteBuilder endpoints, EmbeddedWwwroot files)
{
endpoints.MapGet("/api/capabilities", (HttpContext context, FebeWebOptions options, INativeShell shell, IBrowserWindow browser, IClock clock) =>
ApiHttp.Json(Capabilities(context, options, shell, browser, clock), FebeJsonContext.Default.CapabilitiesDto));
endpoints.MapGet("/api/preferences", async (IFebeStorage storage, CancellationToken ct) =>
{
var theme = await storage.Settings.GetAsync(ThemeKey, ct).ConfigureAwait(false);
return ApiHttp.Json(new PreferencesDto(Themes.Contains(theme) ? theme! : "sistema"), FebeJsonContext.Default.PreferencesDto);
});
endpoints.MapPut("/api/preferences", async (HttpContext context, IFebeStorage storage, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PreferencesDto).ConfigureAwait(false);
if (!Themes.Contains(body.Theme))
{
throw new BadRequestException("Tema sconosciuto: si sceglie fra chiaro, scuro e come il sistema.");
}
await storage.Settings.SetAsync(ThemeKey, body.Theme, ct).ConfigureAwait(false);
return ApiHttp.Json(body, FebeJsonContext.Default.PreferencesDto);
});
// Every icon of wwwroot/icone as one sprite of <symbol id="i-name">, inlined once by the page.
var cached = new Lazy<string>(() => BuildSprite(files));
string Sprite() => files.FromDisk ? BuildSprite(files) : cached.Value;
endpoints.MapGet("/icone/tutte.svg", (HttpContext context) =>
{
context.Response.Headers.CacheControl = "no-cache";
return Results.Text(Sprite(), "image/svg+xml; charset=utf-8");
});
}
public static CapabilitiesDto Capabilities(HttpContext context, FebeWebOptions options, INativeShell shell, IBrowserWindow browser, IClock clock)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(shell);
ArgumentNullException.ThrowIfNull(browser);
ArgumentNullException.ThrowIfNull(clock);
var edition = options.Demo ? DemoRequest.Edition(context) ?? FebeEdition.Desktop : options.Edition;
var desktop = edition == FebeEdition.Desktop;
var demoDesktop = options.Demo && desktop;
return new CapabilitiesDto(
desktop ? "desktop" : "docker",
options.Demo,
options.Access switch { AccessMode.Password => "password", AccessMode.Token => "token", _ => "none" },
ShowInFolder: demoDesktop || (desktop && shell.CanShowInFolder),
PickFolder: demoDesktop || (desktop && shell.CanPickFolder),
OpenUrlNative: !options.Demo && shell.CanOpenUrl,
FoldersReadOnly: !desktop,
Autostart: demoDesktop || (desktop && shell.SupportsAutostart),
BrowserWindow: demoDesktop || (desktop && browser.IsSeparateWindow),
Notifications: demoDesktop || shell.CanNotify,
options.Version,
options.Demo ? DemoRequest.SceneName(DemoRequest.Scene(context)) : null,
options.Demo ? DemoRequest.SceneNames : [],
clock.Now.ToUnixTimeMilliseconds(),
ApiMapping.Day(LocalCalendar.Today(clock.Now, clock.LocalZone)));
}
/// <summary>The sprite: each Lucide file's drawing inside a symbol; stroke and fill come from the CSS of <c>svg.ic</c>.</summary>
public static string BuildSprite(EmbeddedWwwroot files)
{
ArgumentNullException.ThrowIfNull(files);
var builder = new StringBuilder("<svg xmlns=\"http://www.w3.org/2000/svg\" aria-hidden=\"true\" style=\"display:none\">");
foreach (var path in files.Files.Where(f => f.StartsWith("icone/", StringComparison.Ordinal) && f.EndsWith(".svg", StringComparison.Ordinal)).Order(StringComparer.Ordinal))
{
var text = files.ReadText(path);
if (text is null)
{
continue;
}
var open = text.IndexOf("<svg", StringComparison.Ordinal);
var openEnd = open < 0 ? -1 : text.IndexOf('>', open);
var close = text.LastIndexOf("</svg>", StringComparison.Ordinal);
if (openEnd < 0 || close <= openEnd)
{
continue;
}
var name = path["icone/".Length..^".svg".Length];
builder.Append("<symbol id=\"i-").Append(name).Append("\" viewBox=\"0 0 24 24\">")
.Append(text[(openEnd + 1)..close].Trim())
.Append("</symbol>");
}
return builder.Append("</svg>").ToString();
}
}
+378
View File
@@ -0,0 +1,378 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Engine;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Demo;
/// <summary>
/// The fake engine of the demo (spec §10.6): no browser, no network. The scene of each request
/// (<c>?scena=normale|sessione|fermo|scollegato</c>) decides what it shows; the numbers come from the seeded day, so
/// sessions, budgets, queue and «Appena fatto» agree with the library and the accounts.
/// </summary>
public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage storage, IHttpContextAccessor accessor) : IEngineMonitor, IEngineControl
{
private static readonly CautionProfile Profile = CautionProfile.Prudent;
public DemoScene CurrentScene => DemoRequest.Scene(accessor.HttpContext);
public async Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default)
{
var scene = CurrentScene;
var now = clock.Now;
var zone = clock.LocalZone;
var day = LocalCalendar.Today(now, zone);
var (dayStart, dayEnd) = LocalCalendar.DayBounds(day, zone);
var inWindow = now >= world.WindowStart && now < world.WindowEnd;
var sessions = scene == DemoScene.Disconnected ? [] : world.Today.Where(s => s.End <= now).ToList();
var stopAt = sessions.Count > 0 ? sessions[^1].End - TimeSpan.FromSeconds(40) : now - TimeSpan.FromMinutes(25);
var current = scene == DemoScene.Session
? new DemoSession(now - TimeSpan.FromMinutes(2.5), now, 2, 6, 0, 18_000_000, 2)
: null;
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
var marta = accounts.FirstOrDefault(a => a.Username == "marta.demo")?.Username ?? world.MineUsername;
// Mode and texts.
EngineMode mode;
string headline;
IReadOnlyList<string> details;
string sidebar;
DateTimeOffset? resumes = null;
StopBanner? banner = null;
var breaker = BreakerState.Normal;
var next = world.NextSession is { } n && n > now ? n : inWindow ? now + TimeSpan.FromMinutes(18) : (DateTimeOffset?)null;
switch (scene)
{
case DemoScene.Session:
mode = EngineMode.InSession;
headline = "In sessione";
details = [$"Sto guardando le storie di @{marta}", $"Iniziata {ItalianText.At(current!.Start, zone)}, ancora 4 minuti circa."];
sidebar = $"Storie di @{marta}";
break;
case DemoScene.Stopped:
mode = EngineMode.StoppedForVerification;
headline = "Fermo";
details = ["In attesa che tu completi la verifica", $"Ultima azione: apertura del profilo di @giulia.corre.demo {ItalianText.At(stopAt, zone)}. Nessun nuovo tentativo finché non premi «Riprendi»."];
sidebar = "Serve il tuo intervento";
breaker = new BreakerState(BreakerStatus.Challenge, null, new Signal(SignalLevel.Challenge, "challenge-url", "https://www.instagram.com/challenge/", stopAt), null);
banner = new StopBanner(
BannerLevel.Error,
"Instagram chiede una verifica",
$"Ho fermato tutto {ItalianText.At(stopAt, zone)} e non riparto da solo. Apri il browser, completa la verifica a mano, poi premi «Riprendi».",
true);
break;
case DemoScene.Disconnected:
mode = EngineMode.NotConnected;
headline = "Non collegato";
details = ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento: accedi tu, nella vera pagina di Instagram."];
sidebar = "Accedi per cominciare";
break;
default:
if (inWindow && next is { } around)
{
mode = EngineMode.Resting;
headline = "In ascolto";
resumes = around;
details = [$"Riprende {ItalianText.Around(around, now, zone)}.", "Fra una sessione e l'altra il browser resta sulla pagina vuota."];
sidebar = $"Riprende {ItalianText.Around(around, now, zone)}";
}
else
{
mode = EngineMode.OutsideWindow;
headline = "Fuori fascia";
resumes = world.NextWindowStart + TimeSpan.FromMinutes(4);
details = ["Fuori dalla fascia oraria Febe non apre nulla da solo.", $"Riprende {ItalianText.Around(resumes.Value, now, zone)}."];
sidebar = $"Riprende {ItalianText.Around(resumes.Value, now, zone)}";
}
break;
}
// Strip of the day.
var spans = new List<StripSpan>();
if (world.WindowStart > dayStart)
{
spans.Add(new StripSpan(StripSpanKind.OutsideWindow, dayStart, world.WindowStart < dayEnd ? world.WindowStart : dayEnd, false, "Fuori fascia"));
}
if (world.WindowEnd < dayEnd)
{
spans.Add(new StripSpan(StripSpanKind.OutsideWindow, world.WindowEnd, dayEnd, false, "Fuori fascia"));
}
DateTimeOffset? previousEnd = null;
foreach (var session in sessions)
{
if (previousEnd is { } rest)
{
spans.Add(new StripSpan(StripSpanKind.Rest, rest, session.Start, false, "Pausa"));
}
spans.Add(new StripSpan(StripSpanKind.Session, session.Start, session.End, false, $"Sessione dalle {ItalianText.Clock(session.Start, zone)} alle {ItalianText.Clock(session.End, zone)}"));
previousEnd = session.End;
}
if (current is not null)
{
spans.Add(new StripSpan(StripSpanKind.CurrentSession, current.Start, now, false, $"Sessione in corso dalle {ItalianText.Clock(current.Start, zone)}"));
}
else if (scene == DemoScene.Stopped)
{
spans.Add(new StripSpan(StripSpanKind.Stop, stopAt, now, false, "Fermo per una verifica"));
}
else if (scene == DemoScene.Normal && previousEnd is { } lastEnd && inWindow)
{
spans.Add(new StripSpan(StripSpanKind.Rest, lastEnd, now, false, "Pausa"));
}
if (scene is DemoScene.Normal or DemoScene.Session)
{
var start = scene == DemoScene.Session ? now + TimeSpan.FromMinutes(4) + TimeSpan.FromMinutes(42) : next;
for (var i = 0; start is { } s && s < world.WindowEnd && s < dayEnd && i < 40; i++)
{
var end = s + TimeSpan.FromMinutes(4.5);
spans.Add(new StripSpan(StripSpanKind.PlannedSession, s, end < world.WindowEnd ? end : world.WindowEnd, true, "Prossima sessione " + ItalianText.Around(s, now, zone)));
start = end + TimeSpan.FromMinutes(42);
}
}
var all = current is null ? sessions : [.. sessions, current];
var minutes = all.Sum(s => (s.End - s.Start).TotalMinutes);
var newEntries = scene == DemoScene.Disconnected ? 0 : world.DiscoveredToday + (current?.NewEntries ?? 0);
var summary = string.Join(", ", new[]
{
ItalianText.Count(all.Count, "sessione", "sessioni"),
ItalianText.Count((long)Math.Round(minutes), "minuto di attività", "minuti di attività"),
ItalianText.Count(newEntries, "contenuto nuovo", "contenuti nuovi"),
"nessun rallentamento",
});
var strip = new DayStrip(day, dayStart, dayEnd, now, scene == DemoScene.Disconnected ? "Nessuna sessione oggi: Febe non è collegato" : summary, [.. spans.OrderBy(s => s.Start).ThenBy(s => s.Kind)]);
// Budgets.
var lastHour = all.Where(s => s.End > now - TimeSpan.FromHours(1)).ToList();
var stopped = scene == DemoScene.Stopped ? "Fermo " + ItalianText.Since(stopAt, zone) : null;
var disconnected = scene == DemoScene.Disconnected;
long Used(ActionKind kind) => disconnected ? 0 : kind switch
{
ActionKind.Home => all.Count,
ActionKind.ProfileOpen => all.Sum(s => s.ProfilesOpened),
ActionKind.StoryView => all.Sum(s => s.StoriesViewed),
ActionKind.BackfillPage => all.Sum(s => s.HistoryPages),
ActionKind.SinglePost => world.SinglePostsToday,
ActionKind.FollowingListPage => 0,
ActionKind.DataDownload => world.BytesToday + (current?.Bytes ?? 0),
_ => 0,
};
long Hour(ActionKind kind) => disconnected ? 0 : kind switch
{
ActionKind.Home => lastHour.Count,
ActionKind.ProfileOpen => lastHour.Sum(s => s.ProfilesOpened),
ActionKind.StoryView => lastHour.Sum(s => s.StoriesViewed),
ActionKind.BackfillPage => lastHour.Sum(s => s.HistoryPages),
_ => 0,
};
var budgets = SnapshotParts.All.Select(k => SnapshotParts.Budget(Profile, k, Used(k), Hour(k), stopped)).ToList();
return new EngineSnapshot
{
At = now,
Mode = mode,
Headline = headline,
Details = details,
SidebarLine = sidebar,
ResumesAround = resumes,
Banner = banner,
Profile = Profile.Kind,
ProfileLine = "Profilo «Prudente»",
ReductionNote = null,
Today = strip,
MainBudgets = [.. SnapshotParts.Main.Select(k => budgets.First(b => b.Kind == k))],
AllBudgets = budgets,
ProfilesOpenedToday = budgets.First(b => b.Kind == ActionKind.ProfileOpen),
Queue = Queue(scene, accounts, now, zone, next),
RecentActions = Recent(scene, now, zone, marta, stopAt),
SuspendedRecipes = [],
Breaker = breaker,
};
}
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
yield break;
}
public Task PauseAsync(CancellationToken ct) => Task.CompletedTask;
public Task<ResumeResult> ResumeAsync(CancellationToken ct) =>
Task.FromResult(new ResumeResult(false, "Dimostrazione: il motore è finto e la scena resta quella scelta nell'indirizzo."));
public async Task<CheckNowResult> CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct)
{
var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
if (account is null)
{
return new CheckNowResult(CheckNowStatus.Refused, "Questo account non c'è più nell'elenco di Febe.");
}
var handle = ItalianText.Handle(account.Username);
var now = clock.Now;
var zone = clock.LocalZone;
switch (CurrentScene)
{
case DemoScene.Stopped:
return new CheckNowResult(CheckNowStatus.Refused, "Febe è fermo per una verifica: completala nel browser e premi «Riprendi». Il controllo non parte.");
case DemoScene.Disconnected:
return new CheckNowResult(CheckNowStatus.Refused, "Febe non è collegato a Instagram: collegalo prima di chiedere un controllo.");
}
if (!CheckPolicy.AllowsManualCheck(account))
{
return new CheckNowResult(
CheckNowStatus.Refused,
account.State == AccountState.ArchiveOnly ? $"{handle} è «Solo archivio»: Febe non lo contatta." : $"{handle} è privato e non lo segui: Febe non lo apre.");
}
var inWindow = now >= world.WindowStart && now < world.WindowEnd;
if (!inWindow && string.IsNullOrEmpty(confirmationToken))
{
return new CheckNowResult(
CheckNowStatus.NeedsConfirmation,
$"Sei fuori dalla fascia oraria, quando Febe non apre nulla da solo. Di solito riprende {ItalianText.Around(world.NextWindowStart, now, zone)}. Confermi un solo controllo di {handle} adesso?",
"dimostrazione-" + accountId.ToString(CultureInfo.InvariantCulture));
}
if (!inWindow)
{
return new CheckNowResult(CheckNowStatus.Queued, $"Controllo di {handle} confermato: è l'unico che Febe fa fuori fascia.", null, now);
}
var start = world.NextSession is { } n && n > now ? n : now + TimeSpan.FromMinutes(6);
return new CheckNowResult(
CheckNowStatus.Queued,
$"Controllo di {handle} in cima alla coda: parte {ItalianText.Around(start, now, zone)}, dopo la pausa minima fra due sessioni.",
null,
start);
}
public async Task RequestFollowingListAsync(CancellationToken ct)
{
// The demo pretends the reading started and is half-way: the dialog shows the progress of spec §4.2.
await storage.Settings.SetManyAsync(
new Dictionary<string, string?>
{
[RecipeRunner.FollowingKeys.StartedAt] = clock.Now.ToString("O", CultureInfo.InvariantCulture),
[RecipeRunner.FollowingKeys.Read] = "96",
},
ct).ConfigureAwait(false);
}
public Task NotifyAccountsChangedAsync(CancellationToken ct) => Task.CompletedTask;
private IReadOnlyList<QueueItem> Queue(DemoScene scene, IReadOnlyList<Account> accounts, DateTimeOffset now, TimeZoneInfo zone, DateTimeOffset? next)
{
var suspended = scene is DemoScene.Stopped or DemoScene.Disconnected;
var items = new List<QueueItem>();
var id = 1L;
string When(DateTimeOffset? at) => suspended ? "Sospeso" : at is { } a ? (scene == DemoScene.Session && a <= now + TimeSpan.FromMinutes(4) ? "In questa sessione" : ItalianText.Around(a, now, zone)) : "Sospeso";
if (scene == DemoScene.Disconnected)
{
return items;
}
var sweep = scene == DemoScene.Session ? now + TimeSpan.FromMinutes(46) : next;
items.Add(new QueueItem(id++, EngineTaskKind.FollowingSweep, null, "Giro dei profili che segui", "Home e barra delle storie", suspended ? null : sweep, When(sweep), false, suspended));
if (scene == DemoScene.Session)
{
var marta = accounts.FirstOrDefault(a => a.Username == "marta.demo");
if (marta is not null)
{
items.Insert(0, new QueueItem(id++, EngineTaskKind.AccountStories, marta.Id, ItalianText.Handle(marta.Username), "Storie segnalate dalla barra", now, "In questa sessione", false, false));
}
}
foreach (var account in accounts.Where(CheckPolicy.IsContactable).Where(a => a.NextProfileCheckAt is not null).OrderBy(a => a.NextProfileCheckAt).Take(7))
{
var detail = account.State == AccountState.Backfilling
? "Storico, altri " + ItalianText.Number(Math.Min(account.Limits.BackfillPostsPerDay, 120)) + " post"
: account.IsFollowed ? "Riconciliazione del profilo" : CheckPolicy.WantsStories(account) ? "Nuovi post e storie" : "Nuovi post";
var at = account.NextProfileCheckAt!.Value < now ? now : account.NextProfileCheckAt.Value;
items.Add(new QueueItem(id++, account.State == AccountState.Backfilling ? EngineTaskKind.Backfill : EngineTaskKind.ProfileCheck, account.Id, ItalianText.Handle(account.Username), detail, suspended ? null : at, When(at), false, suspended));
}
return items;
}
private IReadOnlyList<RecentActionView> Recent(DemoScene scene, DateTimeOffset now, TimeZoneInfo zone, string marta, DateTimeOffset stopAt)
{
var list = new List<RecentActionView>();
if (scene == DemoScene.Disconnected)
{
return list;
}
if (scene == DemoScene.Session)
{
list.Add(new RecentActionView(now, ItalianText.Clock(now, zone), $"@{marta}", "Storie, in corso", "In corso", true));
}
if (scene == DemoScene.Stopped)
{
list.Add(new RecentActionView(stopAt, ItalianText.Clock(stopAt, zone), "Verifica richiesta", "Pagina di verifica aperta durante @giulia.corre.demo", "Tutto fermo", false));
}
list.AddRange(world.Recent.Where(r => r.At <= (scene == DemoScene.Stopped ? stopAt : now))
.Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false)));
return list.Take(10).ToList();
}
}
/// <summary>Native functions of the demo: they pretend to work when the demo imitates the desktop, and touch nothing.</summary>
public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INativeShell, IBrowserWindow
{
private bool Desktop => DemoRequest.Edition(accessor.HttpContext) != FebeEdition.Docker;
public bool CanPickFolder => Desktop;
public bool CanShowInFolder => Desktop;
public bool CanOpenUrl => false;
public bool CanNotify => Desktop;
public bool SupportsAutostart => Desktop;
public bool IsSeparateWindow => Desktop;
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) =>
Task.FromResult<string?>(Desktop ? Path.Combine(root, "altre-cartelle", Path.GetFileName(Path.TrimEndingDirectorySeparator(initialFolder ?? "cartella"))) : null);
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(Desktop);
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false);
public Task NotifyAsync(string title, string message, CancellationToken ct) => Task.CompletedTask;
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(true);
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
public Task ShowAsync(CancellationToken ct) => Task.CompletedTask;
}
/// <summary>Files of the demo: the shared sample pictures. Videos have only their cover.</summary>
public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
{
public string? Resolve(Account account, Media media)
{
ArgumentNullException.ThrowIfNull(media);
return media.Kind == MediaKind.Photo && media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null;
}
}
+134
View File
@@ -0,0 +1,134 @@
using Febe.Core.Abstractions;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Web.Engine;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Web.Demo;
/// <summary>Options of <c>--demo</c>.</summary>
/// <param name="Port">Port on 127.0.0.1 (8480 by default; 0 picks a free one).</param>
/// <param name="Zone">Alberto's time zone for the demo (the system zone by default).</param>
/// <param name="Root">Parent of the temporary folder (the system temporary folder by default).</param>
/// <param name="InterfaceFolder">Development: serve the interface from this folder (see <see cref="FebeWebOptions.InterfaceFolder"/>).</param>
public sealed record DemoOptions(int Port = FebeListen.DefaultPort, TimeZoneInfo? Zone = null, string? Root = null, string? InterfaceFolder = null);
/// <summary>
/// Demo mode (spec §10.6): starts without browser and network, listening only on 127.0.0.1 and without password, with
/// a temporary Data folder and a temporary library seeded with coherent demo data. It cannot write to the real
/// library: every path lives under a new temporary folder, removed when the demo ends.
/// </summary>
public sealed class DemoHost : IAsyncDisposable
{
private readonly FebeDatabase _database;
private DemoHost(string root, FebeDatabase database, WebApplication app, DemoWorld world, Uri address)
{
Root = root;
_database = database;
App = app;
World = world;
Address = address;
}
/// <summary>The temporary folder of this demo (Data and library inside).</summary>
public string Root { get; }
public WebApplication App { get; }
public DemoWorld World { get; }
/// <summary>Where the interface answers, e.g. http://127.0.0.1:8480/.</summary>
public Uri Address { get; }
public IFebeStorage Storage => _database;
public static async Task<DemoHost> StartAsync(DemoOptions options, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(options);
var root = Path.Combine(options.Root ?? Path.GetTempPath(), "febe-dimostrazione-" + Guid.NewGuid().ToString("N")[..10]);
Directory.CreateDirectory(root);
FebeDatabase? database = null;
try
{
var clock = new SystemClock(options.Zone ?? TimeZoneInfo.Local);
var data = new DataFolderLayout(Path.Combine(root, "dati"));
var layout = new LibraryLayout(Path.Combine(root, "libreria"));
Directory.CreateDirectory(data.Root);
Directory.CreateDirectory(layout.Root);
database = await FebeDatabase.OpenAsync(data.Root, ct).ConfigureAwait(false);
await database.Settings.SetAsync(SettingKeys.LibraryRoot, layout.Root, ct).ConfigureAwait(false);
var world = await DemoSeeder.SeedAsync(database, data, layout, clock, ct).ConfigureAwait(false);
var library = new FebeLibrary(database, data, layout, clock);
var web = new FebeWebOptions
{
Edition = FebeEdition.Desktop,
Access = AccessMode.None,
AllowedHosts = FebeWebOptions.LoopbackHosts(options.Port),
Demo = true,
InterfaceFolder = options.InterfaceFolder,
};
var db = database;
var app = FebeWebHost.Build(web, FebeListen.Loopback(options.Port), services =>
{
services.AddSingleton<IFebeStorage>(db);
services.AddSingleton(library);
services.AddSingleton<IClock>(clock);
services.AddSingleton(world);
services.AddSingleton<DemoEngine>();
services.AddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<DemoEngine>());
services.AddSingleton<IEngineControl>(sp => sp.GetRequiredService<DemoEngine>());
services.AddSingleton(sp => new DemoShell(sp.GetRequiredService<IHttpContextAccessor>(), root));
services.AddSingleton<INativeShell>(sp => sp.GetRequiredService<DemoShell>());
services.AddSingleton<IBrowserWindow>(sp => sp.GetRequiredService<DemoShell>());
services.AddSingleton<IMediaFileResolver, DemoFileResolver>();
});
await app.StartAsync(ct).ConfigureAwait(false);
return new DemoHost(root, database, app, world, FebeWebHost.BoundAddress(app));
}
catch
{
if (database is not null)
{
await database.DisposeAsync().ConfigureAwait(false);
}
TryDelete(root);
throw;
}
}
public async ValueTask DisposeAsync()
{
try
{
await App.StopAsync().ConfigureAwait(false);
}
finally
{
await App.DisposeAsync().ConfigureAwait(false);
await _database.DisposeAsync().ConfigureAwait(false);
TryDelete(Root);
}
}
private static void TryDelete(string root)
{
try
{
Directory.Delete(root, recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
}
+587
View File
@@ -0,0 +1,587 @@
using SkiaSharp;
namespace Febe.Web.Demo;
/// <summary>Subjects of the demo pictures, in the flat style of the mockups.</summary>
public enum DemoSubject
{
Hills,
Road,
Mountains,
Sunset,
Sea,
CityNight,
Leaves,
Flowers,
Food,
Portrait,
Room,
Bokeh,
Concert,
Houses,
}
/// <summary>
/// Flat illustrations for the demo library (spec §10.6: «le fotografie sono disegni generati»): landscapes, sunsets,
/// mountains, the sea with a sail, the city at night, plants, food, portraits, rooms. Deterministic for a seed.
/// They are drawings, never photographs, and never come from the network.
/// </summary>
public static class DemoImages
{
public static IReadOnlyList<DemoSubject> Subjects { get; } = Enum.GetValues<DemoSubject>();
/// <summary>A JPEG of the subject at the given size.</summary>
public static byte[] Render(DemoSubject subject, int seed, int width, int height, int quality = 84)
{
ArgumentOutOfRangeException.ThrowIfLessThan(width, 16);
ArgumentOutOfRangeException.ThrowIfLessThan(height, 16);
using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
using (var canvas = new SKCanvas(bitmap))
{
var painter = new Painter(canvas, width, height, new Random(seed * 7919 + (int)subject));
switch (subject)
{
case DemoSubject.Hills: painter.Hills(road: false); break;
case DemoSubject.Road: painter.Hills(road: true); break;
case DemoSubject.Mountains: painter.Mountains(); break;
case DemoSubject.Sunset: painter.Sunset(); break;
case DemoSubject.Sea: painter.Sea(); break;
case DemoSubject.CityNight: painter.City(); break;
case DemoSubject.Leaves: painter.Leaves(flowers: false); break;
case DemoSubject.Flowers: painter.Leaves(flowers: true); break;
case DemoSubject.Food: painter.Food(); break;
case DemoSubject.Portrait: painter.Portrait(); break;
case DemoSubject.Room: painter.Room(); break;
case DemoSubject.Bokeh: painter.Bokeh(); break;
case DemoSubject.Concert: painter.Concert(); break;
case DemoSubject.Houses: painter.Houses(); break;
default: painter.Hills(road: false); break;
}
}
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality);
return data.ToArray();
}
private sealed class Painter(SKCanvas canvas, float w, float h, Random random)
{
private float R(float min, float max) => min + ((float)random.NextDouble() * (max - min));
private T Pick<T>(params T[] items) => items[random.Next(items.Length)];
private static SKColor C(uint rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
private static SKColor Mix(SKColor a, SKColor b, float t) => new(
(byte)(a.Red + ((b.Red - a.Red) * t)),
(byte)(a.Green + ((b.Green - a.Green) * t)),
(byte)(a.Blue + ((b.Blue - a.Blue) * t)));
private void Gradient(SKRect rect, SKColor top, SKColor bottom)
{
using var paint = new SKPaint { IsAntialias = true };
paint.Shader = SKShader.CreateLinearGradient(new SKPoint(0, rect.Top), new SKPoint(0, rect.Bottom), [top, bottom], null, SKShaderTileMode.Clamp);
canvas.DrawRect(rect, paint);
}
private void Fill(SKPathBuilder builder, SKColor color)
{
using var path = builder.Detach();
using var paint = new SKPaint { IsAntialias = true, Color = color, Style = SKPaintStyle.Fill };
canvas.DrawPath(path, paint);
}
private void Circle(float x, float y, float r, SKColor color)
{
using var paint = new SKPaint { IsAntialias = true, Color = color };
canvas.DrawCircle(x, y, r, paint);
}
private void Oval(float cx, float cy, float rx, float ry, SKColor color, float rotate = 0)
{
using var paint = new SKPaint { IsAntialias = true, Color = color };
canvas.Save();
canvas.Translate(cx, cy);
canvas.RotateDegrees(rotate);
canvas.DrawOval(new SKRect(-rx, -ry, rx, ry), paint);
canvas.Restore();
}
private void Rect(float x, float y, float rw, float rh, SKColor color, float radius = 0)
{
using var paint = new SKPaint { IsAntialias = true, Color = color };
canvas.DrawRoundRect(new SKRect(x, y, x + rw, y + rh), radius, radius, paint);
}
/// <summary>A soft ridge across the picture at height <paramref name="baseY"/>, filled down to the bottom.</summary>
private static SKPathBuilder Ridge(float w, float h, float baseY, float amplitude, int bumps, float phase)
{
var path = new SKPathBuilder();
path.MoveTo(0, h);
const int steps = 48;
for (var i = 0; i <= steps; i++)
{
var x = w * i / steps;
var y = baseY - (amplitude * (float)(Math.Sin((i / (double)steps * bumps * Math.PI) + phase) * 0.6 + (Math.Sin((i / (double)steps * bumps * 2.3 * Math.PI) + phase * 1.7) * 0.4)));
path.LineTo(x, y);
}
path.LineTo(w, h);
path.Close();
return path;
}
private void Clouds(float top, float bottom, int count)
{
for (var i = 0; i < count; i++)
{
var cx = R(-0.1f, 1.1f) * w;
var cy = R(top, bottom) * h;
var size = R(0.07f, 0.13f) * Math.Max(w, h);
var color = new SKColor(255, 255, 255, (byte)R(200, 240));
Oval(cx, cy, size, size * 0.32f, color);
Oval(cx - (size * 0.35f), cy + (size * 0.05f), size * 0.55f, size * 0.25f, color);
Oval(cx + (size * 0.25f), cy - (size * 0.12f), size * 0.5f, size * 0.3f, new SKColor(255, 255, 255, (byte)R(220, 250)));
}
}
private void Cypress(float x, float baseY, float size, SKColor color)
{
Oval(x, baseY - (size * 0.55f), size * 0.22f, size * 0.55f, color);
Rect(x - (size * 0.03f), baseY - (size * 0.08f), size * 0.06f, size * 0.12f, Mix(color, SKColors.Black, 0.3f));
}
public void Hills(bool road)
{
var sky = Pick(C(0x6FA8DC), C(0x7FB3E0), C(0x5E9BD6), C(0x8DBBE3));
Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.45f));
Clouds(0.08f, 0.35f, random.Next(2, 5));
var greens = Pick(
new[] { C(0x8DB867), C(0x6E9E4C), C(0x4F8A3E), C(0x3C7232) },
new[] { C(0x9CC27A), C(0x7DAE5A), C(0x5F9447), C(0x447A36) },
new[] { C(0xA3C46C), C(0x86AE55), C(0x6A9842), C(0x4E7F33) });
var baseY = h * R(0.48f, 0.58f);
for (var layer = 0; layer < 4; layer++)
{
var y = baseY + (layer * h * R(0.08f, 0.12f));
using var ridge = Ridge(w, h, y, h * R(0.015f, 0.04f), random.Next(1, 4), R(0, 6));
Fill(ridge, greens[layer]);
if (!road && layer < 3)
{
for (var t = 0; t < random.Next(1, 4); t++)
{
Cypress(R(0.05f, 0.95f) * w, y + (h * 0.03f), h * R(0.05f, 0.08f), C(0x2E4A22));
}
}
}
if (road)
{
var horizon = baseY + (h * 0.03f);
using var path = new SKPathBuilder();
path.MoveTo(w * 0.47f, horizon);
path.LineTo(w * 0.53f, horizon);
path.LineTo(w * 0.86f, h);
path.LineTo(w * 0.14f, h);
path.Close();
Fill(path, C(0x4A4D52));
for (var i = 0; i < 6; i++)
{
var t0 = i / 6f;
var y0 = horizon + ((h - horizon) * t0 * t0) + 4;
var y1 = horizon + ((h - horizon) * (t0 + 0.07f) * (t0 + 0.07f));
var half = 1 + (t0 * w * 0.008f);
Rect((w * 0.5f) - half, y0, half * 2, Math.Max(2, y1 - y0), C(0xF2F2F2));
}
foreach (var side in new[] { 0.08f, 0.9f, 0.3f, 0.72f })
{
var size = h * R(0.1f, 0.18f);
var x = side * w;
var y = horizon + (h * R(0.12f, 0.3f));
Rect(x - (size * 0.03f), y - (size * 0.2f), size * 0.06f, size * 0.25f, C(0x3B2F22));
Oval(x, y - (size * 0.45f), size * 0.22f, size * 0.32f, C(0x2F5A27));
}
}
}
public void Mountains()
{
var sky = Pick(C(0x5D8FC8), C(0x6E9BD0), C(0x7FA8D6));
Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.55f));
var ranges = new[] { C(0x8C9BB2), C(0x6F7F99), C(0x56647E) };
for (var r = 0; r < 3; r++)
{
var baseY = h * (0.55f + (r * 0.08f));
var peaks = random.Next(2, 4) + r;
using var path = new SKPathBuilder();
path.MoveTo(0, h);
path.LineTo(0, baseY);
var snow = new List<(float X, float Y, float Half)>();
for (var p = 0; p < peaks; p++)
{
var px = (p + 0.5f) / peaks * w + R(-0.06f, 0.06f) * w;
var py = baseY - (h * R(0.18f, 0.32f) * (1 - (r * 0.2f)));
var half = w / peaks * 0.5f;
path.LineTo(px - half, baseY);
path.LineTo(px, py);
path.LineTo(px + half, baseY);
snow.Add((px, py, half));
}
path.LineTo(w, baseY);
path.LineTo(w, h);
path.Close();
Fill(path, ranges[r]);
if (r < 2)
{
foreach (var (px, py, half) in snow)
{
var depth = (baseY - py) * 0.32f;
var ratio = depth / (baseY - py);
using var cap = new SKPathBuilder();
cap.MoveTo(px, py);
cap.LineTo(px + (half * ratio), py + depth);
cap.LineTo(px + (half * ratio * 0.3f), py + (depth * 0.8f));
cap.LineTo(px, py + depth);
cap.LineTo(px - (half * ratio * 0.4f), py + (depth * 0.85f));
cap.LineTo(px - (half * ratio), py + depth);
cap.Close();
Fill(cap, C(0xF4F6F8));
}
}
}
var forest = C(0x2D4A33);
var groundY = h * 0.86f;
Rect(0, groundY, w, h - groundY, C(0x34553A));
for (var i = 0; i < 26; i++)
{
var x = R(0, 1) * w;
var size = h * R(0.06f, 0.11f);
var y = groundY + (h * R(-0.01f, 0.08f));
using var tree = new SKPathBuilder();
tree.MoveTo(x, y - size);
tree.LineTo(x + (size * 0.28f), y);
tree.LineTo(x - (size * 0.28f), y);
tree.Close();
Fill(tree, forest);
}
}
public void Sunset()
{
var top = Pick(C(0x3B2A5A), C(0x4A2F63), C(0x2E2350));
var bottom = Pick(C(0xF0784C), C(0xE86A5A), C(0xF29A57));
Gradient(new SKRect(0, 0, w, h * 0.75f), top, bottom);
var sunX = w * R(0.35f, 0.65f);
var sunY = h * R(0.5f, 0.6f);
var r = Math.Min(w, h) * R(0.09f, 0.13f);
Circle(sunX, sunY, r * 1.8f, new SKColor(255, 220, 170, 60));
Circle(sunX, sunY, r, C(0xFBE3B0));
var hills = new[] { C(0x6B4A73), C(0x4E3A63), C(0x35294D) };
for (var i = 0; i < 3; i++)
{
using var ridge = Ridge(w, h, h * (0.66f + (i * 0.09f)), h * R(0.02f, 0.05f), random.Next(1, 3), R(0, 6));
Fill(ridge, hills[i]);
}
}
public void Sea()
{
var sky = Pick(C(0x8CC4E8), C(0x7BB8E2), C(0x9CCDEB));
var horizon = h * R(0.42f, 0.55f);
Gradient(new SKRect(0, 0, w, horizon), Mix(sky, C(0x4F8FC8), 0.3f), Mix(sky, SKColors.White, 0.5f));
Clouds(0.08f, 0.25f, random.Next(0, 3));
var water = Pick(C(0x2AA3C1), C(0x1F8FB3), C(0x31A9BE));
var sand = random.Next(3) == 0;
Gradient(new SKRect(0, horizon, w, h), water, Mix(water, C(0x0B4A6B), 0.55f));
using (var wave = new SKPaint { IsAntialias = true, Color = new SKColor(255, 255, 255, 110), StrokeWidth = Math.Max(2, h * 0.004f), StrokeCap = SKStrokeCap.Round })
{
for (var i = 0; i < 9; i++)
{
var y = horizon + ((h - horizon) * R(0.1f, 0.9f));
var x = R(0.05f, 0.85f) * w;
canvas.DrawLine(x, y, x + (w * R(0.03f, 0.08f)), y, wave);
}
}
if (sand)
{
using var shore = Ridge(w, h, h * 0.9f, h * 0.02f, 2, R(0, 6));
Fill(shore, C(0xE9D8B4));
}
var bx = w * R(0.3f, 0.65f);
var by = horizon + ((h - horizon) * R(0.2f, 0.4f));
var s = Math.Min(w, h) * R(0.06f, 0.09f);
using (var sail = new SKPathBuilder())
{
sail.MoveTo(bx, by - s);
sail.LineTo(bx + (s * 0.45f), by - (s * 0.1f));
sail.LineTo(bx, by - (s * 0.1f));
sail.Close();
Fill(sail, C(0xF6F6F4));
}
using (var sail2 = new SKPathBuilder())
{
sail2.MoveTo(bx - (s * 0.04f), by - (s * 0.85f));
sail2.LineTo(bx - (s * 0.04f), by - (s * 0.12f));
sail2.LineTo(bx - (s * 0.38f), by - (s * 0.12f));
sail2.Close();
Fill(sail2, C(0xE0533F));
}
using (var hull = new SKPathBuilder())
{
hull.MoveTo(bx - (s * 0.5f), by - (s * 0.05f));
hull.LineTo(bx + (s * 0.55f), by - (s * 0.05f));
hull.LineTo(bx + (s * 0.4f), by + (s * 0.1f));
hull.LineTo(bx - (s * 0.35f), by + (s * 0.1f));
hull.Close();
Fill(hull, C(0x2B2F36));
}
}
public void City()
{
Gradient(new SKRect(0, 0, w, h), C(0x1E1B3A), Pick(C(0x3E2F5C), C(0x4A3566), C(0x2F2A52)));
for (var i = 0; i < 70; i++)
{
Circle(R(0, 1) * w, R(0, 0.45f) * h, R(0.6f, 1.8f), new SKColor(255, 255, 255, (byte)R(60, 180)));
}
for (var layer = 0; layer < 2; layer++)
{
var x = -R(0, 0.05f) * w;
while (x < w)
{
var bw = w * R(0.07f, 0.16f);
var bh = h * R(0.3f, 0.75f) * (layer == 0 ? 0.85f : 1f);
var shade = layer == 0 ? C(0x2C2B3E) : Pick(C(0x1B1B26), C(0x23222F), C(0x191820));
Rect(x, h - bh, bw, bh, shade);
if (layer == 1)
{
var cell = Math.Max(4, w * 0.018f);
for (var wy = h - bh + cell; wy < h - cell; wy += cell * 1.8f)
{
for (var wx = x + cell * 0.7f; wx < x + bw - cell; wx += cell * 1.5f)
{
if (random.NextDouble() < 0.28)
{
Rect(wx, wy, cell * 0.55f, cell * 0.75f, Pick(C(0xF3C969), C(0xE9B44C), C(0xF7DA8C)));
}
}
}
}
x += bw + (w * R(0, 0.015f));
}
}
}
public void Leaves(bool flowers)
{
var dark = Pick(C(0x1F4D33), C(0x24533A), C(0x2B5C3C));
Gradient(new SKRect(0, 0, w, h), Mix(dark, SKColors.Black, 0.1f), dark);
var greens = new[] { C(0x3E8C4E), C(0x5AA45A), C(0x2F7A45), C(0x78B861), C(0x4C9A6A), C(0x8BC46A) };
var size = Math.Max(w, h);
for (var i = 0; i < 46; i++)
{
var cx = R(-0.1f, 1.1f) * w;
var cy = R(-0.1f, 1.1f) * h;
var rx = size * R(0.05f, 0.11f);
var angle = R(0, 360);
var color = greens[random.Next(greens.Length)];
Oval(cx, cy, rx, rx * 0.42f, color, angle);
using var vein = new SKPaint { IsAntialias = true, Color = Mix(color, SKColors.White, 0.25f), StrokeWidth = Math.Max(1.5f, size * 0.003f) };
canvas.Save();
canvas.Translate(cx, cy);
canvas.RotateDegrees(angle);
canvas.DrawLine(-rx * 0.85f, 0, rx * 0.85f, 0, vein);
canvas.Restore();
}
if (flowers)
{
for (var i = 0; i < 9; i++)
{
var cx = R(0.05f, 0.95f) * w;
var cy = R(0.05f, 0.95f) * h;
var r = size * R(0.025f, 0.04f);
var petal = Pick(C(0xF27BA6), C(0xB57AE0), C(0xF6D55C), C(0xF49A6C));
for (var p = 0; p < 5; p++)
{
var a = p * Math.PI * 2 / 5;
Circle(cx + (float)(Math.Cos(a) * r * 0.8), cy + (float)(Math.Sin(a) * r * 0.8), r * 0.65f, petal);
}
Circle(cx, cy, r * 0.45f, C(0xF7E7A1));
}
}
}
public void Food()
{
var table = Pick(C(0xE9E6E1), C(0xEFEBE4), C(0xDCD7CF));
Rect(0, 0, w, h, table);
using (var line = new SKPaint { IsAntialias = true, Color = Mix(table, SKColors.Black, 0.08f), StrokeWidth = Math.Max(2, w * 0.004f) })
{
for (var y = h * 0.12f; y < h; y += h * 0.16f)
{
canvas.DrawLine(0, y, w, y + (h * 0.01f), line);
}
}
var r = Math.Min(w, h) * R(0.28f, 0.34f);
var cx = w * R(0.42f, 0.55f);
var cy = h * R(0.48f, 0.58f);
using (var shadow = new SKPaint { IsAntialias = true, Color = new SKColor(0, 0, 0, 40), MaskFilter = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, r * 0.06f) })
{
canvas.DrawCircle(cx + (r * 0.04f), cy + (r * 0.06f), r, shadow);
}
Circle(cx, cy, r, C(0xFAFAF8));
Circle(cx, cy, r * 0.78f, C(0xF0EEEA));
var food = Pick(C(0xE8BE55), C(0xE3A548), C(0xD9B25C));
Circle(cx, cy, r * 0.66f, food);
for (var i = 0; i < 16; i++)
{
var a = R(0, (float)(Math.PI * 2));
var d = R(0, r * 0.55f);
Circle(cx + (float)(Math.Cos(a) * d), cy + (float)(Math.Sin(a) * d), r * R(0.04f, 0.075f), Pick(C(0xC0392B), C(0x3E8E41), C(0x7A4A2A), C(0x6BAF5B)));
}
var cupX = w * R(0.78f, 0.86f);
var cupY = h * R(0.12f, 0.2f);
var cr = Math.Min(w, h) * 0.085f;
Circle(cupX, cupY, cr, C(0xF5F3EF));
Circle(cupX, cupY, cr * 0.75f, C(0x5B3A26));
using var fork = new SKPaint { IsAntialias = true, Color = C(0xC9C6C0), StrokeWidth = Math.Max(3, w * 0.008f), StrokeCap = SKStrokeCap.Round };
canvas.DrawLine(cx + (r * 1.18f), cy - (r * 0.5f), cx + (r * 1.18f), cy + (r * 0.75f), fork);
}
public void Portrait()
{
var bg = Pick(C(0xB27FC0), C(0xC98F9B), C(0x8FA8C9), C(0xD3A26F), C(0x7FB8A3), C(0xA88FC7));
Gradient(new SKRect(0, 0, w, h), Mix(bg, SKColors.White, 0.15f), Mix(bg, SKColors.Black, 0.12f));
var skin = Pick(C(0xD9A27B), C(0xC88A63), C(0xA86F4D), C(0xE8B996), C(0x8D5A3B));
var hair = Pick(C(0x8A4B2A), C(0x3B2A20), C(0xD8B45A), C(0x5A3A22), C(0x1F1B18));
var shirt = Pick(C(0xA8B04A), C(0x5F8F57), C(0xB84A4A), C(0x4F6FA8), C(0xE0C35A));
var cx = w * 0.5f;
var unit = Math.Min(w, h * 0.8f);
Oval(cx, h * 1.02f, unit * 0.42f, h * 0.32f, shirt);
Rect(cx - (unit * 0.06f), h * 0.52f, unit * 0.12f, h * 0.16f, Mix(skin, SKColors.Black, 0.08f));
Oval(cx, h * 0.44f, unit * 0.16f, unit * 0.2f, skin);
using var top = new SKPathBuilder();
top.AddArc(new SKRect(cx - (unit * 0.17f), (h * 0.44f) - (unit * 0.22f), cx + (unit * 0.17f), (h * 0.44f) + (unit * 0.04f)), 180, 180);
top.Close();
Fill(top, hair);
}
public void Room()
{
var wall = Pick(C(0xE5DFCF), C(0xE9E2D2), C(0xDCD6C6));
var floorY = h * R(0.68f, 0.74f);
Gradient(new SKRect(0, 0, w, floorY), Mix(wall, SKColors.White, 0.2f), wall);
Gradient(new SKRect(0, floorY, w, h), C(0xC9AE84), C(0xB89A6E));
var winX = w * R(0.25f, 0.45f);
var winW = w * R(0.26f, 0.34f);
var winY = h * 0.1f;
var winH = h * 0.38f;
Rect(winX - 6, winY - 6, winW + 12, winH + 12, C(0xF7F7F5));
Gradient(new SKRect(winX, winY, winX + winW, winY + winH), C(0x9CCBEB), C(0xC9E4F4));
Rect(winX + (winW / 2) - 3, winY, 6, winH, C(0xF7F7F5));
Rect(winX, winY + (winH / 2) - 3, winW, 6, C(0xF7F7F5));
var sofa = Pick(C(0x6E9F7A), C(0x4E8F86), C(0x8A6A9E), C(0xA05A5A));
var sx = w * R(0.05f, 0.15f);
var sw = w * R(0.48f, 0.58f);
Rect(sx, floorY - (h * 0.2f), sw, h * 0.12f, Mix(sofa, SKColors.White, 0.15f), 10);
Rect(sx, floorY - (h * 0.1f), sw, h * 0.12f, sofa, 10);
var px = w * R(0.75f, 0.85f);
using var pot = new SKPathBuilder();
pot.MoveTo(px - (w * 0.045f), floorY - (h * 0.08f));
pot.LineTo(px + (w * 0.045f), floorY - (h * 0.08f));
pot.LineTo(px + (w * 0.035f), floorY + (h * 0.01f));
pot.LineTo(px - (w * 0.035f), floorY + (h * 0.01f));
pot.Close();
Fill(pot, C(0xC7643C));
for (var i = 0; i < 7; i++)
{
var angle = -90 + R(-55, 55);
var len = h * R(0.08f, 0.14f);
var rad = angle * Math.PI / 180;
Oval(px + (float)(Math.Cos(rad) * len * 0.5), floorY - (h * 0.08f) + (float)(Math.Sin(rad) * len * 0.5), len * 0.5f, len * 0.16f, Pick(C(0x3E8C4E), C(0x5AA45A), C(0x2F7A45)), (float)angle);
}
}
public void Bokeh()
{
Gradient(new SKRect(0, 0, w, h), C(0x1B1530), Pick(C(0x2A1E3A), C(0x1E1A2E)));
var colors = new[] { C(0xF2B84B), C(0xE0567A), C(0x6BC5E8), C(0xB06BE0), C(0xF08A4B), C(0x7FD38A) };
var size = Math.Max(w, h);
for (var i = 0; i < 40; i++)
{
var color = colors[random.Next(colors.Length)].WithAlpha((byte)R(90, 200));
using var paint = new SKPaint { IsAntialias = true, Color = color, MaskFilter = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, size * R(0.004f, 0.012f)) };
canvas.DrawCircle(R(0, 1) * w, R(0, 1) * h, size * R(0.02f, 0.06f), paint);
}
}
public void Concert()
{
Gradient(new SKRect(0, 0, w, h), C(0x14121C), C(0x1E1A2A));
var beams = new[] { C(0xE04A5A), C(0xF2C14B), C(0x4A7FE0), C(0xA04AE0), C(0x4AC0E0) };
for (var i = 0; i < 5; i++)
{
var x = w * (0.12f + (i * 0.19f)) + R(-0.04f, 0.04f) * w;
var color = beams[random.Next(beams.Length)];
using var paint = new SKPaint { IsAntialias = true };
paint.Shader = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, h * 0.75f), [color.WithAlpha(40), color.WithAlpha(190)], null, SKShaderTileMode.Clamp);
using var beam = new SKPathBuilder();
beam.MoveTo(x, 0);
beam.LineTo(x + (w * R(-0.12f, 0.12f)) + (w * 0.08f), h * 0.75f);
beam.LineTo(x + (w * R(-0.12f, 0.12f)) - (w * 0.08f), h * 0.75f);
beam.Close();
using var beamPath = beam.Detach();
canvas.DrawPath(beamPath, paint);
}
Rect(0, h * 0.72f, w, h * 0.04f, C(0x2B2838));
for (var i = 0; i < 28; i++)
{
Circle(R(0, 1) * w, h * R(0.86f, 0.98f), Math.Min(w, h) * R(0.03f, 0.05f), C(0x0D0C12));
}
Rect(0, h * 0.9f, w, h * 0.1f, C(0x0D0C12));
}
public void Houses()
{
var sky = Pick(C(0x8CC4E8), C(0x9CCDEB));
Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.4f));
var facades = new[] { C(0xF2C55C), C(0xE88B6A), C(0xF0A3A0), C(0xE5D37A), C(0xD9774F), C(0x9FC7B4), C(0xF4E2B8) };
var x = 0f;
while (x < w)
{
var fw = w * R(0.18f, 0.3f);
var top = h * R(0.12f, 0.4f);
var color = facades[random.Next(facades.Length)];
Rect(x, top, fw, h - top, color);
Rect(x, top, fw, h * 0.02f, Mix(color, SKColors.Black, 0.2f));
var cell = fw / 5;
for (var wy = top + (cell * 0.8f); wy < h - cell; wy += cell * 1.4f)
{
for (var wx = x + (cell * 0.6f); wx < x + fw - (cell * 0.8f); wx += cell * 1.3f)
{
Rect(wx, wy, cell * 0.55f, cell * 0.85f, C(0x3C3A3A));
Rect(wx - (cell * 0.1f), wy, cell * 0.08f, cell * 0.85f, C(0x4E7F5A));
}
}
x += fw;
}
}
}
}
+107
View File
@@ -0,0 +1,107 @@
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Demo;
/// <summary>Scenes of the demo engine (spec §10.6), chosen by address: <c>?scena=…</c>.</summary>
public enum DemoScene
{
/// <summary>«normale»: between two sessions, «In ascolto».</summary>
Normal,
/// <summary>«sessione»: a session in progress.</summary>
Session,
/// <summary>«fermo»: stopped for a verification, red strip on every page.</summary>
Stopped,
/// <summary>«scollegato»: no Instagram session yet.</summary>
Disconnected,
}
/// <summary>
/// Per-request choices of the demo: the scene (<c>scena</c>) and the shell it imitates (<c>veste</c>: desktop or docker).
/// The page carries them on every call as query parameters or headers (<c>X-Febe-Scena</c>, <c>X-Febe-Veste</c>), so
/// every page stays in the chosen scene. Outside the demo they are ignored.
/// </summary>
public static class DemoRequest
{
public const string SceneQuery = "scena";
public const string EditionQuery = "veste";
public const string SceneHeader = "X-Febe-Scena";
public const string EditionHeader = "X-Febe-Veste";
private const string SceneItem = "febe.demo.scena";
private const string EditionItem = "febe.demo.veste";
public static IReadOnlyList<string> SceneNames { get; } = ["normale", "sessione", "fermo", "scollegato"];
public static DemoScene? ParseScene(string? text) => text?.Trim().ToLowerInvariant() switch
{
"normale" => DemoScene.Normal,
"sessione" => DemoScene.Session,
"fermo" => DemoScene.Stopped,
"scollegato" => DemoScene.Disconnected,
_ => null,
};
public static string SceneName(DemoScene scene) => scene switch
{
DemoScene.Session => "sessione",
DemoScene.Stopped => "fermo",
DemoScene.Disconnected => "scollegato",
_ => "normale",
};
public static FebeEdition? ParseEdition(string? text) => text?.Trim().ToLowerInvariant() switch
{
"desktop" or "windows" => FebeEdition.Desktop,
"docker" => FebeEdition.Docker,
_ => null,
};
/// <summary>The scene of this request (normal when not given).</summary>
public static DemoScene Scene(HttpContext? context) =>
context?.Items.TryGetValue(SceneItem, out var value) == true && value is DemoScene scene ? scene : DemoScene.Normal;
/// <summary>The shell this request imitates, or null when not given.</summary>
public static FebeEdition? Edition(HttpContext? context) =>
context?.Items.TryGetValue(EditionItem, out var value) == true && value is FebeEdition edition ? edition : null;
internal static void Capture(HttpContext context)
{
var scene = ParseScene(First(context, SceneQuery, SceneHeader));
if (scene is not null)
{
context.Items[SceneItem] = scene.Value;
}
var edition = ParseEdition(First(context, EditionQuery, EditionHeader));
if (edition is not null)
{
context.Items[EditionItem] = edition.Value;
}
}
private static string? First(HttpContext context, string query, string header)
{
var fromQuery = context.Request.Query[query].ToString();
if (fromQuery.Length > 0)
{
return fromQuery;
}
var fromHeader = context.Request.Headers[header].ToString();
return fromHeader.Length > 0 ? fromHeader : null;
}
}
/// <summary>Reads the demo choices of each request (registered only in demo mode).</summary>
public sealed class DemoRequestMiddleware(RequestDelegate next)
{
public Task InvokeAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
DemoRequest.Capture(context);
return next(context);
}
}
File diff suppressed because it is too large. Load diff
+188
View File
@@ -0,0 +1,188 @@
using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Web.Engine;
/// <summary>
/// The commands the interface sends to the engine (spec §7.8, §4.2). The real implementation is
/// <see cref="EngineHostControl"/>; the demo has its own; without an engine <see cref="OfflineEngine"/> refuses politely.
/// What the engine shows is <see cref="IEngineMonitor"/> (Febe.Core).
/// </summary>
public interface IEngineControl
{
/// <summary>«Metti in pausa».</summary>
Task PauseAsync(CancellationToken ct);
/// <summary>«Riprendi».</summary>
Task<ResumeResult> ResumeAsync(CancellationToken ct);
/// <summary>«Controlla ora», with the confirmation token outside the active window.</summary>
Task<CheckNowResult> CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct);
/// <summary>«Rileggi l'elenco» of the profiles Alberto follows.</summary>
Task RequestFollowingListAsync(CancellationToken ct);
/// <summary>Accounts were added, removed or changed: the engine brings its queue in step.</summary>
Task NotifyAccountsChangedAsync(CancellationToken ct);
}
/// <summary>The commands of the interface on the real engine.</summary>
public sealed class EngineHostControl(EngineHost host) : IEngineControl
{
public Task PauseAsync(CancellationToken ct) => host.PauseAsync(ct);
public Task<ResumeResult> ResumeAsync(CancellationToken ct) => host.ResumeAsync(ct);
public Task<CheckNowResult> CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct) =>
host.CheckNowAsync(accountId, confirmationToken, ct);
public Task RequestFollowingListAsync(CancellationToken ct) => host.RequestFollowingListAsync(ct);
public Task NotifyAccountsChangedAsync(CancellationToken ct) => host.NotifyAccountsChangedAsync(ct);
}
/// <summary>
/// When the browser was last used by Alberto: «Riprendi» after a verification becomes active only after he used the
/// browser (mockup 11). The Browser page («Ho finito») and the desktop window report it.
/// </summary>
public sealed class BrowserUseTracker
{
private long _lastUsedTicks;
public DateTimeOffset? LastUsedAt
{
get
{
var ticks = Interlocked.Read(ref _lastUsedTicks);
return ticks == 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero);
}
}
public void MarkUsed(DateTimeOffset at) => Interlocked.Exchange(ref _lastUsedTicks, at.UtcTicks);
}
/// <summary>No engine in this process (it has not been wired yet, or the configuration stopped it): «Motore spento».</summary>
public sealed class OfflineEngine(IClock clock) : IEngineMonitor, IEngineControl
{
private const string Off = "Il motore non è in funzione.";
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
Task.FromResult(SnapshotParts.Build(clock, EngineMode.Off, "Motore spento", [Off], "Motore spento", CautionProfile.Prudent));
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
yield break;
}
public Task PauseAsync(CancellationToken ct) => Task.CompletedTask;
public Task<ResumeResult> ResumeAsync(CancellationToken ct) => Task.FromResult(new ResumeResult(false, Off));
public Task<CheckNowResult> CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct) =>
Task.FromResult(new CheckNowResult(CheckNowStatus.Refused, Off + " Il controllo non parte."));
public Task RequestFollowingListAsync(CancellationToken ct) => Task.CompletedTask;
public Task NotifyAccountsChangedAsync(CancellationToken ct) => Task.CompletedTask;
}
/// <summary>Pieces for building snapshots outside <see cref="EngineMonitor"/> (offline engine, demo).</summary>
public static class SnapshotParts
{
/// <summary>The four main budgets in the order of the Attività page.</summary>
public static readonly ActionKind[] Main = [ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.DataDownload];
/// <summary>Every category in the order of the table of spec §7.5.</summary>
public static readonly ActionKind[] All =
[ActionKind.Home, ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.SinglePost, ActionKind.FollowingListPage, ActionKind.DataDownload];
/// <summary>A minimal snapshot: no sessions, empty budgets.</summary>
public static EngineSnapshot Build(IClock clock, EngineMode mode, string headline, IReadOnlyList<string> details, string sidebar, CautionProfile profile)
{
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(profile);
var now = clock.Now;
var zone = clock.LocalZone;
var day = LocalCalendar.Today(now, zone);
var (start, end) = LocalCalendar.DayBounds(day, zone);
var budgets = All.Select(k => Budget(profile, k, 0, 0, null)).ToList();
return new EngineSnapshot
{
At = now,
Mode = mode,
Headline = headline,
Details = details,
SidebarLine = sidebar,
Profile = profile.Kind,
ProfileLine = $"Profilo «{ItalianText.Profile(profile.Kind)}»",
Today = new DayStrip(day, start, end, now, "Nessuna sessione oggi", []),
MainBudgets = [.. Main.Select(k => budgets.First(b => b.Kind == k))],
AllBudgets = budgets,
ProfilesOpenedToday = budgets.First(b => b.Kind == ActionKind.ProfileOpen),
Queue = [],
RecentActions = [],
SuspendedRecipes = [],
Breaker = BreakerState.Normal,
};
}
/// <summary>A budget as the interface shows it, with the same wording as the real monitor.</summary>
/// <param name="profile">Profile with the limits.</param>
/// <param name="kind">Category.</param>
/// <param name="usedToday">Used today (bytes for data).</param>
/// <param name="usedLastHour">Used in the last hour (ignored for data).</param>
/// <param name="stoppedNote">«Fermo dalle 16:32» while the engine is stopped; null otherwise.</param>
public static BudgetView Budget(CautionProfile profile, ActionKind kind, long usedToday, long usedLastHour, string? stoppedNote)
{
ArgumentNullException.ThrowIfNull(profile);
var data = kind == ActionKind.DataDownload;
long limitToday = data ? profile.DataPerDayBytes : profile.Budgets[kind].PerDay;
long? limitHour = data ? null : profile.Budgets[kind].PerHour;
var status = new BudgetStatus(kind, usedToday, limitToday, data ? null : usedLastHour, limitHour);
string note;
if (stoppedNote is not null && !data)
{
note = stoppedNote;
}
else if (status.DailyReached)
{
note = "Tetto di oggi raggiunto: riprende domani";
}
else if (status.HourlyReached)
{
note = "Tetto orario raggiunto: riprende entro un'ora";
}
else if (status.DailyRatio >= BudgetStatus.AmberThreshold)
{
note = "Quasi al limite per oggi";
}
else if (status.HourlyRatio >= BudgetStatus.AmberThreshold)
{
note = "Quasi al limite di quest'ora";
}
else if (data)
{
note = "Restano " + ItalianText.Bytes(Math.Max(0, limitToday - usedToday));
}
else
{
note = $"In questa ora {ItalianText.Number(usedLastHour)} di {ItalianText.Number(limitHour ?? 0)}";
}
return new BudgetView(
kind,
ItalianText.CategoryLabel(kind),
usedToday,
limitToday,
status.UsedLastHour,
limitHour,
status.IsAmber,
Math.Clamp(status.DailyRatio, 0, 1),
data ? ItalianText.Bytes(usedToday) : ItalianText.Number(usedToday),
"di " + (data ? ItalianText.Bytes(limitToday) : ItalianText.Number(limitToday)),
note);
}
}
+193
View File
@@ -0,0 +1,193 @@
using System.Net;
using Febe.Core.Abstractions;
using Febe.Core.Engine;
using Febe.Web.Api;
using Febe.Web.Demo;
using Febe.Web.Engine;
using Febe.Web.Hosting;
using Febe.Web.Library;
using Febe.Web.Native;
using Febe.Web.Security;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
namespace Febe.Web;
/// <summary>
/// The web application of Febe, the same for both shells (spec §5): API under <c>/api</c>, server-sent events at
/// <c>/api/eventi</c>, the interface files embedded in this assembly, and the Italian page addresses
/// (<c>/libreria</c>, <c>/account/12</c>, <c>/impostazioni/generali</c> …) answered with the application page.
/// <code>
/// var app = FebeWebHost.Build(options, FebeListen.Loopback(port), services =>
/// {
/// services.AddSingleton&lt;IFebeStorage&gt;(db);
/// services.AddSingleton(library); // FebeLibrary
/// services.AddSingleton&lt;IClock&gt;(clock);
/// services.AddSingleton(engine.Monitor); // IEngineMonitor (optional)
/// services.AddSingleton&lt;IEngineControl&gt;(new EngineHostControl(engine)); // optional
/// services.AddSingleton&lt;INativeShell&gt;(shell); // desktop only
/// });
/// await app.StartAsync();
/// </code>
/// </summary>
public static class FebeWeb
{
/// <summary>
/// Registers the web layer. Register <c>IFebeStorage</c>, <see cref="FebeLibrary"/> and <see cref="IClock"/> as
/// well; everything else has a default (no engine, no native functions, files from the library layout) that a
/// registration made before this call replaces.
/// </summary>
public static IServiceCollection AddFebeWeb(this IServiceCollection services, FebeWebOptions options)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(options);
services.AddSingleton(options);
services.TryAddSingleton<INativeShell>(BrowserShell.Instance);
services.TryAddSingleton<IBrowserWindow, NoBrowserWindow>();
services.TryAddSingleton<IMediaFileResolver, LibraryFileResolver>();
services.TryAddSingleton<LibraryChanges>();
services.TryAddSingleton<BrowserUseTracker>();
services.TryAddSingleton<OfflineEngine>();
services.TryAddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<OfflineEngine>());
services.TryAddSingleton<IEngineControl>(sp => sp.GetRequiredService<OfflineEngine>());
services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{
services.TryAddSingleton(sp => new PasswordAccess(options.Password, options.Lockout, () => sp.GetRequiredService<IClock>().Now));
}
services.ConfigureHttpJsonOptions(json =>
{
json.SerializerOptions.TypeInfoResolverChain.Clear();
json.SerializerOptions.TypeInfoResolverChain.Add(FebeJsonContext.Default);
});
return services;
}
/// <summary>Middleware (security, errors, static files) and every endpoint.</summary>
public static WebApplication UseFebe(this WebApplication app)
{
ArgumentNullException.ThrowIfNull(app);
var options = app.Services.GetRequiredService<FebeWebOptions>();
var files = options.InterfaceFolder is { Length: > 0 } folder ? new EmbeddedWwwroot(folder) : new EmbeddedWwwroot();
app.UseMiddleware<SecurityMiddleware>();
if (options.Demo)
{
app.UseMiddleware<DemoRequestMiddleware>();
}
app.UseMiddleware<ApiErrorMiddleware>();
var types = new FileExtensionContentTypeProvider();
types.Mappings[".json"] = "application/json; charset=utf-8";
types.Mappings[".js"] = "text/javascript; charset=utf-8";
types.Mappings[".css"] = "text/css; charset=utf-8";
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = files,
ContentTypeProvider = types,
OnPrepareResponse = ctx => ctx.Context.Response.Headers.CacheControl = "no-cache",
});
app.MapFebeApi(files);
return app;
}
/// <summary>The endpoints alone (API, events, icons, application page).</summary>
public static IEndpointRouteBuilder MapFebeApi(this IEndpointRouteBuilder endpoints, EmbeddedWwwroot files)
{
ArgumentNullException.ThrowIfNull(endpoints);
ArgumentNullException.ThrowIfNull(files);
SystemApi.Map(endpoints, files);
EngineApi.Map(endpoints);
LibraryApi.Map(endpoints);
AccountsApi.Map(endpoints);
AccessApi.Map(endpoints);
endpoints.Map("/api/{**rest}", static context =>
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return context.Response.WriteAsJsonAsync(new ProblemDto("Indirizzo dell'API sconosciuto."), FebeJsonContext.Default.ProblemDto);
});
// Every page address without an extension answers with the application page; the router of the page
// decides what to show (and says «Pagina non trovata» for unknown addresses).
var embeddedIndex = files.ReadText("index.html") ?? throw new InvalidOperationException("index.html non è incorporato.");
endpoints.MapFallback("{*path:nonfile}", context =>
{
if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
{
context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
return Task.CompletedTask;
}
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.Headers.CacheControl = "no-cache";
return context.Response.WriteAsync(files.FromDisk ? files.ReadText("index.html") ?? embeddedIndex : embeddedIndex);
});
return endpoints;
}
}
/// <summary>Builds and starts the web application for either shell.</summary>
public static class FebeWebHost
{
/// <summary>
/// A web application listening on <paramref name="listen"/> (Kestrel only, no other server), with the web layer
/// registered and mapped. ASP.NET Core request logs are kept at warnings: the desktop token travels once in a
/// query string and must never reach a log.
/// </summary>
public static WebApplication Build(FebeWebOptions options, FebeListen listen, Action<IServiceCollection> configureServices, Action<ILoggingBuilder>? configureLogging = null)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(listen);
ArgumentNullException.ThrowIfNull(configureServices);
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions
{
ApplicationName = typeof(FebeWeb).Assembly.GetName().Name,
ContentRootPath = AppContext.BaseDirectory,
});
builder.WebHost.ConfigureKestrel(kestrel =>
{
kestrel.AddServerHeader = false;
kestrel.Listen(listen.Address, listen.Port);
});
builder.Logging.ClearProviders();
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.Hosting", LogLevel.Warning);
if (configureLogging is not null)
{
configureLogging(builder.Logging);
}
configureServices(builder.Services);
builder.Services.AddFebeWeb(options);
var app = builder.Build();
app.UseFebe();
return app;
}
/// <summary>The address Kestrel actually listens on (after <c>StartAsync</c>; useful with port 0).</summary>
public static Uri BoundAddress(WebApplication app)
{
ArgumentNullException.ThrowIfNull(app);
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()?.Addresses
?? throw new InvalidOperationException("Il server non ha indirizzi.");
var first = addresses.First();
return new Uri(first.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal));
}
/// <summary>The port Kestrel listens on.</summary>
public static int BoundPort(WebApplication app) => BoundAddress(app).Port;
/// <summary>True for an address that only this computer can reach.</summary>
public static bool IsLoopback(IPAddress address) => IPAddress.IsLoopback(address);
}
+101
View File
@@ -0,0 +1,101 @@
using System.Net;
using System.Reflection;
namespace Febe.Web;
/// <summary>Which of the two shells serves the interface (spec §1, §5). The interface adapts to it (capabilities).</summary>
public enum FebeEdition
{
/// <summary>Container on the home server: folders read-only in the interface, «Scarica» instead of «Mostra nella cartella».</summary>
Docker,
/// <summary>Windows application: native folder picker, «Mostra nella cartella», «Avvio» block, browser in its own window.</summary>
Desktop,
}
/// <summary>How requests are admitted (spec §13.1).</summary>
public enum AccessMode
{
/// <summary>No authentication: only for the demo, which listens on 127.0.0.1 and holds no real data.</summary>
None,
/// <summary>Docker: password, HttpOnly SameSite=Strict session cookie, lockout after repeated failures.</summary>
Password,
/// <summary>Windows: a token generated at every start, known to the window, plus Host and Origin checks.</summary>
Token,
}
/// <summary>Repeated wrong passwords lock the login for a while (spec §13.1 «blocco dopo tentativi ripetuti»).</summary>
public sealed record LockoutOptions
{
/// <summary>Wrong attempts from one client within <see cref="Window"/> that lock that client.</summary>
public int AttemptsPerClient { get; init; } = 5;
/// <summary>Wrong attempts from all clients within <see cref="Window"/> that lock every new login.</summary>
public int AttemptsOverall { get; init; } = 20;
public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(15);
public TimeSpan LockFor { get; init; } = TimeSpan.FromMinutes(15);
/// <summary>A session lasts this long after the login.</summary>
public TimeSpan SessionLifetime { get; init; } = TimeSpan.FromDays(30);
}
/// <summary>Configuration of the web layer. Services (storage, library, engine...) are registered separately.</summary>
public sealed record FebeWebOptions
{
public FebeEdition Edition { get; init; } = FebeEdition.Docker;
public AccessMode Access { get; init; } = AccessMode.Password;
/// <summary>Docker: the interface password (FEBE_PASSWORD). Never logged.</summary>
public string? Password { get; init; }
/// <summary>Windows: the token of this start (see <see cref="Security.AccessToken.Create"/>). Never logged.</summary>
public string? AccessToken { get; init; }
/// <summary>
/// Values accepted in the Host header (host, or host:port), case-insensitive. Empty means any host: right for Docker,
/// reached by the server's name or address on the home network; the password and the Origin check protect it.
/// The desktop and the demo pass the loopback names with their port (DNS rebinding cannot reach them).
/// </summary>
public IReadOnlyList<string> AllowedHosts { get; init; } = [];
/// <summary>Trust X-Forwarded-Host for the Origin check (behind a reverse proxy with HTTPS). Off by default.</summary>
public bool TrustForwardedHost { get; init; }
public LockoutOptions Lockout { get; init; } = new();
/// <summary>
/// Development only: serve the interface from this folder (src/Febe.Web/wwwroot) instead of the copy embedded in
/// the assembly, so that pages can be edited and reloaded without rebuilding. Null in every real start.
/// </summary>
public string? InterfaceFolder { get; init; }
/// <summary>Demo mode (spec §10.6): fake engine, temporary library, scenes chosen by address.</summary>
public bool Demo { get; init; }
/// <summary>Program version shown in the interface.</summary>
public string Version { get; init; } = typeof(FebeWebOptions).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion?.Split('+')[0] ?? "0.0.0";
/// <summary>Loopback host names with a port, for <see cref="AllowedHosts"/>; port 0 accepts any port (<c>host:*</c>).</summary>
public static IReadOnlyList<string> LoopbackHosts(int port)
{
var p = port == 0 ? "*" : port.ToString(System.Globalization.CultureInfo.InvariantCulture);
return [$"127.0.0.1:{p}", $"localhost:{p}", $"[::1]:{p}"];
}
}
/// <summary>Where Kestrel listens.</summary>
/// <param name="Address">IP address (127.0.0.1 for the desktop and the demo; any address in Docker).</param>
/// <param name="Port">Port; 0 picks a free one (tests, desktop).</param>
public sealed record FebeListen(IPAddress Address, int Port)
{
public const int DefaultPort = 8480;
public static FebeListen Loopback(int port = DefaultPort) => new(IPAddress.Loopback, port);
public static FebeListen Any(int port = DefaultPort) => new(IPAddress.Any, port);
}
+278
View File
@@ -0,0 +1,278 @@
using System.Collections;
using System.Reflection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
namespace Febe.Web.Hosting;
/// <summary>
/// The interface files (<c>wwwroot</c>) embedded in the Febe.Web assembly, as an <see cref="IFileProvider"/> for the
/// static file middleware. Resources are named <c>wwwroot/&lt;relative path&gt;</c> (see Febe.Web.csproj): one
/// executable carries the whole interface, also on Windows. Paths are case-sensitive, '/' separated; anything that
/// tries to leave the root (<c>..</c>, rooted paths, backslashes) is simply not found.
/// </summary>
public sealed class EmbeddedWwwroot : IFileProvider
{
/// <summary>Prefix of the manifest resource names.</summary>
public const string Prefix = "wwwroot/";
private readonly Assembly _assembly;
private readonly string? _folder;
private readonly Dictionary<string, string> _files = new(StringComparer.Ordinal);
private readonly HashSet<string> _directories = new(StringComparer.Ordinal) { string.Empty };
private readonly DateTimeOffset _lastModified;
public EmbeddedWwwroot()
: this(typeof(EmbeddedWwwroot).Assembly)
{
}
public EmbeddedWwwroot(Assembly assembly)
{
_assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
foreach (var name in assembly.GetManifestResourceNames())
{
if (!name.StartsWith(Prefix, StringComparison.Ordinal))
{
continue;
}
// MSBuild keeps the platform separator of %(RecursiveDir): normalize to '/'.
var relative = name[Prefix.Length..].Replace('\\', '/');
_files[relative] = name;
var slash = relative.LastIndexOf('/');
while (slash > 0)
{
_directories.Add(relative[..slash]);
slash = relative.LastIndexOf('/', slash - 1);
}
}
// Embedded files change only with the assembly: its time is a good Last-Modified (and ETag) for all of them.
var location = assembly.Location;
_lastModified = !string.IsNullOrEmpty(location) && File.Exists(location)
? new DateTimeOffset(File.GetLastWriteTimeUtc(location), TimeSpan.Zero)
: DateTimeOffset.UtcNow;
}
/// <summary>
/// Development only: serves the interface from a folder on disk (the wwwroot of the sources), so that a change to
/// a page shows at the next reload without rebuilding. Set by <see cref="FebeWebOptions.InterfaceFolder"/>.
/// </summary>
public EmbeddedWwwroot(string folder)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
_assembly = typeof(EmbeddedWwwroot).Assembly;
_folder = Path.GetFullPath(folder);
foreach (var file in Directory.EnumerateFiles(_folder, "*", SearchOption.AllDirectories))
{
var relative = Path.GetRelativePath(_folder, file).Replace('\\', '/');
_files[relative] = file;
var slash = relative.LastIndexOf('/');
while (slash > 0)
{
_directories.Add(relative[..slash]);
slash = relative.LastIndexOf('/', slash - 1);
}
}
_lastModified = DateTimeOffset.UtcNow;
}
/// <summary>True when files come from a folder on disk instead of the assembly.</summary>
public bool FromDisk => _folder is not null;
/// <summary>Relative paths of every embedded file ('/' separated).</summary>
public IReadOnlyCollection<string> Files => _files.Keys;
public IFileInfo GetFileInfo(string subpath)
{
var path = Normalize(subpath);
if (path is null)
{
return new NotFoundFileInfo(subpath ?? string.Empty);
}
if (_folder is not null)
{
var full = Path.Combine(_folder, path.Replace('/', Path.DirectorySeparatorChar));
return File.Exists(full) ? new PhysicalFile(full) : new NotFoundFileInfo(subpath ?? string.Empty);
}
if (!_files.TryGetValue(path, out var resource))
{
return new NotFoundFileInfo(subpath ?? string.Empty);
}
return new EmbeddedFile(_assembly, resource, path[(path.LastIndexOf('/') + 1)..], _lastModified);
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
var path = Normalize(subpath);
if (path is null || !_directories.Contains(path))
{
return NotFoundDirectoryContents.Singleton;
}
var prefix = path.Length == 0 ? string.Empty : path + "/";
var entries = new List<IFileInfo>();
foreach (var (relative, resource) in _files)
{
if (relative.StartsWith(prefix, StringComparison.Ordinal) && relative.IndexOf('/', prefix.Length) < 0)
{
entries.Add(_folder is null ? new EmbeddedFile(_assembly, resource, relative[prefix.Length..], _lastModified) : new PhysicalFile(resource));
}
}
foreach (var directory in _directories)
{
if (directory.Length > prefix.Length && directory.StartsWith(prefix, StringComparison.Ordinal) && directory.IndexOf('/', prefix.Length) < 0)
{
entries.Add(new EmbeddedDirectory(directory[prefix.Length..], _lastModified));
}
}
return new Contents(entries.OrderBy(e => e.Name, StringComparer.Ordinal).ToList());
}
/// <summary>Embedded files never change while the program runs.</summary>
public IChangeToken Watch(string filter) => NullChangeToken.Singleton;
/// <summary>Opens an embedded file, or returns null.</summary>
public Stream? Open(string subpath)
{
var path = Normalize(subpath);
if (path is null)
{
return null;
}
if (_folder is not null)
{
var full = Path.Combine(_folder, path.Replace('/', Path.DirectorySeparatorChar));
return File.Exists(full) ? File.OpenRead(full) : null;
}
return _files.TryGetValue(path, out var resource) ? _assembly.GetManifestResourceStream(resource) : null;
}
/// <summary>Reads an embedded text file (UTF-8), or returns null.</summary>
public string? ReadText(string subpath)
{
using var stream = Open(subpath);
if (stream is null)
{
return null;
}
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
private static string? Normalize(string? subpath)
{
if (subpath is null)
{
return null;
}
var path = subpath.TrimStart('/');
if (path.EndsWith('/'))
{
path = path.TrimEnd('/');
}
if (path.Contains('\\', StringComparison.Ordinal) || path.Contains(':', StringComparison.Ordinal) || path.Contains('\0', StringComparison.Ordinal))
{
return null;
}
foreach (var segment in path.Split('/'))
{
if (segment is "." or ".." || (segment.Length == 0 && path.Length > 0))
{
return null;
}
}
return path;
}
private sealed class PhysicalFile(string path) : IFileInfo
{
private readonly FileInfo _info = new(path);
public bool Exists => _info.Exists;
public long Length => _info.Length;
public string? PhysicalPath => _info.FullName;
public string Name => _info.Name;
public DateTimeOffset LastModified => _info.LastWriteTimeUtc;
public bool IsDirectory => false;
public Stream CreateReadStream() => File.OpenRead(_info.FullName);
}
private sealed class EmbeddedFile(Assembly assembly, string resource, string name, DateTimeOffset lastModified) : IFileInfo
{
private long? _length;
public bool Exists => true;
public long Length
{
get
{
if (_length is null)
{
using var stream = assembly.GetManifestResourceStream(resource);
_length = stream?.Length ?? 0;
}
return _length.Value;
}
}
public string? PhysicalPath => null;
public string Name => name;
public DateTimeOffset LastModified => lastModified;
public bool IsDirectory => false;
public Stream CreateReadStream() =>
assembly.GetManifestResourceStream(resource) ?? throw new FileNotFoundException("Risorsa incorporata mancante.", name);
}
private sealed class EmbeddedDirectory(string name, DateTimeOffset lastModified) : IFileInfo
{
public bool Exists => true;
public long Length => -1;
public string? PhysicalPath => null;
public string Name => name;
public DateTimeOffset LastModified => lastModified;
public bool IsDirectory => true;
public Stream CreateReadStream() => throw new InvalidOperationException("Una cartella non si legge come file.");
}
private sealed class Contents(IReadOnlyList<IFileInfo> entries) : IDirectoryContents
{
public bool Exists => true;
public IEnumerator<IFileInfo> GetEnumerator() => entries.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
+166
View File
@@ -0,0 +1,166 @@
# Febe.Web
L'applicazione web di Febe, la stessa per le due vesti (§5): API sotto `/api`, eventi a `/api/eventi`, l'interfaccia
in `wwwroot/` incorporata nell'assembly e servita senza pacchetti in più, le pagine agli indirizzi italiani.
Qui sotto le convenzioni per chi continua il lavoro (parte 2 dell'interfaccia, composizione di Server e Desktop).
## Struttura
| Cartella | Cosa c'è |
|---|---|
| `FebeWeb.cs` | `AddFebeWeb`, `UseFebe`, `MapFebeApi`, `FebeWebHost.Build` / `BoundAddress` |
| `FebeWebOptions.cs` | Opzioni: veste, accesso, password, gettone, nomi ammessi, blocco, cartella dell'interfaccia, dimostrazione |
| `Hosting/` | `EmbeddedWwwroot`: `IFileProvider` sulle risorse incorporate `wwwroot/…` (o su una cartella, per sviluppo) |
| `Security/` | Controlli di §13.1: Host, Origin, gettone del desktop, password e blocco della veste Docker, intestazioni |
| `Api/` | Endpoint minimi, DTO (`Dtos.cs`), contesto JSON generato (`FebeJsonContext`), conversioni (`ApiMapping`) |
| `Engine/` | `IEngineControl` (comandi al motore), `EngineHostControl`, `OfflineEngine` (nessun motore), `BrowserUseTracker` |
| `Library/` | `FebeLibrary` (archivio + disposizione), `LibraryChanges`, esportazione CSV, collegamenti a Instagram, nomi utente |
| `Native/` | `INativeShell` (funzioni del sistema) e `IBrowserWindow` (finestra del browser), con le versioni «niente» |
| `Demo/` | Modalità dimostrativa: dati finti coerenti, motore finto con scene, guscio finto |
| `wwwroot/` | Interfaccia: HTML, CSS, moduli ES senza framework né build |
## Ospitare l'interfaccia (Server e Desktop)
```csharp
var app = FebeWebHost.Build(options, FebeListen.Any(8480) /* Docker */ or FebeListen.Loopback(0) /* Windows */, services =>
{
services.AddSingleton<IFebeStorage>(database);
services.AddSingleton(new FebeLibrary(database, dataLayout, libraryLayout, clock));
services.AddSingleton<IClock>(clock);
services.AddSingleton<IEngineMonitor>(engineHost.Monitor); // facoltativo
services.AddSingleton<IEngineControl>(new EngineHostControl(engineHost)); // facoltativo
services.AddSingleton<INativeShell>(shell); // solo desktop
services.AddSingleton<IBrowserWindow>(window); // solo desktop
});
app.Services.GetRequiredService<LibraryChanges>().Attach(downloadQueue, clock); // «libreria» negli eventi
await app.StartAsync();
var address = FebeWebHost.BoundAddress(app);
```
- Obbligatori: `IFebeStorage`, `FebeLibrary`, `IClock`. Il resto ha un'implementazione di ripiego registrata con
`TryAdd`: basta registrare la propria **prima** di `AddFebeWeb` (in `Build` succede da sé).
- `OfflineEngine` risponde «Motore spento» quando non c'è un motore. `EngineHostControl` traduce i comandi per
`EngineHost` (pausa, riprendi, controlla ora, leggi i seguiti, account cambiati).
- `BrowserUseTracker`: il desktop chiama `MarkUsed()` (o la pagina chiama `POST /api/browser/used`) quando Alberto usa
davvero il browser; «Riprendi» dopo una verifica si accende solo dopo quel momento.
- `LibraryChanges.Publish(new LibraryChange(at, accountId, reason))` per altre modifiche (importazione, eliminazioni:
queste ultime le pubblica già l'API).
- `IMediaFileResolver` trova il file su disco di un media (di serie: disposizione della libreria e cartelle per account).
### Opzioni e sicurezza (§13.1)
| Veste | Opzioni | Effetto |
|---|---|---|
| Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde 503 e non si apre |
| Windows | `Edition = Desktop`, `Access = Token`, `AccessToken = AccessToken.Create()`, `AllowedHosts = FebeWebOptions.LoopbackHosts(porta)`, `FebeListen.Loopback(0)` | La finestra apre `/?gettone=…` una volta: il gettone diventa un cookie HttpOnly Strict e sparisce dall'indirizzo. Anche l'intestazione `X-Febe-Gettone` vale |
| Prove e dimostrazione | `Access = None` | Solo su 127.0.0.1 |
Sempre attivi: nome Host in elenco (altrimenti 400), Origin uguale all'Host per ogni comando, per `/api/eventi` e
`/api/vista` (altrimenti 403; `Sec-Fetch-Site` cross-site rifiutato), CSP senza script esterni, `nosniff`,
`X-Frame-Options: DENY`, niente `Referer`. I registri di ASP.NET Core sono fermi agli avvisi: il gettone passa una
volta nell'indirizzo e non deve finire in un registro. Gli errori 500 registrano solo tipo e messaggio.
## API
JSON con nomi inglesi in camelCase (`FebeJsonContext`, generato: ogni DTO nuovo va aggiunto con
`[JsonSerializable]`, altrimenti la serializzazione fallisce). Gli enum del motore (`EngineSnapshot`) viaggiano come
nomi C# (`"InSession"`); i nostri come stringhe camelCase (`"upToDate"`). Gli errori sono `{ "message": "…" }` in
italiano, con 400/404/409. Gli orari sono millisecondi Unix; dove la pagina deve mostrare giorni e ore locali ci
sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| Endpoint | Uso |
|---|---|
| `GET /api/capabilities` | Veste, accesso, cosa sa fare il guscio (`showInFolder`, `pickFolder`, `foldersReadOnly`, `autostart`, `browserWindow`), versione, ora e giorno del server |
| `GET/PUT /api/preferences` | Tema (`chiaro`, `scuro`, `sistema`) |
| `GET /api/engine`, `POST /api/engine/pause`, `/resume` | Istantanea del motore, collegamento, `canResume` |
| `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` | Totali e giorni con conteggio e cursore (per la finestra del mosaico) |
| `GET /api/library?cursor=&direction=older\|newer&limit=` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q` |
| `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 |
| `GET /api/accounts`, `GET /api/accounts/{id}`, `GET /{id}/history` | Elenco con conteggi, scheda, cronologia |
| `POST /api/accounts/{id}/plan`, `PUT /{id}/settings`, `POST /{id}/keep-updated`, `/pause`, `/resume`, `/check-now`, `/remove`, `/pick-folder`, `/open-on-instagram` | Impostazioni dell'account e comandi |
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account» |
| `GET /accesso`, `POST /api/accesso`, `POST /api/uscita` | Accesso con password |
| `GET /icone/tutte.svg` | Tutte le icone Lucide di `wwwroot/icone` in un solo sprite (`<symbol id="i-nome">`) |
Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON.
## Interfaccia (`wwwroot/`)
Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da disco:
`FEBE_INTERFACCIA=$PWD/src/Febe.Web/wwwroot dotnet run --project src/Febe.Server -- --demo`, e basta ricaricare.
### Una pagina nuova
1. Una riga in `js/routes.js`: `{ pattern: /^\/attivita\/?$/, nav: 'attivita', page: () => import('./pages/activity.js') }`
(i gruppi con nome del `pattern` arrivano in `route.params`; `data` aggiunge valori fissi).
2. Il modulo esporta `export default { async mount(page, route) { … } }`. `route` ha `path`, `params`, `query`
(`URLSearchParams`). Se `mount` restituisce una funzione, viene chiamata quando si lascia la pagina.
3. `page` (`PageFrame` in `js/core/shell.js`) dà la cornice di §10.2:
- `page.title(testo, conteggio)`, `page.count(testo)`, `page.actions(...nodi)`: riga del titolo;
- `page.header(nodo, titoloDocumento)`: intestazione su misura (scheda account); `page.back(testo, indirizzo)`;
- `page.tabs(nodo)`, `page.tools(nodo)`: linguette e riga degli strumenti; `page.body`: contenuto che scorre;
- `page.saveBar(nodo)`: barra fissa in basso (`null` la toglie); `page.guard(async () => bool)` prima di uscire;
- `page.signal`: da passare a `api()` (le richieste si annullano uscendo); `page.onEngine(fn)`, `page.onLibrary(fn)`,
`page.onLeave(fn)`.
La striscia rossa di arresto (mockup 11) la mette la cornice su ogni pagina, da sola.
4. Pagine ancora da fare (segnaposto in `pages/placeholder.js`): `/attivita`, `/importa` (deve leggere
`route.query.get('passo')`, la dimostrazione apre `/importa?passo=3`), `/impostazioni/{generali|limiti|collegamento|notifiche|dati|informazioni}`,
`/browser` (vista remota della veste Docker).
### Moduli comuni (`js/core/`)
- `dom.js`: `h('tag.classe#id', attributi, ...figli)` (attributi `on…`, `style` oggetto, `dataset`), `fill`, `icon('nome', 's'|'l')`.
- `ui.js`: `toast`, `showError`, `dialog`, `confirmDialog`, `menu`, `toggle`, `checkbox`, `radio`, `segmented`, `avatar`, `label`.
- `text.js`: `t('chiave.sotto', { n, … })` (forme `singolare|plurale` scelte da `n`), `number` (punti delle migliaia),
`decimal`, `bytes`, `duration`, `around` («verso le 15:30»), `ago` («2 ore fa»), `dayName`.
- `api.js`: `api(percorso, { method, body, signal, raw })` (lancia `ApiError` con il messaggio italiano del server),
`download`, `withCarried`. I parametri `scena`, `veste`, `tema` della dimostrazione restano negli indirizzi interni e
viaggiano verso l'API (intestazioni `X-Febe-Scena`, `X-Febe-Veste`).
- `engine.js`: `onEngine`, `onLibrary`, `refreshEngine`. In dimostrazione niente SSE: si chiede il motore ogni 30 s
(così le schermate senza finestra finiscono).
- `context.js`: `caps()` (da `/api/capabilities`), `serverNow()`, `isDesktop()`.
- `theme.js`: tema chiaro, scuro o di sistema su `html[data-tema]`; `js/tema.js` lo applica prima del disegno.
Pezzi riusabili delle pagine: `pages/mosaic.js` (`Mosaic`: righe giustificate o griglia 9:16, finestre per giorno,
virtualizzazione, selezione, nuovi elementi in cima senza spostare la vista), `pages/viewer.js` (`openViewer`),
`pages/accounts.js` (`checkNow`, `removeAccount`, `accountMenu`, `stateLine`), `pages/library.js` (`confirmDelete`).
### Testi, stile, accessibilità
- Ogni testo visibile sta in `testi/it.json` (chiavi senza punti nei nomi: il punto separa i livelli). I testi del
motore (istantanea, piano dell'account) arrivano già in italiano dal server (`ItalianText`): non si duplicano.
- Maiuscola solo all'inizio, «verso le», punti per le migliaia e virgola per i decimali; i pulsanti dicono cosa
succede («Aggiungi 3 account», «Elimina dalla libreria»).
- Classi e token dell'appendice B in `css/febe.css`; le aggiunte stanno nel blocco «estensioni» prima delle regole per
finestra stretta (≤1000 px: barra a icone; ≤560 px: una colonna e navigazione in basso). Colori solo dai token, mai
informazione affidata al solo colore, focus sempre visibile, animazioni solo su gesto e spente con
`prefers-reduced-motion`.
- Icone: file Lucide in `icone/`, usati con `icon('nome')` (lo sprite si costruisce da sé).
## Dimostrazione
`dotnet run --project src/Febe.Server -- --demo [--porta 8480] [--fuso Europe/Rome]`: 127.0.0.1, senza password,
cartella temporanea con dati e libreria finti (38 account, circa 18.000 elementi), cancellata alla chiusura. Non
scrive mai nella libreria vera e non usa la rete.
- Scene del motore: `?scena=normale|sessione|fermo|scollegato`; tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|docker`.
- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/account/2?tipo=storie`, `/importa?passo=3` (da fare).
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
conti tornino.
## Schermate (§10.7)
`bash tools/schermate/tutte.sh 8490` rifà le schermate di `docs/schermate/` da una dimostrazione avviata su quella
porta; `node tools/schermate/schermata.mjs <indirizzo> <file.png> [larghezza] [altezza] [attesa] [passo.js]` ne fa
una (scala 1,25, passi in `tools/schermate/passi/`). Accetta solo indirizzi di questo computer. Le differenze
rimaste dai mockup sono in `docs/schermate/differenze.md`.
## Prove
`tests/Febe.Tests/Web/` avvia Kestrel vero su una porta libera di 127.0.0.1 (`Support/WebTestServer.cs`), con
archivio e libreria temporanei e orologio manuale; `DemoTests` avvia una dimostrazione intera una volta per classe.
`dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Web"`.
+122
View File
@@ -0,0 +1,122 @@
using System.Globalization;
using System.Text;
using Febe.Core.Domain;
namespace Febe.Web.Library;
/// <summary>One line of the exported list: an entry with its account and files.</summary>
public sealed record CsvEntry(Account Account, Entry Entry, IReadOnlyList<Media> Media, IReadOnlyList<string> Highlights, string? Address);
/// <summary>
/// «Esporta l'elenco» (spec §4.8): CSV with <c>;</c> as separator and UTF-8 with BOM, so that it opens well in Excel
/// with Italian settings. Fields with a separator, quotes, line breaks or edge spaces are quoted with doubled quotes;
/// fields that Excel would read as a formula (starting with = + - @ or a tab) get a leading apostrophe.
/// Dates and times are local (Alberto's zone), as in the file names.
/// </summary>
public static class CsvExport
{
public const char Separator = ';';
public static readonly IReadOnlyList<string> Header =
[
"Account", "Tipo", "Data", "Ora", "Codice", "Identificativo", "Didascalia", "Autore", "Raccolte",
"Provenienza", "Stato", "File", "Nomi dei file", "Indirizzo",
];
/// <summary>Writes the BOM, the header and one line per entry.</summary>
public static async Task WriteAsync(Stream output, IAsyncEnumerable<CsvEntry> entries, TimeZoneInfo zone, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(entries);
ArgumentNullException.ThrowIfNull(zone);
var writer = new StreamWriter(output, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), 16 * 1024, leaveOpen: true) { NewLine = "\r\n" };
await using (writer.ConfigureAwait(false))
{
await writer.WriteLineAsync(Line(Header)).ConfigureAwait(false);
await foreach (var entry in entries.WithCancellation(ct).ConfigureAwait(false))
{
await writer.WriteLineAsync(Line(Fields(entry, zone))).ConfigureAwait(false);
}
await writer.FlushAsync(ct).ConfigureAwait(false);
}
}
/// <summary>The fields of one entry, in the order of <see cref="Header"/>.</summary>
public static IReadOnlyList<string?> Fields(CsvEntry row, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(row);
var local = LocalCalendar.ToLocal(row.Entry.PublishedAt, zone);
var present = row.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList();
return
[
row.Account.Username,
KindName(row.Entry.Kind),
local.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
local.ToString("HH:mm:ss", CultureInfo.InvariantCulture),
row.Entry.Code,
row.Entry.InstagramId,
row.Entry.Caption,
row.Entry.AuthorUsername,
string.Join(", ", row.Highlights),
row.Entry.Provenance == Provenance.Imported ? "Importato" : "Scaricato da Instagram",
StateName(row.Entry.State),
row.Media.Count.ToString(CultureInfo.InvariantCulture),
string.Join(" | ", present.Select(m => m.RelativePath)),
row.Address,
];
}
/// <summary>One CSV line (without the line break).</summary>
public static string Line(IEnumerable<string?> fields)
{
ArgumentNullException.ThrowIfNull(fields);
return string.Join(Separator, fields.Select(Field));
}
/// <summary>Escapes one field.</summary>
public static string Field(string? value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
var text = value;
if (text[0] is '=' or '+' or '-' or '@' or '\t' or '\r')
{
text = "'" + text;
}
var quote = text.Contains(Separator, StringComparison.Ordinal)
|| text.Contains('"', StringComparison.Ordinal)
|| text.Contains('\n', StringComparison.Ordinal)
|| text.Contains('\r', StringComparison.Ordinal)
|| text[0] == ' '
|| text[^1] == ' '
|| text[0] == '\'';
return quote ? "\"" + text.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : text;
}
public static string KindName(EntryKind kind) => kind switch
{
EntryKind.Post => "Post",
EntryKind.Story => "Storia",
EntryKind.Highlight => "In evidenza",
EntryKind.Tagged => "Taggato",
EntryKind.ProfilePicture => "Foto del profilo",
_ => kind.ToString(),
};
public static string StateName(EntryState state) => state switch
{
EntryState.ToDownload => "Da scaricare",
EntryState.Downloaded => "Scaricato",
EntryState.Partial => "Parziale",
EntryState.Failed => "Fallito",
EntryState.Skipped => "Saltato",
EntryState.Imported => "Importato",
EntryState.Deleted => "Eliminato",
_ => state.ToString(),
};
}
+157
View File
@@ -0,0 +1,157 @@
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Downloads;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Web.Library;
/// <summary>
/// The library as the web layer uses it: Data folder, library folder, thumbnails, journal and deletion. The library
/// folder can change at run time (Impostazioni, Generali): <see cref="UseLibraryRoot"/> swaps the layout.
/// </summary>
public sealed class FebeLibrary
{
private readonly IFebeStorage _storage;
private readonly IClock _clock;
private readonly PerceptualHashIndex? _index;
private volatile LibraryLayout _layout;
public FebeLibrary(IFebeStorage storage, DataFolderLayout data, LibraryLayout layout, IClock clock, PerceptualHashIndex? index = null)
{
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
Data = data ?? throw new ArgumentNullException(nameof(data));
_layout = layout ?? throw new ArgumentNullException(nameof(layout));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_index = index;
Thumbnails = new ThumbnailStore(data.Thumbnails);
Journal = new AccountJournal(clock);
}
public DataFolderLayout Data { get; }
public LibraryLayout Layout => _layout;
public ThumbnailStore Thumbnails { get; }
public AccountJournal Journal { get; }
/// <summary>«Elimina dalla libreria», on Alberto's explicit choice only (rule 12).</summary>
public LibraryDeletion Deletion => new(_storage, _layout, Journal, _clock, Thumbnails, _index);
/// <summary>The library folder changed: new files go there; existing accounts keep their stored folders.</summary>
public void UseLibraryRoot(string root) => _layout = new LibraryLayout(root, _layout.MaxPathLength);
}
/// <summary>Where the file of a media record is on disk. The demo maps its shared sample files; the real one uses the layout.</summary>
public interface IMediaFileResolver
{
/// <summary>Full path of an existing file, or null when the file is not on disk.</summary>
string? Resolve(Account account, Media media);
}
/// <summary>Files under the account folders of the library (spec §4.7).</summary>
public sealed class LibraryFileResolver(FebeLibrary library) : IMediaFileResolver
{
public string? Resolve(Account account, Media media)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(media);
if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State))
{
return null;
}
try
{
var path = library.Layout.FullPath(account, media.RelativePath);
return File.Exists(path) ? path : null;
}
catch (ArgumentException)
{
return null;
}
}
}
/// <summary>Something changed in the library: the open pages reload what they show.</summary>
/// <param name="At">When.</param>
/// <param name="AccountId">The account concerned, when there is only one.</param>
/// <param name="Reason">Short machine reason: "stored", "deleted", "account", "import".</param>
public sealed record LibraryChange(DateTimeOffset At, long? AccountId, string Reason);
/// <summary>
/// Library notifications for the server-sent events (<c>/api/eventi</c>, event <c>libreria</c>). Publishers: the web
/// layer itself (deletions, account changes), the download queue (<see cref="Attach"/>) and the import (M7).
/// Slow subscribers lose the oldest notifications.
/// </summary>
public sealed class LibraryChanges
{
private readonly Lock _gate = new();
private readonly List<Channel<LibraryChange>> _subscribers = [];
public void Publish(LibraryChange change)
{
Channel<LibraryChange>[] subscribers;
lock (_gate)
{
subscribers = [.. _subscribers];
}
foreach (var subscriber in subscribers)
{
subscriber.Writer.TryWrite(change);
}
}
/// <summary>Publishes a change for every file the download queue stores.</summary>
public IDisposable Attach(DownloadQueue queue, IClock clock)
{
ArgumentNullException.ThrowIfNull(queue);
ArgumentNullException.ThrowIfNull(clock);
void Handler(object? sender, DownloadProgress progress)
{
if (progress.Step == DownloadStep.Stored)
{
Publish(new LibraryChange(clock.Now, progress.AccountId, "stored"));
}
}
queue.Progress += Handler;
return new Detach(() => queue.Progress -= Handler);
}
public async IAsyncEnumerable<LibraryChange> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
var channel = Channel.CreateBounded<LibraryChange>(new BoundedChannelOptions(256) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
lock (_gate)
{
_subscribers.Add(channel);
}
try
{
while (await channel.Reader.WaitToReadAsync(ct).ConfigureAwait(false))
{
while (channel.Reader.TryRead(out var change))
{
yield return change;
}
}
}
finally
{
lock (_gate)
{
_subscribers.Remove(channel);
}
}
}
private sealed class Detach(Action action) : IDisposable
{
public void Dispose() => action();
}
}
+37
View File
@@ -0,0 +1,37 @@
using Febe.Core.Domain;
namespace Febe.Web.Library;
/// <summary>
/// Addresses for «Apri su Instagram»: they open in Alberto's own browser (a link, or the default browser on Windows),
/// never in Febe's and never from the server. They use the public forms anyone sees in the address bar; a story
/// older than a day opens the profile, because the story is no longer there.
/// </summary>
public static class InstagramLinks
{
public const string Site = "https://www.instagram.com/";
public static string Profile(string username) => Site + Uri.EscapeDataString(username.Trim().TrimStart('@')) + "/";
/// <summary>The page of an entry, or the profile when the entry has no page of its own any more.</summary>
public static string For(Account account, Entry entry, DateTimeOffset now, string? highlightInstagramId = null)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(entry);
switch (entry.Kind)
{
case EntryKind.Post or EntryKind.Tagged when !string.IsNullOrWhiteSpace(entry.Code):
return Site + "p/" + Uri.EscapeDataString(entry.Code) + "/";
case EntryKind.Story when !string.IsNullOrWhiteSpace(entry.InstagramId) && now - entry.PublishedAt < TimeSpan.FromHours(24):
return Site + "stories/" + Uri.EscapeDataString(account.Username) + "/" + Uri.EscapeDataString(entry.InstagramId) + "/";
case EntryKind.Highlight when !string.IsNullOrWhiteSpace(highlightInstagramId):
return Site + "stories/highlights/" + Uri.EscapeDataString(highlightInstagramId) + "/";
default:
return Profile(account.Username);
}
}
/// <summary>True for addresses of the site that the shell may open in the default browser.</summary>
public static bool IsSiteAddress(Uri address) =>
address is not null && address.Scheme == Uri.UriSchemeHttps && string.Equals(address.Host, "www.instagram.com", StringComparison.OrdinalIgnoreCase);
}
+117
View File
@@ -0,0 +1,117 @@
using System.Text.RegularExpressions;
namespace Febe.Web.Library;
/// <summary>A user name read from a line of the «Per nome utente» text area.</summary>
public sealed record ParsedUsername(int Line, string Username);
/// <summary>A line that is not a user name, with the reason in Italian.</summary>
public sealed record UsernameProblem(int Line, string Text, string Reason);
/// <summary>
/// «Per nome utente» (spec §4.2, mockup 04): one user name or profile address per line. Accepts «marta.demo»,
/// «@marta.demo», «instagram.com/marta.demo», «https://www.instagram.com/marta.demo/?hl=it». Refuses addresses of
/// posts, reels and other pages, and names Instagram would not accept. Names are compared and stored in lowercase.
/// </summary>
public static partial class UsernameParser
{
/// <summary>First path segments of the site that are pages, not profiles.</summary>
public static readonly IReadOnlySet<string> ReservedPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"p", "reel", "reels", "tv", "stories", "explore", "accounts", "direct", "about", "legal", "developer", "web", "challenge", "emails", "session",
};
public static (IReadOnlyList<ParsedUsername> Names, IReadOnlyList<UsernameProblem> Problems) Parse(string? text)
{
var names = new List<ParsedUsername>();
var problems = new List<UsernameProblem>();
var seen = new Dictionary<string, int>(StringComparer.Ordinal);
if (string.IsNullOrWhiteSpace(text))
{
return (names, problems);
}
var lines = text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n');
for (var i = 0; i < lines.Length; i++)
{
var number = i + 1;
var line = lines[i].Trim();
if (line.Length == 0)
{
continue;
}
if (line.Length > 300)
{
problems.Add(new UsernameProblem(number, line[..60] + "…", "Riga troppo lunga per essere un nome utente."));
continue;
}
var (candidate, reason) = Extract(line);
if (candidate is null)
{
problems.Add(new UsernameProblem(number, line, reason!));
continue;
}
if (seen.TryGetValue(candidate, out var first))
{
problems.Add(new UsernameProblem(number, line, $"Già scritto alla riga {first}."));
continue;
}
seen[candidate] = number;
names.Add(new ParsedUsername(number, candidate));
}
return (names, problems);
}
/// <summary>True for a valid user name (already lowercase, without @).</summary>
public static bool IsValid(string username) =>
Valid().IsMatch(username) && !username.StartsWith('.') && !username.EndsWith('.') && !username.Contains("..", StringComparison.Ordinal);
private static (string? Username, string? Reason) Extract(string line)
{
var text = line;
if (text.Contains("instagram.com", StringComparison.OrdinalIgnoreCase))
{
if (!text.Contains("://", StringComparison.Ordinal))
{
text = "https://" + text;
}
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri)
|| !(uri.Host.Equals("instagram.com", StringComparison.OrdinalIgnoreCase) || uri.Host.EndsWith(".instagram.com", StringComparison.OrdinalIgnoreCase)))
{
return (null, "Indirizzo non riconosciuto: serve quello del profilo, per esempio instagram.com/nome.utente.");
}
var segments = uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length == 0)
{
return (null, "L'indirizzo non contiene il nome del profilo.");
}
if (ReservedPaths.Contains(segments[0]))
{
return (null, "È l'indirizzo di un post o di un'altra pagina, non di un profilo.");
}
text = Uri.UnescapeDataString(segments[0]);
}
text = text.Trim().TrimStart('@').ToLowerInvariant();
if (text.Contains(' ', StringComparison.Ordinal))
{
return (null, "Un nome utente non contiene spazi: uno per riga.");
}
return IsValid(text)
? (text, null)
: (null, "Non è un nome utente valido: lettere, numeri, punti e trattini bassi, al massimo 30.");
}
[GeneratedRegex("^[a-z0-9._]{1,30}$", RegexOptions.CultureInvariant)]
private static partial Regex Valid();
}
+91
View File
@@ -0,0 +1,91 @@
namespace Febe.Web.Native;
/// <summary>
/// Native functions the shell offers to the interface (spec §12): folder picker, «Mostra nella cartella», opening an
/// address in Alberto's default browser, notifications, start with the system. The desktop implements it with
/// Windows APIs; in Docker and in a plain browser <see cref="BrowserShell"/> says that none is available and the
/// interface falls back (download instead of «Mostra nella cartella», links instead of native opening).
/// The web layer never passes paths or addresses that come from the page: it resolves them itself.
/// </summary>
public interface INativeShell
{
/// <summary>A folder picker exists («Cambia…» of the folders).</summary>
bool CanPickFolder { get; }
/// <summary>The file manager can show a file («Mostra nella cartella»).</summary>
bool CanShowInFolder { get; }
/// <summary>Addresses open in the default browser through the shell (otherwise the page opens them as links).</summary>
bool CanOpenUrl { get; }
/// <summary>System notifications are available (Windows).</summary>
bool CanNotify { get; }
/// <summary>«Avvia Febe all'accensione del computer» exists (Windows only).</summary>
bool SupportsAutostart { get; }
/// <summary>Asks Alberto for a folder; null when he cancels.</summary>
Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct);
/// <summary>Opens the file manager on a file. False when not possible.</summary>
Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct);
/// <summary>Opens an address in the default browser (Alberto's browser, never Febe's). False when not possible.</summary>
Task<bool> OpenUrlAsync(Uri address, CancellationToken ct);
/// <summary>Shows a system notification (spec §13.3).</summary>
Task NotifyAsync(string title, string message, CancellationToken ct);
Task<bool> GetAutostartAsync(CancellationToken ct);
Task SetAutostartAsync(bool enabled, CancellationToken ct);
}
/// <summary>No native functions: Docker and plain browsers.</summary>
public sealed class BrowserShell : INativeShell
{
public static BrowserShell Instance { get; } = new();
public bool CanPickFolder => false;
public bool CanShowInFolder => false;
public bool CanOpenUrl => false;
public bool CanNotify => false;
public bool SupportsAutostart => false;
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult<string?>(null);
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(false);
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false);
public Task NotifyAsync(string title, string message, CancellationToken ct) => Task.CompletedTask;
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(false);
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
}
/// <summary>
/// The browser of Febe as the interface sees it: on Windows a separate window brought to the front by «Apri il
/// browser»; in Docker the «Browser» page with the remote view. Implemented by the shells (M5, M6).
/// </summary>
public interface IBrowserWindow
{
/// <summary>True when the browser is a window of its own (Windows): «Apri il browser» calls <see cref="ShowAsync"/>.</summary>
bool IsSeparateWindow { get; }
/// <summary>Brings the browser window to the front (Windows). The engine stays still while Alberto uses it.</summary>
Task ShowAsync(CancellationToken ct);
}
/// <summary>No browser window (Docker uses the Browser page; the demo has no browser).</summary>
public sealed class NoBrowserWindow : IBrowserWindow
{
public bool IsSeparateWindow => false;
public Task ShowAsync(CancellationToken ct) => Task.CompletedTask;
}
+157
View File
@@ -0,0 +1,157 @@
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
namespace Febe.Web.Security;
/// <summary>Outcome of a login attempt.</summary>
public enum LoginStatus
{
Accepted,
WrongPassword,
/// <summary>Too many wrong attempts: no attempt is checked until <see cref="LoginResult.LockedUntil"/>.</summary>
Locked,
}
/// <summary>Result of <see cref="PasswordAccess.TryLogin"/>.</summary>
public sealed record LoginResult(LoginStatus Status, string? SessionId = null, DateTimeOffset? LockedUntil = null);
/// <summary>
/// Docker access (spec §13.1): one password (FEBE_PASSWORD), sessions in memory identified by a random value kept in an
/// HttpOnly SameSite=Strict cookie, and a lockout after repeated failures — per client and overall, so that guessing
/// from many addresses is slowed down too. A restart closes every session. Nothing here is ever logged.
/// </summary>
public sealed class PasswordAccess
{
/// <summary>Session cookie name.</summary>
public const string CookieName = "febe_sessione";
private readonly byte[] _passwordHash;
private readonly LockoutOptions _options;
private readonly Func<DateTimeOffset> _now;
private readonly ConcurrentDictionary<string, DateTimeOffset> _sessions = new(StringComparer.Ordinal);
private readonly Lock _gate = new();
private readonly Dictionary<string, List<DateTimeOffset>> _failures = new(StringComparer.Ordinal);
private readonly List<DateTimeOffset> _allFailures = [];
private readonly Dictionary<string, DateTimeOffset> _lockedClients = new(StringComparer.Ordinal);
private DateTimeOffset _lockedAll = DateTimeOffset.MinValue;
public PasswordAccess(string password, LockoutOptions? options = null, Func<DateTimeOffset>? now = null)
{
ArgumentException.ThrowIfNullOrEmpty(password);
_passwordHash = Hash(password);
_options = options ?? new LockoutOptions();
_now = now ?? (() => DateTimeOffset.UtcNow);
}
public TimeSpan SessionLifetime => _options.SessionLifetime;
/// <summary>Checks a password from a client (its address, or another stable key).</summary>
public LoginResult TryLogin(string? password, string client)
{
ArgumentNullException.ThrowIfNull(client);
var now = _now();
lock (_gate)
{
var locked = LockedUntilLocked(client, now);
if (locked is not null)
{
return new LoginResult(LoginStatus.Locked, LockedUntil: locked);
}
}
var accepted = password is not null && CryptographicOperations.FixedTimeEquals(Hash(password), _passwordHash);
if (accepted)
{
var id = AccessToken.Base64Url(RandomNumberGenerator.GetBytes(32));
_sessions[id] = now + _options.SessionLifetime;
lock (_gate)
{
_failures.Remove(client);
}
return new LoginResult(LoginStatus.Accepted, id);
}
lock (_gate)
{
var since = now - _options.Window;
if (!_failures.TryGetValue(client, out var list))
{
list = [];
_failures[client] = list;
}
list.RemoveAll(t => t < since);
list.Add(now);
_allFailures.RemoveAll(t => t < since);
_allFailures.Add(now);
if (list.Count >= _options.AttemptsPerClient)
{
_lockedClients[client] = now + _options.LockFor;
list.Clear();
}
if (_allFailures.Count >= _options.AttemptsOverall)
{
_lockedAll = now + _options.LockFor;
_allFailures.Clear();
}
var locked = LockedUntilLocked(client, now);
return locked is null ? new LoginResult(LoginStatus.WrongPassword) : new LoginResult(LoginStatus.Locked, LockedUntil: locked);
}
}
/// <summary>True when the session exists and has not expired.</summary>
public bool IsValid(string? sessionId)
{
if (string.IsNullOrEmpty(sessionId) || !_sessions.TryGetValue(sessionId, out var expires))
{
return false;
}
if (expires > _now())
{
return true;
}
_sessions.TryRemove(sessionId, out _);
return false;
}
/// <summary>«Esci»: closes a session.</summary>
public void Logout(string? sessionId)
{
if (!string.IsNullOrEmpty(sessionId))
{
_sessions.TryRemove(sessionId, out _);
}
}
private DateTimeOffset? LockedUntilLocked(string client, DateTimeOffset now)
{
DateTimeOffset? until = null;
if (_lockedClients.TryGetValue(client, out var c))
{
if (c > now)
{
until = c;
}
else
{
_lockedClients.Remove(client);
}
}
if (_lockedAll > now && (until is null || _lockedAll > until))
{
until = _lockedAll;
}
return until;
}
private static byte[] Hash(string text) => SHA256.HashData(Encoding.UTF8.GetBytes(text));
}
+135
View File
@@ -0,0 +1,135 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Security;
/// <summary>
/// Spec §13.1, first line of defence: the Host header must be one of the allowed names (desktop and demo: loopback with
/// the port, against DNS rebinding), and every request that changes something — plus the server-sent events and
/// WebSocket openings — must come from the interface itself: <c>Origin</c> equal to the interface, or, for browsers
/// that do not send it on same-origin requests, <c>Sec-Fetch-Site: same-origin</c>. Another page open in Alberto's
/// browser cannot command Febe or the remote view.
/// </summary>
public static class HostOriginGuard
{
/// <summary>Paths opened with GET that still count as commands (long-lived channels).</summary>
public static readonly IReadOnlyList<string> ChannelPaths = ["/api/eventi", "/api/vista"];
/// <summary>True when the Host header is acceptable.</summary>
public static bool HostAllowed(HttpRequest request, FebeWebOptions options)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(options);
if (!request.Host.HasValue)
{
return false;
}
if (options.AllowedHosts.Count == 0)
{
return true;
}
var host = request.Host.Value;
return options.AllowedHosts.Any(a => string.Equals(a, host, StringComparison.OrdinalIgnoreCase)
|| (a.EndsWith(":*", StringComparison.Ordinal) && request.Host.Port is not null
&& string.Equals(a[..^2], request.Host.Host, StringComparison.OrdinalIgnoreCase)));
}
/// <summary>True for requests that must pass the Origin check.</summary>
public static bool NeedsOriginCheck(HttpRequest request)
{
ArgumentNullException.ThrowIfNull(request);
if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method) && !HttpMethods.IsOptions(request.Method))
{
return true;
}
if (request.Headers.Upgrade.Count > 0)
{
return true;
}
var path = request.Path.Value ?? string.Empty;
return ChannelPaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// The Origin check. A present Origin must name the interface; without it, a present <c>Sec-Fetch-Site</c> must be
/// <c>same-origin</c>. Requests with neither come from programs, not from a web page, and are left to the access
/// check (token or password).
/// </summary>
public static bool OriginAllowed(HttpRequest request, FebeWebOptions options)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(options);
var origin = request.Headers.Origin.ToString();
if (!string.IsNullOrEmpty(origin))
{
if (string.Equals(origin, "null", StringComparison.Ordinal)
|| !Uri.TryCreate(origin, UriKind.Absolute, out var uri)
|| (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
{
return false;
}
var expected = ExpectedAuthority(request, options);
return expected is not null && string.Equals(Authority(uri), expected, StringComparison.OrdinalIgnoreCase);
}
var site = request.Headers["Sec-Fetch-Site"].ToString();
return string.IsNullOrEmpty(site) || string.Equals(site, "same-origin", StringComparison.OrdinalIgnoreCase);
}
private static string? ExpectedAuthority(HttpRequest request, FebeWebOptions options)
{
if (options.TrustForwardedHost && request.Headers["X-Forwarded-Host"].ToString() is { Length: > 0 } forwarded)
{
return NormalizeAuthority(forwarded.Split(',')[0].Trim(), request.Headers["X-Forwarded-Proto"].ToString().Split(',')[0].Trim() is { Length: > 0 } p ? p : request.Scheme);
}
return request.Host.HasValue ? NormalizeAuthority(request.Host.Value, request.Scheme) : null;
}
private static string Authority(Uri uri) => uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}";
private static string NormalizeAuthority(string hostAndPort, string scheme)
{
if (Uri.TryCreate($"{scheme}://{hostAndPort}", UriKind.Absolute, out var uri))
{
return Authority(uri);
}
return hostAndPort;
}
}
/// <summary>The per-start token of the desktop (spec §13.1, Windows).</summary>
public static class AccessToken
{
/// <summary>Cookie set when the window opens the interface with the token; HttpOnly, SameSite=Strict.</summary>
public const string CookieName = "febe_gettone";
/// <summary>Query parameter the window uses once: <c>http://127.0.0.1:port/?gettone=…</c>.</summary>
public const string QueryName = "gettone";
/// <summary>Header accepted instead of the cookie (programs, tests).</summary>
public const string HeaderName = "X-Febe-Gettone";
/// <summary>A new random token (256 bits, URL-safe).</summary>
public static string Create() => Base64Url(RandomNumberGenerator.GetBytes(32));
public static bool Matches(string? candidate, string? expected)
{
if (string.IsNullOrEmpty(candidate) || string.IsNullOrEmpty(expected))
{
return false;
}
return CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(candidate)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
}
internal static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
+158
View File
@@ -0,0 +1,158 @@
using Febe.Web.Api;
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Security;
/// <summary>
/// The pluggable access points of spec §13.1, in order: Host, Origin, then the access mode (none for the demo, token
/// for the desktop, password for Docker). Also sets the security headers of every response. Requests that fail get a
/// short Italian answer and are never logged with their query (the token travels there once).
/// </summary>
public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions options, PasswordAccess? passwords = null)
{
/// <summary>Paths reachable without a session in password mode: the login page and what it needs.</summary>
public static readonly IReadOnlyList<string> PublicPrefixes =
["/accesso", "/api/accesso", "/css/", "/caratteri/", "/img/", "/testi/", "/js/", "/favicon.ico"];
public async Task InvokeAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var request = context.Request;
var response = context.Response;
SetHeaders(response);
if (!HostOriginGuard.HostAllowed(request, options))
{
await RefuseAsync(context, StatusCodes.Status400BadRequest, "Indirizzo non ammesso: apri Febe dal suo indirizzo.").ConfigureAwait(false);
return;
}
if (HostOriginGuard.NeedsOriginCheck(request) && !HostOriginGuard.OriginAllowed(request, options))
{
await RefuseAsync(context, StatusCodes.Status403Forbidden, "Richiesta rifiutata: non arriva dall'interfaccia di Febe.").ConfigureAwait(false);
return;
}
switch (options.Access)
{
case AccessMode.Token:
if (await TokenAsync(context).ConfigureAwait(false))
{
await next(context).ConfigureAwait(false);
}
return;
case AccessMode.Password:
if (await PasswordAsync(context).ConfigureAwait(false))
{
await next(context).ConfigureAwait(false);
}
return;
default:
await next(context).ConfigureAwait(false);
return;
}
}
private async Task<bool> TokenAsync(HttpContext context)
{
var request = context.Request;
var query = request.Query[AccessToken.QueryName].ToString();
if (query.Length > 0)
{
if (!AccessToken.Matches(query, options.AccessToken))
{
await RefuseAsync(context, StatusCodes.Status401Unauthorized, "Gettone non valido: apri Febe dalla sua finestra.").ConfigureAwait(false);
return false;
}
context.Response.Cookies.Append(AccessToken.CookieName, query, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = request.IsHttps,
Path = "/",
IsEssential = true,
});
// The token leaves the address at once: it must not stay in the history or in a bookmark.
var rest = QueryString.Create(request.Query.Where(q => !string.Equals(q.Key, AccessToken.QueryName, StringComparison.Ordinal)));
context.Response.Redirect(request.PathBase + request.Path + rest);
return false;
}
var presented = request.Headers[AccessToken.HeaderName].ToString();
if (presented.Length == 0)
{
presented = request.Cookies[AccessToken.CookieName] ?? string.Empty;
}
if (AccessToken.Matches(presented, options.AccessToken))
{
return true;
}
await RefuseAsync(context, StatusCodes.Status401Unauthorized, "Questa pagina si apre solo dalla finestra di Febe.").ConfigureAwait(false);
return false;
}
private async Task<bool> PasswordAsync(HttpContext context)
{
if (passwords is null)
{
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "Manca la password dell'interfaccia (FEBE_PASSWORD): Febe non si apre senza.").ConfigureAwait(false);
return false;
}
var path = context.Request.Path.Value ?? "/";
if (PublicPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
{
return true;
}
if (passwords.IsValid(context.Request.Cookies[PasswordAccess.CookieName]))
{
return true;
}
if (IsApi(context.Request) || !HttpMethods.IsGet(context.Request.Method))
{
await RefuseAsync(context, StatusCodes.Status401Unauthorized, "Sessione scaduta: accedi di nuovo.").ConfigureAwait(false);
}
else
{
context.Response.Redirect("/accesso?torna=" + Uri.EscapeDataString(path));
}
return false;
}
private static bool IsApi(HttpRequest request) => request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase);
private static async Task RefuseAsync(HttpContext context, int status, string message)
{
context.Response.StatusCode = status;
if (IsApi(context.Request))
{
await context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
}
else
{
context.Response.ContentType = "text/plain; charset=utf-8";
await context.Response.WriteAsync(message).ConfigureAwait(false);
}
}
private static void SetHeaders(HttpResponse response)
{
var headers = response.Headers;
headers["X-Content-Type-Options"] = "nosniff";
headers["Referrer-Policy"] = "no-referrer";
headers["X-Frame-Options"] = "DENY";
headers["Cross-Origin-Opener-Policy"] = "same-origin";
headers["Content-Security-Policy"] =
"default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; "
+ "script-src 'self'; connect-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
}
}
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="it" data-tema="chiaro">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Accedi · Febe</title>
<link rel="icon" href="/img/marchio.svg" type="image/svg+xml">
<link rel="stylesheet" href="/css/febe.css">
<script src="/js/tema.js"></script>
<script type="module" src="/js/accesso.js"></script>
</head>
<body>
<main class="accesso" id="app"></main>
</body>
</html>
+394 -12
View File
@@ -137,13 +137,13 @@ svg.ic.l{width:22px;height:22px}
.campo.scelta{justify-content:space-between;font-weight:500}
.campo.sola{background:var(--rialzo);color:var(--testo-2)}
.gruppo{display:inline-flex;border:1px solid var(--bordo-forte);border-radius:var(--r-controllo);background:var(--superficie);padding:2px;gap:2px}
.gruppo span{height:28px;padding:0 12px;border-radius:5px;display:inline-flex;align-items:center;gap:6px;font-weight:500;font-size:13.5px;color:var(--testo-2);white-space:nowrap}
.gruppo span.qui{background:var(--accento-tinta);color:var(--accento-scuro);font-weight:600}
[data-tema="scuro"] .gruppo span.qui{color:var(--accento-scuro)}
.gruppo > span,.gruppo > button{height:28px;padding:0 12px;border-radius:5px;display:inline-flex;align-items:center;gap:6px;font-weight:500;font-size:13.5px;color:var(--testo-2);white-space:nowrap}
.gruppo > .qui{background:var(--accento-tinta);color:var(--accento-scuro);font-weight:600}
[data-tema="scuro"] .gruppo > .qui{color:var(--accento-scuro)}
.filtri{display:flex;gap:6px}
.filtri span{height:30px;padding:0 12px;border-radius:15px;display:inline-flex;align-items:center;gap:6px;font-weight:500;font-size:13.5px;color:var(--testo-2);border:1px solid var(--bordo);background:var(--superficie)}
.filtri span.qui{background:var(--testo);border-color:var(--testo);color:var(--superficie);font-weight:600}
.filtri span i{font-style:normal;font-size:12px;opacity:.7}
.filtri > span,.filtri > button{height:30px;padding:0 12px;border-radius:15px;display:inline-flex;align-items:center;gap:6px;font-weight:500;font-size:13.5px;color:var(--testo-2);border:1px solid var(--bordo);background:var(--superficie)}
.filtri > .qui{background:var(--testo);border-color:var(--testo);color:var(--superficie);font-weight:600}
.filtri > * i{font-style:normal;font-size:12px;opacity:.7}
.int{width:36px;height:20px;border-radius:10px;background:var(--bordo-forte);position:relative;flex:none;display:inline-block}
.int::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25)}
.int.si{background:var(--accento)} .int.si::after{left:18px}
@@ -166,8 +166,11 @@ svg.ic.l{width:22px;height:22px}
.misura.fine{height:4px}
/* ---------- avatar ---------- */
/* (il colore del testo vince sulle regole «.stato .chi span» e simili: le iniziali restano bianche) */
.av{width:32px;height:32px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;font-weight:650;font-size:12px;color:#fff;font-stretch:92%;letter-spacing:.02em;overflow:hidden}
.av.p{width:24px;height:24px;font-size:10px} .av.g{width:56px;height:56px;font-size:19px} .av.m{width:40px;height:40px;font-size:14px}
.av.p{width:24px;height:24px;font-size:10px}
span.av,.chi span.av,.chi-vis span.av{color:#fff}
span.av.segnaposto{color:var(--testo-2);background:var(--bordo-forte)} .av.g{width:56px;height:56px;font-size:19px} .av.m{width:40px;height:40px;font-size:14px}
/* ---------- pannelli e tabelle ---------- */
.pannello{background:var(--superficie);border:1px solid var(--bordo);border-radius:var(--r-pannello)}
@@ -178,9 +181,9 @@ svg.ic.l{width:22px;height:22px}
.tab tr.sopra td{background:var(--rialzo)}
.tab tr.scelto td{background:var(--accento-tinta)}
.linguette{display:flex;gap:22px;border-bottom:1px solid var(--bordo);padding:0 28px;flex:none}
.linguette span{padding:10px 0 11px;font-weight:500;color:var(--testo-2);border-bottom:2px solid transparent;margin-bottom:-1px;display:flex;gap:7px;align-items:baseline}
.linguette span.qui{color:var(--testo);font-weight:650;border-bottom-color:var(--accento)}
.linguette span i{font-style:normal;font-size:12px;color:var(--testo-3)}
.linguette > span,.linguette > a,.linguette > button{padding:10px 0 11px;font-weight:500;color:var(--testo-2);border-bottom:2px solid transparent;margin-bottom:-1px;display:flex;gap:7px;align-items:baseline}
.linguette > .qui{color:var(--testo);font-weight:650;border-bottom-color:var(--accento)}
.linguette > * i{font-style:normal;font-size:12px;color:var(--testo-3)}
/* ---------- tessere (foto) ---------- */
.tess{position:relative;border-radius:var(--r-tessera);overflow:hidden;background:var(--bordo);flex:none}
@@ -242,10 +245,340 @@ p.aiuto{margin:0;color:var(--testo-2);font-size:13px}
/* ---------- impostazioni: sotto-menu ---------- */
.imp{display:grid;grid-template-columns:238px 1fr;gap:28px;height:100%}
.imp nav{display:flex;flex-direction:column;gap:2px;padding-top:4px}
.imp nav span{white-space:nowrap;display:flex;align-items:center;gap:10px;height:34px;padding:0 10px;border-radius:var(--r-controllo);color:var(--testo-2);font-weight:500}
.imp nav span.qui{background:var(--superficie);border:1px solid var(--bordo);color:var(--testo);font-weight:600}
.imp nav > span,.imp nav > a{white-space:nowrap;display:flex;align-items:center;gap:10px;height:34px;padding:0 10px;border-radius:var(--r-controllo);color:var(--testo-2);font-weight:500}
.imp nav > .qui{background:var(--superficie);border:1px solid var(--bordo);color:var(--testo);font-weight:600}
.imp .cont{max-width:820px;min-width:0}
/* ==========================================================================
Estensioni per l'interfaccia vera (M4). I token e le classi qui sopra sono
quelli dell'appendice B; da qui in giù: elementi interattivi, schermate,
accessibilità. Le classi nuove seguono lo stesso vocabolario italiano.
========================================================================== */
/* ---------- base interattiva ---------- */
html{color-scheme:light}
[data-tema="scuro"]{color-scheme:dark}
button,input,select,textarea{font:inherit;color:inherit}
button{cursor:pointer}
button:disabled,.btn:disabled{cursor:default}
a{color:var(--accento)}
:focus{outline:none}
:focus-visible{outline:2px solid var(--accento);outline-offset:2px;border-radius:var(--r-controllo)}
.tess:focus-visible{outline:3px solid var(--accento);outline-offset:-3px;border-radius:var(--r-tessera)}
.vh{position:absolute!important;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
svg.ic{fill:none;stroke:currentColor;stroke-linecap:round;stroke-linejoin:round}
svg.ic.xs{width:12px;height:12px}
[hidden]{display:none!important}
.salta{position:absolute;left:12px;top:-60px;z-index:100;background:var(--superficie);border:1px solid var(--bordo-forte);border-radius:var(--r-controllo);padding:8px 12px;color:var(--testo)}
.salta:focus{top:12px}
.btn{text-decoration:none;user-select:none}
.btn:hover:not(:disabled){border-color:var(--testo-3)}
.btn.primo:hover:not(:disabled){background:var(--accento-scuro);border-color:var(--accento-scuro)}
[data-tema="scuro"] .btn.primo:hover:not(:disabled){background:var(--accento);border-color:var(--accento);filter:brightness(1.08)}
.btn.nudo:hover:not(:disabled){background:var(--rialzo);border-color:transparent}
.btn.pericolo.pieno{background:var(--rosso);border-color:var(--rosso);color:#fff}
.btn.nudo.pericolo{border-color:transparent}
.btn.nudo.pericolo:hover:not(:disabled){background:var(--rosso-tinta)}
[data-tema="scuro"] .btn.pericolo.pieno{color:#2A0F0C}
.btn:disabled{opacity:.45}
.btn svg.ic{width:17px;height:17px}
.btn.piccolo{height:30px;padding:0 11px;font-size:13px}
.btn.collegamento{border:0;background:none;color:var(--accento);padding:0;height:auto;font-weight:550}
.btn.collegamento:hover{text-decoration:underline}
.filtri{flex-wrap:wrap;align-items:center}
.filtri > button:hover:not(.qui){border-color:var(--bordo-forte);color:var(--testo)}
.filtri > button{cursor:pointer}
.gruppo > button{border:0;background:transparent;cursor:pointer}
.gruppo > button:hover:not(.qui){color:var(--testo)}
.linguette > a,.linguette > button{text-decoration:none;background:none;border-top:0;border-left:0;border-right:0;cursor:pointer}
.linguette > a:hover:not(.qui),.linguette > button:hover:not(.qui){color:var(--testo)}
.imp nav > a{text-decoration:none}
/* campi */
.campo input,.campo select,.campo textarea{border:0;background:transparent;outline:none;flex:1;min-width:0;padding:0;height:100%}
.campo input::placeholder,.campo textarea::placeholder{color:var(--testo-3)}
.campo:focus-within{border-color:var(--accento);box-shadow:0 0 0 3px var(--accento-tinta)}
.campo.cerca{color:var(--testo)}
.campo .unita{color:var(--testo-3);font-size:13px;flex:none}
.campo.area{height:auto;align-items:stretch;padding:9px 11px}
.campo.area textarea{resize:vertical;min-height:150px;line-height:1.5}
.campo.scelta{cursor:pointer;gap:10px}
.campo.scelta svg{margin-left:auto}
.campo.scelta.attivo{border-color:var(--testo-2)}
.campo select{-webkit-appearance:none;appearance:none;cursor:pointer;padding-right:4px;background:transparent;color:var(--testo);font-weight:500}
.campo.scelta:has(select){padding-right:11px}
.campo.scelta select + svg{pointer-events:none;color:var(--testo-3)}
.campo input[type=date]{min-width:0}
.campo[aria-disabled="true"]{background:var(--rialzo);color:var(--testo-2)}
input[type=number]{-moz-appearance:textfield}
input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}
/* interruttori, spunte, tondi come input veri (accessibili da tastiera) */
.leva{display:inline-flex;align-items:center;gap:10px;cursor:pointer;position:relative}
input:checked + .int{background:var(--accento)}
input:checked + .int::after{left:18px}
[data-tema="scuro"] input:checked + .int::after{background:#0C2230}
input:disabled + .int{opacity:.4}
input:focus-visible + .int,input:focus-visible + .spunta,input:focus-visible + .tondo{outline:2px solid var(--accento);outline-offset:2px}
.int::after{transition:left .12s ease}
input:checked + .spunta{background:var(--accento);border-color:var(--accento);color:var(--su-accento)}
input:not(:checked) + .spunta svg{visibility:hidden}
input:checked + .tondo{border-color:var(--accento)}
input:checked + .tondo::after{content:"";position:absolute;inset:3px;border-radius:50%;background:var(--accento)}
input:disabled + .spunta{opacity:.6}
.voce{cursor:pointer;position:relative}
.voce.spenta{opacity:.5;cursor:default}
/* cursore */
input[type=range].cursore{-webkit-appearance:none;appearance:none;width:96px;height:20px;background:transparent;cursor:pointer}
input[type=range].cursore::-webkit-slider-runnable-track{height:3px;border-radius:2px;background:var(--bordo-forte)}
input[type=range].cursore::-moz-range-track{height:3px;border-radius:2px;background:var(--bordo-forte)}
input[type=range].cursore::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;margin-top:-6.5px;border-radius:50%;background:var(--superficie);border:1.5px solid var(--testo-2);box-shadow:0 1px 2px rgba(0,0,0,.2)}
input[type=range].cursore::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--superficie);border:1.5px solid var(--testo-2)}
input[type=range].cursore:focus-visible{outline:2px solid var(--accento);outline-offset:3px}
.grandezza{display:flex;align-items:center;gap:8px;color:var(--testo-2)}
/* menu a comparsa */
.menu{position:fixed;z-index:60;min-width:200px;max-width:340px;max-height:min(420px,70vh);overflow:auto;background:var(--superficie);border:1px solid var(--bordo);border-radius:var(--r-pannello);box-shadow:var(--ombra-menu);padding:6px}
.menu [role=menuitem],.menu [role=menuitemradio],.menu [role=menuitemcheckbox],.menu .riga{display:flex;align-items:center;gap:10px;width:100%;min-height:34px;padding:6px 10px;border:0;border-radius:6px;background:transparent;text-align:left;color:var(--testo);font-size:13.5px}
.menu [role^=menuitem]:hover,.menu [role^=menuitem]:focus-visible{background:var(--rialzo);outline:none}
.menu [role^=menuitem][aria-checked=true]{font-weight:600}
.menu [role^=menuitem][aria-checked=true] .ic.segno{visibility:visible}
.menu .ic.segno{visibility:hidden;color:var(--accento);margin-left:auto}
.menu [role^=menuitem].pericolo{color:var(--rosso)}
.menu hr{border:0;border-top:1px solid var(--bordo);margin:6px 4px}
.menu .cerca-menu{margin:2px 2px 6px}
.menu .vuoto{padding:10px;color:var(--testo-2);font-size:13px}
.menu .date{display:flex;gap:8px;padding:6px 6px 4px;align-items:center}
.menu .date .campo{flex:1}
/* avvisi brevi */
.brevi{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:80;display:flex;flex-direction:column;gap:8px;align-items:center;pointer-events:none}
.breve{pointer-events:auto;display:flex;gap:10px;align-items:flex-start;max-width:min(560px,calc(100vw - 32px));padding:11px 14px;border-radius:var(--r-pannello);background:var(--testo);color:var(--superficie);box-shadow:var(--ombra-menu);font-size:13.5px}
.breve.errore{background:var(--rosso);color:#fff}
[data-tema="scuro"] .breve.errore{color:#2A0F0C}
.breve svg{flex:none;margin-top:1px}
/* dialoghi */
.velo.finestra{position:fixed;z-index:40;padding:16px}
.dialogo{max-height:calc(100vh - 32px);max-width:calc(100vw - 32px)}
.dialogo header .btn.solo{margin-left:auto}
.dialogo .contenuto{padding:10px 22px 18px;overflow:auto}
.dialogo .contenuto p{margin:0 0 12px}
.dialogo .scelte{display:flex;flex-direction:column;gap:10px;margin:12px 0 4px}
.dialogo .scelte .voce{align-items:flex-start}
.dialogo .scelte .voce .tondo{margin-top:2px}
.dialogo .scelte small{display:block;color:var(--testo-2);font-size:12.5px}
.dialogo.piccolo{width:480px}
/* striscia rossa di arresto, in cima a ogni pagina */
.arresto{margin:0 28px 14px;flex:none;display:flex;gap:12px;align-items:center;padding:12px 14px;border-radius:var(--r-pannello);background:var(--rosso-tinta);border:1px solid color-mix(in srgb,var(--rosso) 35%,transparent);color:var(--testo)}
.arresto.ambra{background:var(--ambra-tinta);border-color:color-mix(in srgb,var(--ambra) 35%,transparent)}
.arresto > svg{color:var(--rosso);flex:none}
.arresto.ambra > svg{color:var(--ambra)}
.arresto .testo{flex:1;min-width:0}
.arresto b{display:block;font-weight:650;font-size:14.5px}
.arresto span{font-size:13px;color:var(--testo-2)}
.arresto .azioni{display:flex;gap:8px;flex:none}
/* ossatura: elementi in più */
.nav a{position:relative}
.nav a:hover:not(.qui){color:var(--testo);background:color-mix(in srgb,var(--superficie) 55%,transparent)}
.marchio{color:var(--testo);text-decoration:none}
.stato{display:block;text-decoration:none;color:var(--testo)}
a.stato:hover{border-color:var(--bordo-forte)}
.stato .chi .av{color:#fff;font-size:12px}
.stato .misura{margin-top:10px}
.indietro{display:inline-flex;align-items:center;gap:6px;margin:18px 28px 0;color:var(--testo-2);text-decoration:none;font-size:13.5px;align-self:flex-start;flex:none}
.indietro:hover{color:var(--testo)}
.corpo{overflow-anchor:none}
.salva{flex:none;display:flex;align-items:center;gap:10px;padding:12px 28px;border-top:1px solid var(--bordo);background:var(--superficie)}
.salva .destra{margin-left:auto;display:flex;gap:10px}
.salva .nota{color:var(--testo-2);font-size:13.5px}
.vuoto-pagina{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:10px;padding:80px 20px;color:var(--testo-2)}
.vuoto-pagina h2{margin:0;color:var(--testo);font-size:17px;font-weight:650}
.vuoto-pagina svg.ic{width:28px;height:28px;color:var(--testo-3)}
.caricamento{padding:40px 0;text-align:center;color:var(--testo-2)}
/* ---------- libreria ---------- */
.strumenti .scelte-menu{display:flex;gap:10px;margin-left:6px}
.strumenti .scelte-menu .campo.scelta{min-width:110px}
.mosaico{position:relative}
.mosaico .gruppo-giorno{contain:layout}
.mosaico .righe{position:relative}
.mosaico .segnaposto{border-radius:var(--r-tessera);background:var(--barra)}
.tess{padding:0;border:0;cursor:pointer;display:block;color:#fff;text-align:left}
.tess img{display:block;width:100%;height:100%;object-fit:cover;background:var(--bordo)}
.tess .chi,.tess .sel{display:none}
.tess:hover::after,.tess:focus-visible::after,.tess.scelta::after{content:"";position:absolute;inset:0;pointer-events:none;background:linear-gradient(180deg,rgba(0,0,0,.42) 0,rgba(0,0,0,0) 34%,rgba(0,0,0,0) 54%,rgba(0,0,0,.62) 100%)}
.tess:hover .chi,.tess:focus-visible .chi{display:flex}
.tess:hover .sel,.tess:focus-visible .sel,.mosaico.scegli .tess .sel,.tess.scelta .sel{display:flex}
.tess .segno{z-index:2}
.tess .segno .anello{padding:0 4px}
.tess .chi .av{color:#fff}
.tess .sel{cursor:pointer}
.tess .sel:hover{background:rgba(0,0,0,.45)}
.tess.scelta .sel:hover{background:var(--accento)}
.tess .sel svg{visibility:hidden}
.tess.scelta .sel svg{visibility:visible}
.tess.vuota{background:var(--bordo);display:flex;align-items:center;justify-content:center;color:var(--testo-3)}
.giorno{scroll-margin-top:8px}
.mosaico .gruppo-giorno .giorno{margin-top:18px}
.mosaico .gruppo-giorno:first-child .giorno{margin-top:2px}
.linguette + .strumenti{padding-top:14px}
.nuovi-in-cima{position:sticky;top:6px;z-index:5;display:flex;justify-content:center;height:0}
.nuovi-in-cima .btn{box-shadow:var(--ombra-menu);height:32px}
.griglia-storie{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:4px}
.raccolta-titolo{display:flex;align-items:baseline;gap:10px;margin:18px 0 8px}
.raccolta-titolo b{font-size:15px;font-weight:650}
.raccolta-titolo span{color:var(--testo-2);font-size:13px}
/* ---------- visualizzatore ---------- */
.vis{position:fixed;inset:0;z-index:50;display:grid;grid-template-columns:1fr 380px;background:#141414;color:#fff}
.vis .palco{position:relative;display:flex;flex-direction:column;min-width:0;min-height:0}
.vis .palco-testa{display:flex;align-items:center;gap:10px;padding:14px 16px;flex:none}
.vis .palco-testa .dove{font-size:13px;color:rgba(255,255,255,.72)}
.vis .palco-testa .destra{margin-left:auto;display:flex;gap:6px}
.vis .tondino{width:34px;height:34px;border-radius:8px;border:0;background:rgba(255,255,255,.08);color:#fff;display:inline-flex;align-items:center;justify-content:center}
.vis .tondino:hover{background:rgba(255,255,255,.16)}
.vis .tondino:disabled{opacity:.3}
.vis .scena{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:0 72px;position:relative}
.vis .scena img,.vis .scena video{max-width:100%;max-height:100%;object-fit:contain;display:block;box-shadow:0 10px 40px rgba(0,0,0,.45);background:#222}
.vis .scena.ingrandita{overflow:auto;align-items:flex-start;justify-content:flex-start}
.vis .scena.ingrandita img{max-width:none;max-height:none;cursor:zoom-out}
.vis .scena img{cursor:zoom-in}
.vis .freccia{position:absolute;top:50%;transform:translateY(-50%);width:40px;height:40px;border-radius:50%;border:0;background:rgba(255,255,255,.1);color:#fff;display:flex;align-items:center;justify-content:center;z-index:2}
.vis .freccia:hover{background:rgba(255,255,255,.2)}
.vis .freccia:disabled{opacity:.25}
.vis .freccia.sx{left:16px} .vis .freccia.dx{right:16px}
.vis .mancante{display:flex;flex-direction:column;align-items:center;gap:10px;color:rgba(255,255,255,.75);text-align:center;max-width:380px}
.vis .mancante img{max-height:50vh;opacity:.7}
.vis .serie{display:flex;gap:6px;justify-content:center;padding:12px 16px 16px;flex:none;overflow-x:auto}
.vis .serie button{width:44px;height:44px;border-radius:4px;border:2px solid transparent;padding:0;overflow:hidden;background:#2a2a2a;flex:none;opacity:.7;position:relative}
.vis .serie button img{width:100%;height:100%;object-fit:cover;display:block}
.vis .serie button.qui{border-color:#fff;opacity:1}
.vis .serie button:hover{opacity:1}
.vis .serie button svg{position:absolute;right:2px;bottom:2px;width:12px;height:12px;stroke-width:2.4;filter:drop-shadow(0 0 2px #000)}
.vis .scheda{background:var(--superficie);color:var(--testo);border-left:1px solid var(--bordo);display:flex;flex-direction:column;min-height:0}
.vis .scheda .alto{padding:18px 18px 4px;overflow:auto;flex:1}
.vis .scheda .chi-vis{display:flex;align-items:center;gap:10px;margin-bottom:14px}
.vis .scheda .chi-vis b{display:block;font-weight:650}
.vis .scheda .chi-vis div > span{font-size:12.5px;color:var(--testo-2)}
.vis .scheda .chi-vis .et{margin-left:auto}
.vis .scheda .etichette{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px}
.vis .scheda .quando b{display:block;font-weight:650}
.vis .scheda .quando span{font-size:12.5px;color:var(--testo-2)}
.vis .scheda section{padding:14px 0;border-top:1px solid var(--bordo)}
.vis .scheda section:first-of-type{margin-top:14px}
.vis .scheda h3{margin:0 0 8px;font-size:13.5px;font-weight:650}
.vis .scheda .didascalia{white-space:pre-wrap;overflow-wrap:anywhere;font-size:13.5px;margin:0}
.vis .scheda dl{display:grid;grid-template-columns:96px 1fr;gap:6px 10px;margin:0;font-size:13px}
.vis .scheda dt{color:var(--testo-2)}
.vis .scheda dd{margin:0;overflow-wrap:anywhere}
.vis .scheda .basso{padding:12px 18px 16px;display:flex;flex-direction:column;gap:8px;border-top:1px solid var(--bordo)}
.vis .scheda .basso .btn{justify-content:center;width:100%}
.vis .scheda .basso .btn.nudo.pericolo{color:var(--rosso)}
/* ---------- account ---------- */
.tabella-account{overflow:hidden}
.tabella-account .tab tbody tr{cursor:pointer}
.tabella-account .tab tbody tr:hover td{background:var(--rialzo)}
.tabella-account .tab td{padding-top:12px;padding-bottom:12px}
.tabella-account .tab{table-layout:auto}
.tabella-account th.col-raccoglie{width:136px}
.tabella-account th.col-stato{width:236px}
.tabella-account td.col-stato{padding-right:4px}
.tabella-account th.col-ultimo{width:118px}
.tabella-account th.col-prossimo{width:108px}
.tabella-account th.col-libreria{width:76px}
.tabella-account th.col-tieni{width:112px;padding-left:16px;padding-right:4px}
.tabella-account td.col-tieni{padding-left:16px}
.tabella-account .col-ultimo,.tabella-account .col-prossimo,.tabella-account .col-libreria{white-space:nowrap}
.tabella-account .nome .sotto{flex-wrap:nowrap;white-space:nowrap}
.tabella-account .nome{display:flex;align-items:center;gap:12px;min-width:0}
.tabella-account .nome b{display:block;font-weight:650;font-size:14.5px;line-height:1.3}
.tabella-account .nome .sotto{display:flex;align-items:center;gap:6px;color:var(--testo-2);font-size:13px;margin-top:3px}
.raccoglie{display:flex;gap:9px;color:var(--testo-2)}
.raccoglie svg.spento{opacity:.28}
.condizione{display:flex;flex-direction:column;gap:2px;min-width:0}
.condizione .riga{display:flex;align-items:center;gap:8px;font-weight:600}
.condizione .sotto{font-size:12.5px;color:var(--testo-2);padding-left:16px}
.condizione .misura{margin:5px 0 0 16px;width:150px}
.tabella-account .num{text-align:right;font-variant-numeric:tabular-nums}
.tabella-account td.menu-riga{width:32px;text-align:right;padding-left:0;padding-right:4px}
.tabella-account td.menu-riga .btn.solo{width:28px}
.tabella-account .muto-cella{color:var(--testo-2)}
/* scheda account */
.scheda-testa{display:flex;align-items:center;gap:16px;padding:10px 28px 14px;flex:none}
.scheda-testa .nomi{min-width:0}
.scheda-testa h1{margin:0;font-size:22px;font-weight:650;font-stretch:104%;line-height:1.2}
.scheda-testa .sotto{display:flex;gap:6px;align-items:center;flex-wrap:wrap;color:var(--testo-2);font-size:13px;margin-top:4px}
.scheda-testa .numeri{margin-left:auto;display:flex;gap:26px;margin-right:14px}
.scheda-testa .numeri div{display:flex;flex-direction:column}
.scheda-testa .numeri b{font-size:16px;font-weight:650;font-variant-numeric:tabular-nums}
.scheda-testa .numeri span{font-size:12px;color:var(--testo-2);white-space:nowrap}
.scheda-testa .azioni{display:flex;gap:8px;align-items:center}
.av.g img,.av img{width:100%;height:100%;object-fit:cover;display:block}
.imp-account{display:grid;grid-template-columns:minmax(0,1fr) 360px;gap:36px;align-items:start}
.imp-account .colonna{min-width:0}
.imp-account .sezione{padding:18px 0}
.imp-account .sezione:first-child{padding-top:6px}
.riga-campi{display:flex;gap:14px;flex-wrap:wrap;margin-top:12px}
.riga-campi > div{flex:1;min-width:180px}
.frequenza{display:flex;align-items:center;gap:14px;flex-wrap:wrap;margin-top:8px}
.frequenza .nota{font-size:13px;color:var(--testo-2)}
.tipi{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:12px}
.tipo{display:flex;align-items:center;gap:10px;height:44px;padding:0 12px;border:1px solid var(--bordo);border-radius:var(--r-controllo);background:var(--superficie);cursor:pointer}
.tipo span.testo{flex:1;min-width:0;font-weight:500;font-size:13.5px}
.tipo svg.ic{color:var(--testo-3)}
.tipo:has(input:checked){border-color:var(--bordo-forte)}
.tipo:has(input:not(:checked)) span.testo{color:var(--testo-2)}
.cartella{display:flex;gap:10px;margin-top:12px}
.cartella .campo{flex:1}
.piano{position:sticky;top:0;display:flex;flex-direction:column;gap:12px}
.piano .pannello{padding:16px}
.piano h2{margin:0 0 6px;font-size:14.5px;font-weight:650}
.piano .voce-piano{display:flex;gap:10px;padding:10px 0;border-bottom:1px solid var(--bordo);font-size:13px;color:var(--testo-2)}
.piano .voce-piano:last-child{border-bottom:0;padding-bottom:0}
.piano .voce-piano b{color:var(--testo);font-weight:650}
.piano .voce-piano svg.ic{color:var(--testo-3);margin-top:1px}
.piano .misura{margin-top:8px}
.piano .carico small{display:block;margin-top:6px;color:var(--testo-3);font-size:12px}
.cronologia{max-width:900px}
.cronologia .tab td{font-size:13.5px}
.cronologia .quando-cella{white-space:nowrap;color:var(--testo-2);width:150px}
/* dialogo «Aggiungi account» */
.aggiungi{width:min(900px,calc(100vw - 32px));height:min(660px,calc(100vh - 32px))}
.aggiungi .linguette{padding:0 22px;margin-top:6px}
.aggiungi .corpo-dialogo{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 316px}
.aggiungi .sinistra{display:flex;flex-direction:column;min-height:0;padding:14px 18px 0 22px;border-right:1px solid var(--bordo)}
.aggiungi .destra-dialogo{padding:16px 18px;overflow:auto;background:var(--superficie)}
.aggiungi .cerca-riga{display:flex;gap:10px;margin-bottom:6px}
.aggiungi .cerca-riga .campo{flex:1}
.aggiungi .elenco{flex:1;overflow:auto;margin:0 -18px 0 -4px;padding:0 18px 0 4px}
.aggiungi .elenco .voce{padding:9px 2px;border-bottom:1px solid var(--bordo);gap:12px}
.aggiungi .elenco .voce.presente{opacity:.5}
.aggiungi .elenco .voce .chi-nome{flex:1;min-width:0}
.aggiungi .elenco .voce b{display:block;font-weight:600;font-size:13.5px}
.aggiungi .elenco .voce small{color:var(--testo-2);font-size:12.5px}
.aggiungi .avanzamento{display:flex;gap:8px;align-items:center;font-size:12.5px;color:var(--testo-2);padding:8px 0}
.aggiungi .partenza{display:flex;flex-direction:column;gap:8px;margin:10px 0 14px}
.aggiungi .partenza label{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border:1px solid var(--bordo);border-radius:var(--r-controllo);cursor:pointer;position:relative}
.aggiungi .partenza label:has(input:checked){border-color:var(--accento);box-shadow:0 0 0 1px var(--accento)}
.aggiungi .partenza b{display:block;font-weight:600;font-size:13.5px}
.aggiungi .partenza small{display:block;color:var(--testo-2);font-size:12px;line-height:1.35;margin-top:2px}
.aggiungi .partenza .tondo{margin-top:2px}
.aggiungi .problemi{margin-top:10px;font-size:12.5px;color:var(--rosso);display:flex;flex-direction:column;gap:3px}
.aggiungi .riconosciuti{margin-top:10px;font-size:12.5px;color:var(--testo-2)}
/* ---------- pagine segnaposto per la seconda parte ---------- */
.prossimamente{max-width:620px}
/* ---------- finestra stretta e telefono ---------- */
@media (max-width:1000px){
.app{grid-template-columns:64px 1fr}
@@ -268,3 +601,52 @@ p.aiuto{margin:0;color:var(--testo-2);font-size:13px}
.pagina{height:auto;min-height:0;overflow:hidden}
.testa{padding:16px 16px 10px} .testa h1{font-size:20px} .corpo{padding:0 16px 16px} .strumenti{padding:0 16px 12px}
}
/* ---------- finestra stretta e telefono: schermate ---------- */
.solo-stretto{display:none!important}
@media (max-width:1000px){
.solo-stretto{display:inline-flex!important} .solo-largo{display:none!important}
.arresto{margin:0 20px 14px}
.indietro{margin-left:20px}
.scheda-testa{padding-left:20px;padding-right:20px;flex-wrap:wrap}
.scheda-testa .numeri{margin:0;order:3;width:100%;gap:20px}
.imp-account{grid-template-columns:1fr}
.piano{position:static}
.vis{grid-template-columns:1fr 300px}
.strumenti{flex-wrap:wrap}
.salva{padding:12px 20px}
.tabella-account .col-raccoglie,.tabella-account .col-prossimo{display:none}
.aggiungi .corpo-dialogo{grid-template-columns:minmax(0,1fr) 240px}
}
@media (max-width:560px){
.arresto{margin:0 16px 12px;flex-wrap:wrap}
.indietro{margin-left:16px}
.testa .destra .campo.cerca{display:none}
.scheda-testa{padding-left:16px;padding-right:16px}
.vis{grid-template-columns:1fr;grid-template-rows:minmax(0,1fr) auto}
.vis .scheda{max-height:42vh;border-left:0;border-top:1px solid var(--bordo)}
.vis .scena{padding:0 8px}
.vis .freccia{display:none}
.testa .quanti{display:none}
.tabella-account .tab,.tabella-account .tab tbody,.tabella-account .tab tr,.tabella-account .tab td{display:block}
.tabella-account .tab thead{display:none}
.tabella-account .tab tr{position:relative;padding:12px 44px 12px 14px;border-bottom:1px solid var(--bordo)}
.tabella-account .tab tr:last-child{border-bottom:0}
.tabella-account .tab td{padding:0;border:0}
.tabella-account .tab td.col-raccoglie,.tabella-account .tab td.col-ultimo,.tabella-account .tab td.col-prossimo,.tabella-account .tab td.col-libreria,.tabella-account .tab td.col-tieni{display:none}
.tabella-account .tab td.col-stato{margin:8px 0 0 44px}
.tabella-account .tab td.menu-riga{position:absolute;right:4px;top:12px;width:auto}
.tabella-account .nome .sotto{flex-wrap:wrap;white-space:normal}
.tipi{grid-template-columns:1fr 1fr}
.aggiungi .corpo-dialogo{grid-template-columns:1fr;overflow:auto}
.aggiungi .sinistra{border-right:0;min-height:320px}
.salva{padding:10px 16px;flex-wrap:wrap}
.brevi{bottom:72px}
}
/* ---------- animazioni: solo in risposta a un gesto, e mai con le animazioni ridotte ---------- */
@keyframes febe-compare{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.dialogo,.menu,.breve{animation:febe-compare .14s ease-out}
@media (prefers-reduced-motion:reduce){
*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}
}
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="it" data-tema="chiaro" aria-busy="true">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Febe</title>
<link rel="icon" href="/img/marchio.svg" type="image/svg+xml">
<link rel="preload" href="/caratteri/archivo-latin-standard-normal.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="/css/febe.css">
<script src="/js/tema.js"></script>
<script type="module" src="/js/app.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
+51
View File
@@ -0,0 +1,51 @@
// The login page of the Docker interface (spec §13.1): one password, an HttpOnly SameSite=Strict session cookie set
// by the server, lockout after repeated failures. Nothing is stored by this page.
import { h, fill, brand } from './core/dom.js';
import { loadTexts, t } from './core/text.js';
async function boot() {
await loadTexts('it');
const root = document.getElementById('app');
const password = h('input', { type: 'password', id: 'password', autocomplete: 'current-password', required: true, autofocus: true });
const message = h('p.aiuto', { role: 'alert', style: { color: 'var(--rosso)', minHeight: '20px' } });
const button = h('button.btn.primo.grande', { type: 'submit', style: { width: '100%', justifyContent: 'center' } }, t('accesso.entra'));
const form = h('form.pannello', { style: { width: 'min(360px, calc(100vw - 32px))', padding: '28px', display: 'flex', flexDirection: 'column', gap: '12px' } },
h('div.marchio', { style: { padding: '0 0 6px' } }, brand(), h('b', t('app.nome'))),
h('h1', { style: { margin: '0', fontSize: '20px', fontWeight: '650' } }, t('accesso.titolo')),
h('label.etichetta', { for: 'password' }, t('accesso.password')),
h('div.campo', password),
h('p.aiuto', t('accesso.aiuto')),
message,
button);
form.addEventListener('submit', async (e) => {
e.preventDefault();
button.disabled = true;
message.textContent = '';
try {
const response = await fetch('/api/accesso', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ password: password.value }),
});
const data = await response.json().catch(() => ({}));
if (response.ok && data.ok) {
const back = new URLSearchParams(location.search).get('torna');
location.href = back && back.startsWith('/') && !back.startsWith('//') ? back : '/libreria';
return;
}
message.textContent = data.message || t('accesso.sbagliata');
password.value = '';
password.focus();
} catch {
message.textContent = t('comune.errore');
} finally {
button.disabled = false;
}
});
root.style.cssText = 'min-height:100vh;display:flex;align-items:center;justify-content:center;padding:16px';
fill(root, form);
}
boot();
+39
View File
@@ -0,0 +1,39 @@
// Start of the interface: texts, icons, capabilities of the shell, theme, frame, events, router.
import { api, initCarried, setAccess } from './core/api.js';
import { setCapabilities } from './core/context.js';
import { loadIcons, h, fill } from './core/dom.js';
import { startEvents } from './core/engine.js';
import { buildShell, startRouter } from './core/shell.js';
import { loadTexts, t } from './core/text.js';
import { initTheme } from './core/theme.js';
async function boot() {
initCarried();
const root = document.getElementById('app');
try {
await Promise.all([loadTexts(document.documentElement.lang || 'it'), loadIcons()]);
} catch {
fill(root, h('p', { style: { padding: '24px' } }, 'Febe non riesce a caricare i testi dell\'interfaccia. Ricarica la pagina.'));
return;
}
try {
const capabilities = await api('/api/capabilities');
setCapabilities(capabilities);
setAccess(capabilities.access);
if (capabilities.demo) document.documentElement.dataset.dimostrazione = '';
} catch {
// the defaults describe a plain browser
}
initTheme();
buildShell(root);
startEvents();
startRouter();
document.documentElement.removeAttribute('aria-busy');
window.addEventListener('unhandledrejection', (e) => {
if (e.reason && e.reason.name === 'AbortError') e.preventDefault();
});
void t;
}
boot();
+117
View File
@@ -0,0 +1,117 @@
// Calls to the API of Febe. In the demo the scene (scena) and the imitated shell (veste) chosen in the address are
// carried on every call and on every internal link, so that the whole interface stays in the chosen scene.
import { t } from './text.js';
/** Query parameters that travel with every page and call (demo and screenshots). */
export const CARRIED = ['scena', 'veste', 'tema'];
const carried = {};
/** Reads the carried parameters from the address (and from the previous pages of this tab). */
export function initCarried() {
const query = new URLSearchParams(location.search);
for (const key of CARRIED) {
let value = query.get(key);
try {
if (value) sessionStorage.setItem(`febe.${key}`, value);
else value = sessionStorage.getItem(`febe.${key}`);
} catch {
// no session storage: the address is the only source
}
if (value) carried[key] = value;
}
}
export function carriedValue(key) {
return carried[key];
}
/** Adds the carried parameters to an internal address. */
export function withCarried(url) {
const u = new URL(url, location.origin);
for (const [key, value] of Object.entries(carried)) {
if (!u.searchParams.has(key)) u.searchParams.set(key, value);
}
return u.pathname + u.search + u.hash;
}
/** An API error with the Italian message given by the server. */
export class ApiError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
function headers(extra) {
const h = { Accept: 'application/json', ...extra };
if (carried.scena) h['X-Febe-Scena'] = carried.scena;
if (carried.veste) h['X-Febe-Veste'] = carried.veste;
return h;
}
/**
* Calls the API and returns the JSON answer. Errors become ApiError with the message to show.
* options: method, body (object → JSON), signal, raw (returns the Response).
*/
export async function api(path, options = {}) {
const { method = 'GET', body, signal, raw = false } = options;
let response;
try {
response = await fetch(path, {
method,
signal,
credentials: 'same-origin',
headers: headers(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
body: body !== undefined ? JSON.stringify(body) : undefined,
});
} catch (error) {
if (error.name === 'AbortError') throw error;
throw new ApiError(0, t('comune.errore'));
}
if (response.status === 401 && access === 'password') {
// Password mode: the session ended; go back to the login page.
location.href = `/accesso?torna=${encodeURIComponent(location.pathname)}`;
}
if (!response.ok) {
let message = t('comune.errore');
try {
const data = await response.json();
if (data && data.message) message = data.message;
} catch {
// not JSON
}
throw new ApiError(response.status, message);
}
if (raw) return response;
if (response.status === 204) return null;
return response.json();
}
let access;
/** Remembers the access mode from the capabilities (password, token, none). */
export function setAccess(mode) {
access = mode;
}
/** The address of the event stream, with the carried parameters (EventSource cannot send headers). */
export function eventsUrl() {
return withCarried('/api/eventi');
}
/** Downloads an answer as a file (CSV export). */
export async function download(path, body, fallbackName) {
const response = await api(path, { method: 'POST', body, raw: true });
const blob = await response.blob();
const disposition = response.headers.get('Content-Disposition') || '';
const match = /filename="?([^";]+)"?/.exec(disposition);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = match ? match[1] : fallbackName;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
}
+39
View File
@@ -0,0 +1,39 @@
// What the shell can do (GET /api/capabilities): Docker or desktop, demo, native functions. Pages read it to show
// «Mostra nella cartella» or «Scarica», read-only folders in Docker, the Windows-only «Avvio» block.
let capabilities = {
edition: 'docker',
demo: false,
access: 'none',
showInFolder: false,
pickFolder: false,
openUrlNative: false,
foldersReadOnly: true,
autostart: false,
browserWindow: false,
notifications: false,
version: '',
scene: null,
scenes: [],
now: Date.now(),
today: '',
};
let skew = 0;
export function setCapabilities(value) {
if (value) capabilities = { ...capabilities, ...value };
if (value && value.now) skew = value.now - Date.now();
}
/** The server's clock now (milliseconds), for «8 min fa». */
export function serverNow() {
return Date.now() + skew;
}
/** The capabilities of this shell (see CapabilitiesDto). */
export function caps() {
return capabilities;
}
export const isDesktop = () => capabilities.edition === 'desktop';
+126
View File
@@ -0,0 +1,126 @@
// Small DOM helpers: no framework, no build. Text is always set as text (never as HTML), so captions and names from
// Instagram can never become markup.
const SVG = 'http://www.w3.org/2000/svg';
/**
* Creates an element: h('button.btn.primo', { type: 'button', onclick }, 'Salva').
* Attributes: class, style (object), dataset (object), on<event> (function), boolean true → empty attribute,
* null/false/undefined → skipped. Children: nodes, strings, numbers, arrays (flattened), null (skipped).
*/
export function h(tag, attrs, ...children) {
const [name, ...classes] = tag.split('.');
const el = document.createElement(name || 'div');
if (classes.length) el.className = classes.join(' ');
if (attrs && (attrs instanceof Node || typeof attrs !== 'object' || Array.isArray(attrs))) {
children.unshift(attrs);
attrs = null;
}
for (const [key, value] of Object.entries(attrs || {})) {
if (value == null || value === false) continue;
if (key === 'class') el.className = [el.className, value].filter(Boolean).join(' ');
else if (key === 'style' && typeof value === 'object') Object.assign(el.style, value);
else if (key === 'dataset') Object.assign(el.dataset, value);
else if (key.startsWith('on') && typeof value === 'function') el.addEventListener(key.slice(2), value);
else if (key === 'value' && 'value' in el) el.value = value;
else if (key === 'checked' || key === 'disabled' || key === 'selected') el[key] = Boolean(value);
else el.setAttribute(key, value === true ? '' : String(value));
}
append(el, children);
return el;
}
export function append(el, children) {
for (const child of children.flat(Infinity)) {
if (child == null || child === false) continue;
el.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return el;
}
/** Replaces all children. */
export function fill(el, ...children) {
el.replaceChildren();
return append(el, children);
}
/** An icon from the sprite (wwwroot/icone, Lucide, stroke 1.75): <svg class="ic"><use href="#i-name"/></svg>. */
export function icon(name, size = '') {
const svg = document.createElementNS(SVG, 'svg');
svg.setAttribute('class', `ic${size ? ' ' + size : ''}`);
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
const use = document.createElementNS(SVG, 'use');
use.setAttribute('href', `#i-${name}`);
svg.append(use);
return svg;
}
/** The brand mark (appendix C), inline. */
export function brand() {
const svg = document.createElementNS(SVG, 'svg');
svg.setAttribute('viewBox', '0 0 32 32');
svg.setAttribute('aria-hidden', 'true');
svg.innerHTML = '<rect width="32" height="32" rx="8" fill="#0F5C8C"/><circle cx="14.5" cy="17.5" r="7.4" fill="none" stroke="#FFFFFF" stroke-width="2.6"/><circle cx="23.2" cy="8.8" r="3.1" fill="#FFFFFF"/>';
return svg;
}
/** Inlines the icon sprite once (hidden), so every <use href="#i-…"> works offline and with currentColor. */
export async function loadIcons() {
const response = await fetch('/icone/tutte.svg');
if (!response.ok) return;
const holder = document.createElement('div');
holder.hidden = true;
holder.innerHTML = await response.text();
document.body.prepend(holder);
}
let ids = 0;
/** A unique id for aria attributes. */
export function uid(prefix = 'f') {
ids += 1;
return `${prefix}-${ids}`;
}
/** Calls fn at most once per animation frame. */
export function perFrame(fn) {
let queued = false;
return (...args) => {
if (queued) return;
queued = true;
requestAnimationFrame(() => {
queued = false;
fn(...args);
});
};
}
/** Debounce. */
export function later(fn, ms) {
let timer = 0;
const wrapped = (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
wrapped.cancel = () => clearTimeout(timer);
return wrapped;
}
/** Saved per-viewer preferences (tile size, sort order). Never required: storage may be missing. */
export const local = {
get(key, fallback) {
try {
const v = localStorage.getItem(`febe.${key}`);
return v == null ? fallback : JSON.parse(v);
} catch {
return fallback;
}
},
set(key, value) {
try {
localStorage.setItem(`febe.${key}`, JSON.stringify(value));
} catch {
// private window or blocked storage: the preference lasts until the page closes
}
},
};
+102
View File
@@ -0,0 +1,102 @@
// The engine and the library as seen by the pages: one event stream (/api/eventi) for the whole interface.
// «motore» carries the snapshot (sidebar, stop strip, Attività); «libreria» says the library changed.
import { api, eventsUrl } from './api.js';
import { caps } from './context.js';
const engineListeners = new Set();
const libraryListeners = new Set();
let latest = null;
let source = null;
let poll = 0;
/** The latest engine state (EngineDto), or null before the first answer. */
export function engineState() {
return latest;
}
/** Calls fn now (if known) and at every change. Returns the function that stops listening. */
export function onEngine(fn) {
engineListeners.add(fn);
if (latest) fn(latest);
return () => engineListeners.delete(fn);
}
/** Calls fn at every library change ({ at, accountId, reason }). */
export function onLibrary(fn) {
libraryListeners.add(fn);
return () => libraryListeners.delete(fn);
}
function publish(state) {
latest = state;
for (const fn of [...engineListeners]) {
try {
fn(state);
} catch (error) {
console.error(error);
}
}
}
/** Asks the server for the engine now (after a command). */
export async function refreshEngine() {
try {
publish(await api('/api/engine'));
} catch {
// the stream will bring it
}
}
/** Opens the event stream; when it is not available, falls back to asking every 30 seconds. */
export function startEvents() {
refreshEngine();
// The demo engine is static: asking every 30 seconds is enough, and no connection stays open, so headless
// screenshots with --virtual-time-budget (spec §10.7) finish.
if (!('EventSource' in window) || caps().demo) {
poll = setInterval(refreshEngine, 30000);
return;
}
source = new EventSource(eventsUrl());
source.addEventListener('motore', (e) => {
try {
publish(JSON.parse(e.data));
} catch {
// malformed line: ignore
}
});
source.addEventListener('libreria', (e) => {
let change = {};
try {
change = JSON.parse(e.data);
} catch {
// keep the empty change
}
for (const fn of [...libraryListeners]) fn(change);
});
source.addEventListener('error', () => {
// EventSource reconnects by itself (retry: 3000); meanwhile ask once in a while.
if (!poll) poll = setInterval(() => (source.readyState === 1 ? (clearInterval(poll), (poll = 0)) : refreshEngine()), 15000);
});
}
/** Spia (dot) colour of an engine mode. */
export function dotOf(mode) {
switch (mode) {
case 'InSession':
case 'UserDriving':
return 'accento';
case 'Resting':
case 'Starting':
case 'OutsideWindow':
return 'verde';
case 'Throttled':
case 'NotConnected':
return 'ambra';
case 'StoppedForVerification':
case 'Disconnected':
return 'rosso';
default:
return '';
}
}
+335
View File
@@ -0,0 +1,335 @@
// The frame of every page (spec §10.2): fixed 228 px sidebar with brand, Libreria, Account, Attività, Importa,
// separator, Impostazioni, and the status box always visible at the bottom; on the right the page: title row,
// optional tools row, scrolling content, fixed bar for the actions that save. The red strip (mockup 11) appears under
// the title of every page while the engine is stopped and needs Alberto. Also the router of the addresses.
import { api, withCarried } from './api.js';
import { caps } from './context.js';
import { h, icon, brand, fill } from './dom.js';
import { dotOf, onEngine, onLibrary, refreshEngine, engineState } from './engine.js';
import { t } from './text.js';
import { avatar, showError, toast, closeMenu } from './ui.js';
import { routes } from '../routes.js';
const NAV = [
{ key: 'libreria', href: '/libreria', icon: 'layout-grid' },
{ key: 'account', href: '/account', icon: 'users' },
{ key: 'attivita', href: '/attivita', icon: 'activity' },
{ key: 'importa', href: '/importa', icon: 'folder-input' },
'stacco',
{ key: 'impostazioni', href: '/impostazioni', icon: 'settings' },
];
let main;
let navLinks = {};
let statusBox;
let current = null;
let renderToken = 0;
/** Builds the sidebar and the page area inside root. */
export function buildShell(root) {
const links = NAV.map((item) => {
if (item === 'stacco') return h('div.stacco', { role: 'separator' });
const a = h('a', { href: withCarried(item.href), dataset: { nav: item.key } }, icon(item.icon), h('span', t(`nav.${item.key}`)));
navLinks[item.key] = a;
return a;
});
statusBox = h('a.stato', { href: withCarried('/attivita'), 'aria-label': t('stato.riquadro') });
main = h('main.pagina', { id: 'contenuto', tabindex: '-1' });
fill(root,
h('a.salta', { href: '#contenuto' }, t('app.salta')),
h('div.app',
h('aside.barra',
h('a.marchio', { href: withCarried('/libreria') }, brand(), h('b', t('app.nome'))),
h('nav.nav', { 'aria-label': t('nav.principale') }, links),
h('div.molla'),
statusBox),
main));
onEngine(renderStatus);
renderStatus(null);
}
// ------------------------------------------------------------------------------------------------- status box
function renderStatus(state) {
if (!statusBox) return;
if (!state) {
fill(statusBox, h('div.riga', h('span.spia'), h('span', t('comune.caricamento'))));
return;
}
const s = state.snapshot;
const meter = s.profilesOpenedToday;
const connection = state.connection;
const who = connection.state === 'notConnected'
? h('div.chi', h('span.av.segnaposto', icon('user', 's')),
h('div', h('b', t('stato.nessunAccount')), h('span', t('stato.daCollegare'))))
: h('div.chi', avatar(connection.username || ''),
h('div', h('b', `@${connection.username}`), h('span', t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato'))));
const ratio = Math.max(0, Math.min(1, meter.ratio || 0));
fill(statusBox,
h('div.riga', h(`span.spia${dotOf(s.mode) ? '.' + dotOf(s.mode) : ''}`, { 'aria-hidden': 'true' }), h('span', s.headline)),
h('div.sotto', s.sidebarLine),
h(`div.misura${meter.amber ? '.ambra' : ''}`, { role: 'meter', 'aria-valuemin': '0', 'aria-valuemax': String(meter.limitToday), 'aria-valuenow': String(meter.usedToday), 'aria-label': t('stato.profiliOggi') },
h('i', { style: { width: `${ratio * 100}%` } })),
h('div.conto', h('span', t('stato.profiliOggi')), h('span', `${meter.usedText} ${meter.limitText}`)),
who);
statusBox.title = s.details && s.details.length ? s.details.join(' ') : s.headline;
const attention = navLinks.attivita;
if (attention) {
const dot = attention.querySelector('.punto');
if (s.banner && !dot) attention.append(h('span.punto', { role: 'img', 'aria-label': t('nav.fermo') }));
if (!s.banner && dot) dot.remove();
}
}
// ------------------------------------------------------------------------------------------------- page frame
/** What a page module receives to draw itself (see LEGGIMI.md). */
class PageFrame {
constructor(route) {
this.route = route;
this.controller = new AbortController();
this.cleanups = [];
this.guards = [];
this.backSlot = h('div', { hidden: true });
this.head = h('header.testa');
this.bannerSlot = h('div', { hidden: true });
this.tabsSlot = h('div', { hidden: true });
this.toolsSlot = h('div.strumenti', { hidden: true });
this.body = h('div.corpo');
this.saveSlot = h('div.salva', { hidden: true });
this.root = h('div', { style: { display: 'contents' } }, this.backSlot, this.head, this.bannerSlot, this.tabsSlot, this.toolsSlot, this.body, this.saveSlot);
}
/** Aborted when the page is left: pass it to fetch calls. */
get signal() {
return this.controller.signal;
}
/** Title row: «Libreria» with «48.212 elementi di 38 account» beside it. */
title(text, count = null) {
this.titleText = text;
document.title = t('app.titoloPagina', { pagina: text });
const h1 = h('h1', text);
this.countEl = count == null ? null : h('span.quanti', count);
this.actionsEl = h('div.destra');
fill(this.head, h1, this.countEl, this.actionsEl);
this.head.hidden = false;
return this;
}
/** Updates the text beside the title. */
count(text) {
if (this.countEl) this.countEl.textContent = text;
return this;
}
/** Buttons and fields at the right of the title row. */
actions(...nodes) {
if (!this.actionsEl) this.title(this.titleText || '');
fill(this.actionsEl, ...nodes);
return this;
}
/** Replaces the whole title row with a custom header (the account card); keeps the document title. */
header(node, documentTitle) {
if (documentTitle) document.title = t('app.titoloPagina', { pagina: documentTitle });
this.head.replaceWith(node);
this.head = node;
return this;
}
/** «← Account» above the title. */
back(text, href) {
this.backSlot.replaceWith(this.backSlot = h('a.indietro', { href: withCarried(href) }, icon('arrow-left', 's'), text));
return this;
}
/** A row of tabs (.linguette) under the header. */
tabs(node) {
this.tabsSlot.replaceWith(node);
this.tabsSlot = node;
return this;
}
/** The tools row (filters, menus); null hides it. */
tools(node) {
fill(this.toolsSlot, node);
this.toolsSlot.hidden = !node;
return this;
}
/** The fixed bar at the bottom (save, selection); null hides it. */
saveBar(node) {
fill(this.saveSlot, node);
this.saveSlot.hidden = !node;
return this;
}
/** Engine changes while the page is open. */
onEngine(fn) {
this.cleanups.push(onEngine(fn));
}
/** Library changes while the page is open. */
onLibrary(fn) {
this.cleanups.push(onLibrary(fn));
}
/** Runs fn when the page is left. */
onLeave(fn) {
this.cleanups.push(fn);
}
/** guard() → Promise<boolean>: asked before leaving (unsaved changes). */
guard(fn) {
this.guards.push(fn);
}
async mayLeave() {
for (const g of this.guards) {
if (!(await g())) return false;
}
return true;
}
destroy() {
this.controller.abort();
for (const fn of this.cleanups) {
try {
fn();
} catch (error) {
console.error(error);
}
}
}
}
function renderBanner(frame, state) {
const banner = state && state.snapshot.banner;
if (!banner) {
frame.bannerSlot.hidden = true;
frame.bannerSlot.replaceChildren();
return;
}
const isError = banner.level === 'Error';
const resume = h('button.btn', {
type: 'button',
disabled: !state.canResume,
title: state.canResume ? null : t('arresto.riprendiSpento'),
onclick: async () => {
try {
const result = await api('/api/engine/resume', { method: 'POST' });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
},
}, icon('rotate-cw'), t('arresto.riprendi'));
const open = h('button.btn.primo', { type: 'button', onclick: openBrowser }, icon('app-window'), t('arresto.apriBrowser'));
const box = h(`div.arresto${isError ? '' : '.ambra'}`, { role: 'alert' },
icon(isError ? 'octagon-alert' : 'triangle-alert', 'l'),
h('div.testo', h('b', banner.title), h('span', banner.message)),
h('div.azioni', banner.needsResume ? resume : null, isError ? open : null));
frame.bannerSlot.hidden = false;
fill(frame.bannerSlot, box);
}
/** «Apri il browser»: on Windows the window comes to the front; in Docker the Browser page with the remote view. */
export async function openBrowser() {
if (caps().browserWindow) {
try {
const result = await api('/api/browser/show', { method: 'POST' });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
} else {
navigate('/browser');
}
}
// ------------------------------------------------------------------------------------------------- router
/** Goes to an internal address (carried demo parameters kept). */
export async function navigate(path, { replace = false } = {}) {
if (current && !(await current.frame.mayLeave())) return;
const target = withCarried(path);
if (replace) history.replaceState(null, '', target);
else history.pushState(null, '', target);
await render();
}
/** Changes the query of the current address without reloading the page (filters, tabs). */
export function setQuery(params, { replace = true } = {}) {
const url = new URL(location.href);
for (const [key, value] of Object.entries(params)) {
if (value == null || value === '') url.searchParams.delete(key);
else url.searchParams.set(key, value);
}
const target = url.pathname + url.search + url.hash;
if (replace) history.replaceState(null, '', target);
else history.pushState(null, '', target);
}
/** Starts the router: link clicks, back and forward buttons. */
export function startRouter() {
document.addEventListener('click', (e) => {
const a = e.target.closest && e.target.closest('a[href]');
if (!a || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
if (a.target && a.target !== '_self') return;
if (a.hasAttribute('download')) return;
const url = new URL(a.href, location.href);
if (url.origin !== location.origin || url.pathname.startsWith('/api/') || /\.\w+$/.test(url.pathname)) return;
if (a.getAttribute('href').startsWith('#')) return;
e.preventDefault();
navigate(url.pathname + url.search);
});
window.addEventListener('popstate', () => render());
render();
}
async function render() {
closeMenu();
const token = ++renderToken;
const path = location.pathname;
const route = routes.find((r) => r.pattern.test(path));
if (route && route.redirect) {
history.replaceState(null, '', withCarried(route.redirect));
return render();
}
if (current) {
current.frame.destroy();
current = null;
}
for (const [key, link] of Object.entries(navLinks)) {
const here = route && route.nav === key;
link.classList.toggle('qui', here);
if (here) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
}
const match = route ? path.match(route.pattern) : null;
const params = { ...(route && route.data), ...(match && match.groups) };
const query = new URLSearchParams(location.search);
const frame = new PageFrame({ path, params, query });
fill(main, frame.root);
current = { frame };
frame.onEngine((state) => renderBanner(frame, state));
try {
const module = route ? await route.page() : await import('../pages/placeholder.js');
if (token !== renderToken) return;
const page = module.default;
const cleanup = await page.mount(frame, route ? { path, params, query } : { path, params: { key: 'nonTrovata' }, query });
if (typeof cleanup === 'function') frame.onLeave(cleanup);
} catch (error) {
if (error && error.name === 'AbortError') return;
console.error(error);
frame.title(t('comune.erroreTitolo'));
fill(frame.body, h('div.vuoto-pagina', icon('octagon-alert'), h('p', error && error.message ? error.message : t('comune.errore'))));
}
}
/** The engine state now (for pages that need it once). */
export { engineState };
+166
View File
@@ -0,0 +1,166 @@
// Texts and number/date formats. Every string the user reads comes from testi/<lingua>.json (spec §3: adding a
// language must not touch the code). Numbers use dot for thousands and comma for decimals (spec §10.4); future engine
// times are always «verso le».
let texts = {};
/** Loads the text resource (once, at start). */
export async function loadTexts(language = 'it') {
const response = await fetch(`/testi/${language}.json`, { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error('testi');
texts = await response.json();
}
function lookup(key) {
let node = texts;
for (const part of key.split('.')) {
if (node == null) return undefined;
node = node[part];
}
return node;
}
/**
* The text of a key. Values with «|» are «singular|plural» chosen by vars.n; {name} placeholders are filled from vars.
* A missing key shows the key itself, so a gap is visible instead of silently empty.
*/
export function t(key, vars) {
let value = lookup(key);
if (value == null) return key;
if (typeof value !== 'string') return value;
if (value.includes('|')) {
const [one, many] = value.split('|');
value = vars && Number(vars.n) === 1 ? one : many;
}
if (vars) {
value = value.replace(/\{(\w+)\}/g, (match, name) => {
if (!(name in vars)) return match;
const v = vars[name];
return typeof v === 'number' ? number(v) : String(v);
});
}
return value;
}
/** A list of texts (weekday and month names). */
export function list(key) {
const value = lookup(key);
return Array.isArray(value) ? value : [];
}
/** Whole number with dots for thousands: 48.212 (also for four digits: 1.284). */
export function number(value) {
const n = Math.round(Number(value) || 0);
const digits = Math.abs(n).toString();
let out = '';
for (let i = 0; i < digits.length; i++) {
if (i > 0 && (digits.length - i) % 3 === 0) out += '.';
out += digits[i];
}
return (n < 0 ? '-' : '') + out;
}
/** Decimal with a comma: 1,3. Trailing zeros dropped. */
export function decimal(value, decimals = 1) {
const factor = 10 ** decimals;
const rounded = Math.round(Number(value) * factor) / factor;
const whole = Math.trunc(rounded);
let fraction = Math.round(Math.abs(rounded - whole) * factor).toString().padStart(decimals, '0').replace(/0+$/, '');
const head = (rounded < 0 && whole === 0 ? '-' : '') + number(whole);
return fraction ? `${head},${fraction}` : head;
}
/** «412 kB», «1,3 GB». */
export function bytes(value) {
const b = Number(value) || 0;
const KB = 1024, MB = KB * 1024, GB = MB * 1024;
if (b >= GB) return t('unita.GB', { n: decimal(b / GB, 1) });
if (b >= MB) return t('unita.MB', { n: decimal(b / MB, b >= 100 * MB ? 0 : 1) });
if (b >= KB) return t('unita.kB', { n: number(b / KB) });
return t('unita.byte', { n: number(b) });
}
/** Video duration: «0:24», «1:02», «1:02:03». */
export function duration(seconds) {
const s = Math.max(0, Math.round(Number(seconds) || 0));
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60;
const ss = String(r).padStart(2, '0');
return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`;
}
/** Parses «2026-10-13» as a calendar day (no time zone involved). */
export function parseDay(day) {
const [y, m, d] = String(day).split('-').map(Number);
return { y, m, d, weekday: new Date(Date.UTC(y, m - 1, d)).getUTCDay(), number: Date.UTC(y, m - 1, d) / 86400000 };
}
/** «martedì 13 ottobre» (with the year when it is not the year of «today»). */
export function dayName(day, today) {
const p = parseDay(day);
const base = `${list('tempo.giorni')[p.weekday]} ${p.d} ${list('tempo.mesi')[p.m - 1]}`;
return today && parseDay(today).y !== p.y ? `${base} ${p.y}` : base;
}
/** «13 ottobre» (or «13 ottobre 2025» in another year). */
export function shortDay(day, today) {
const p = parseDay(day);
const base = `${p.d} ${list('tempo.mesi')[p.m - 1]}`;
return today && parseDay(today).y !== p.y ? `${base} ${p.y}` : base;
}
/** Days between two calendar days (b − a). */
export function daysBetween(a, b) {
return Math.round(parseDay(b).number - parseDay(a).number);
}
export function capitalize(text) {
return text ? text[0].toUpperCase() + text.slice(1) : text;
}
/** «verso le 16:10», «domani verso le 7:42», «giovedì verso le 7:42», «il 21 ottobre verso le 7:42». */
export function around(local) {
if (!local) return '';
const hour = Number(String(local.clock).split(':')[0]);
const time = t(hour === 1 ? 'tempo.versoUna' : 'tempo.verso', { ora: local.clock });
const prefix = dayPrefix(local);
return prefix ? `${prefix} ${time}` : time;
}
/** «alle 16:10», «ieri alle 7:42». */
export function at(local) {
if (!local) return '';
const hour = Number(String(local.clock).split(':')[0]);
const time = t(hour === 1 ? 'tempo.allUna' : 'tempo.alle', { ora: local.clock });
if (local.dayDelta === 0) return time;
if (local.dayDelta === -1) return `${t('tempo.ieri')} ${time}`;
const prefix = dayPrefix(local);
return prefix ? `${prefix} ${time}` : `${t('tempo.il', { giorno: shortDay(local.day) })} ${time}`;
}
function dayPrefix(local) {
const d = local.dayDelta;
if (d <= 0) return '';
if (d === 1) return t('tempo.domani');
if (d < 7) return list('tempo.giorni')[parseDay(local.day).weekday];
return t('tempo.il', { giorno: shortDay(local.day) });
}
/** «8 min fa», «1 ora fa», «ieri», «11 giorni fa» relative to the server's now (milliseconds). */
export function ago(ms, nowMs, today, day) {
const minutes = Math.max(0, Math.floor((nowMs - ms) / 60000));
if (minutes < 1) return t('tempo.adesso');
if (minutes < 60) return t('tempo.minutiFa', { n: minutes });
const hours = Math.floor(minutes / 60);
if (day && today) {
const days = daysBetween(day, today);
if (days === 1 && hours >= 6) return t('tempo.ieri');
if (days >= 2 && days < 14) return t('tempo.giorniFa', { n: days });
}
if (hours < 24) return t('tempo.oreFa', { n: hours });
const days = Math.floor(hours / 24);
if (days === 1) return t('tempo.ieri');
if (days < 14) return t('tempo.giorniFa', { n: days });
if (days < 60) return t('tempo.settimaneFa', { n: Math.floor(days / 7) });
if (days < 365) return t('tempo.mesiFa', { n: Math.floor(days / 30) });
return t('tempo.anniFa', { n: Math.floor(days / 365) });
}
+56
View File
@@ -0,0 +1,56 @@
// Light, dark or as the system (spec §10.5). The choice is stored on the server (Impostazioni, Generali) and kept in
// this browser too, so the page does not flash at start (js/tema.js applies it before the first paint).
// In the demo «?tema=chiaro|scuro» wins for the whole tab without changing the stored choice.
import { api, carriedValue } from './api.js';
const media = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
let choice = 'sistema';
function paint() {
const forced = carriedValue('tema');
const effective = forced === 'chiaro' || forced === 'scuro'
? forced
: choice === 'sistema' ? (media && media.matches ? 'scuro' : 'chiaro') : choice;
document.documentElement.setAttribute('data-tema', effective);
document.documentElement.setAttribute('data-scelta-tema', choice);
}
/** The stored choice: «chiaro», «scuro» or «sistema». */
export function themeChoice() {
return choice;
}
/** Applies a choice locally (no server call). */
export function applyTheme(value) {
choice = value === 'chiaro' || value === 'scuro' ? value : 'sistema';
try {
localStorage.setItem('febe.tema', choice);
} catch {
// storage blocked: the choice still applies to this page
}
paint();
}
/** At start: local choice first, then the server's. */
export async function initTheme() {
try {
choice = localStorage.getItem('febe.tema') || 'sistema';
} catch {
choice = 'sistema';
}
paint();
if (media && media.addEventListener) media.addEventListener('change', paint);
try {
const prefs = await api('/api/preferences');
if (prefs && prefs.theme && prefs.theme !== choice) applyTheme(prefs.theme);
} catch {
// keep the local choice
}
}
/** Stores a new choice on the server and applies it («Tema» in Impostazioni, Generali). */
export async function saveTheme(value) {
applyTheme(value);
await api('/api/preferences', { method: 'PUT', body: { theme: choice } });
}
+287
View File
@@ -0,0 +1,287 @@
// Components of the style sheet (appendix B, mockup 13) as functions: dialogs, menus, short notices, switches,
// check boxes, avatars. Keyboard first: every control is a real button or input, focus is always visible.
import { h, icon, uid } from './dom.js';
import { t } from './text.js';
// ------------------------------------------------------------------------------------------------- short notices
let toasts;
/** A short notice at the bottom («Impostazioni salvate.»); errors stay longer. */
export function toast(message, kind = '') {
if (!toasts) {
toasts = h('div.brevi', { role: 'status', 'aria-live': 'polite' });
document.body.append(toasts);
}
const item = h(`div.breve${kind ? '.' + kind : ''}`, kind === 'errore' ? icon('octagon-alert', 's') : icon('circle-check', 's'), h('span', message));
toasts.append(item);
setTimeout(() => item.remove(), kind === 'errore' ? 8000 : 4000);
}
/** Shows the message of an error (ApiError or anything else). */
export function showError(error) {
if (error && error.name === 'AbortError') return;
toast(error && error.message ? error.message : t('comune.errore'), 'errore');
}
// ------------------------------------------------------------------------------------------------- dialogs
const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
/**
* Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value)
* resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored.
*/
export function dialog({ title, className = '', build, labelledBy, dismissable = true }) {
return new Promise((resolve) => {
const opener = document.activeElement;
const titleId = labelledBy || uid('dlg');
let closed = false;
const close = (value) => {
if (closed) return;
closed = true;
veil.remove();
document.removeEventListener('keydown', onKey, true);
if (opener && opener.focus && document.contains(opener)) opener.focus();
resolve(value);
};
const parts = build(close);
const box = h(`div.dialogo${className ? '.' + className : ''}`, { role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId });
if (title) {
box.append(h('header', h('h2', { id: titleId }, title),
dismissable ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('comune.chiudi'), onclick: () => close(undefined) }, icon('x')) : null));
}
if (parts instanceof Node) box.append(parts);
else {
if (parts.body) box.append(parts.body);
if (parts.footer) box.append(parts.footer);
}
const veil = h('div.velo.finestra', box);
veil.addEventListener('mousedown', (e) => {
if (e.target === veil && dismissable) close(undefined);
});
const onKey = (e) => {
if (e.key === 'Escape' && dismissable) {
e.stopPropagation();
close(undefined);
} else if (e.key === 'Tab') {
const items = [...box.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null);
if (!items.length) return;
const first = items[0], last = items[items.length - 1];
if (e.shiftKey && document.activeElement === first) {
last.focus();
e.preventDefault();
} else if (!e.shiftKey && document.activeElement === last) {
first.focus();
e.preventDefault();
}
}
};
document.addEventListener('keydown', onKey, true);
document.body.append(veil);
const autofocus = box.querySelector('[autofocus]') || box.querySelector('.contenuto ' + FOCUSABLE) || box.querySelector(FOCUSABLE);
if (autofocus) autofocus.focus();
});
}
/**
* A confirmation with explicit buttons that say what happens (spec §10.4). Returns the value of the chosen button,
* or undefined when dismissed. buttons: [{ label, value, kind: 'primo'|'pericolo'|'' }].
*/
export function confirmDialog({ title, text, extra, buttons }) {
return dialog({
title,
className: 'piccolo',
build: (close) => ({
body: h('div.contenuto', text ? h('p', text) : null, extra || null),
footer: h('footer', h('div.destra',
buttons.map((b) => h(`button.btn${b.kind ? '.' + b.kind : ''}`, { type: 'button', onclick: () => close(b.value), autofocus: b.autofocus || null }, b.label)))),
}),
});
}
// ------------------------------------------------------------------------------------------------- menus
let openMenu = null;
/** Closes the open menu, if any. */
export function closeMenu() {
if (openMenu) openMenu();
}
/**
* Opens a menu under an anchor. items: [{ label, icon, value, checked, danger, disabled }] or nodes (a search field,
* a separator 'hr'). onPick(value) is called with the chosen value. Arrows move, Esc closes, focus returns to the anchor.
*/
export function menu(anchor, items, onPick, { role = 'menu', align = 'left', width } = {}) {
closeMenu();
const box = h('div.menu', { role, style: width ? { width: `${width}px` } : null });
const entries = [];
for (const item of items) {
if (item === 'hr') {
box.append(h('hr'));
continue;
}
if (item instanceof Node) {
box.append(item);
continue;
}
const itemRole = item.checked === undefined ? 'menuitem' : item.radio ? 'menuitemradio' : 'menuitemcheckbox';
const button = h(`button${item.danger ? '.pericolo' : ''}`, {
type: 'button', role: itemRole, disabled: item.disabled || null,
'aria-checked': item.checked === undefined ? null : String(Boolean(item.checked)),
onclick: () => {
if (!item.keepOpen) close();
onPick(item.value, button);
},
}, item.icon ? icon(item.icon, 's') : null, h('span', item.label), item.checked === undefined ? null : icon('check', 's segno'));
entries.push(button);
box.append(button);
}
document.body.append(box);
const rect = anchor.getBoundingClientRect();
const boxWidth = box.offsetWidth;
let left = align === 'right' ? rect.right - boxWidth : rect.left;
left = Math.max(8, Math.min(left, window.innerWidth - boxWidth - 8));
let top = rect.bottom + 6;
if (top + box.offsetHeight > window.innerHeight - 8) top = Math.max(8, rect.top - box.offsetHeight - 6);
box.style.left = `${left}px`;
box.style.top = `${top}px`;
anchor.setAttribute('aria-expanded', 'true');
const onDown = (e) => {
if (!box.contains(e.target) && !anchor.contains(e.target)) close();
};
const onKey = (e) => {
const focusables = [...box.querySelectorAll('button:not([disabled]),input')];
const index = focusables.indexOf(document.activeElement);
if (e.key === 'Escape') {
e.stopPropagation();
close();
anchor.focus();
} else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
const next = e.key === 'ArrowDown' ? index + 1 : index - 1;
const target = focusables[(next + focusables.length) % focusables.length];
if (target) target.focus();
} else if (e.key === 'Tab') {
close();
}
};
const onScroll = (e) => {
if (!box.contains(e.target)) close();
};
function close() {
if (!box.isConnected) return;
box.remove();
anchor.setAttribute('aria-expanded', 'false');
document.removeEventListener('mousedown', onDown, true);
document.removeEventListener('keydown', onKey, true);
document.removeEventListener('scroll', onScroll, true);
window.removeEventListener('resize', close);
if (openMenu === close) openMenu = null;
}
setTimeout(() => {
document.addEventListener('mousedown', onDown, true);
document.addEventListener('scroll', onScroll, true);
});
document.addEventListener('keydown', onKey, true);
window.addEventListener('resize', close);
openMenu = close;
const first = box.querySelector('input') || box.querySelector('[aria-checked=true]') || entries[0];
if (first) first.focus();
return { box, close };
}
// ------------------------------------------------------------------------------------------------- form controls
/** A switch («interruttore»): a real checkbox with role switch, styled as .int. */
export function toggle({ checked, label, hiddenLabel = false, disabled = false, onchange }) {
const input = h('input.vh', { type: 'checkbox', role: 'switch', checked, disabled, 'aria-label': hiddenLabel ? label : null });
if (onchange) input.addEventListener('change', () => onchange(input.checked, input));
const el = h('label.leva', input, h('span.int', { 'aria-hidden': 'true' }), hiddenLabel ? null : h('span', label));
el.input = input;
return el;
}
/** A check box («spunta»). */
export function checkbox({ checked, label, disabled = false, onchange, labelNode }) {
const input = h('input.vh', { type: 'checkbox', checked, disabled });
if (onchange) input.addEventListener('change', () => onchange(input.checked, input));
const el = h('label.voce', input, h('span.spunta', { 'aria-hidden': 'true' }, icon('check')), labelNode || (label ? h('span', label) : null));
el.input = input;
return el;
}
/** A radio button («tondo»). */
export function radio({ name, value, checked, label, labelNode, onchange }) {
const input = h('input.vh', { type: 'radio', name, value, checked });
if (onchange) input.addEventListener('change', () => input.checked && onchange(value, input));
const el = h('label.voce', input, h('span.tondo', { 'aria-hidden': 'true' }), labelNode || (label ? h('span', label) : null));
el.input = input;
return el;
}
/** A segmented control («gruppo»): [{ value, label, icon }]. */
export function segmented({ options, value, label, onchange }) {
const group = h('div.gruppo', { role: 'radiogroup', 'aria-label': label });
const buttons = options.map((o) => {
const b = h('button', {
type: 'button', role: 'radio', 'aria-checked': String(o.value === value), class: o.value === value ? 'qui' : null,
tabindex: o.value === value ? '0' : '-1',
onclick: () => select(o.value, true),
}, o.icon ? icon(o.icon, 's') : null, o.label);
b.dataset.value = o.value;
return b;
});
function select(v, notify) {
for (const b of buttons) {
const on = b.dataset.value === v;
b.classList.toggle('qui', on);
b.setAttribute('aria-checked', String(on));
b.tabIndex = on ? 0 : -1;
if (on && notify) b.focus();
}
if (notify && onchange) onchange(v);
}
group.addEventListener('keydown', (e) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
const index = buttons.findIndex((b) => b.classList.contains('qui'));
const next = buttons[(index + (e.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length];
select(next.dataset.value, true);
e.preventDefault();
});
group.append(...buttons);
group.select = (v) => select(v, false);
return group;
}
// ------------------------------------------------------------------------------------------------- avatars and labels
const AVATAR_COLORS = ['#2F6B45', '#2E5E78', '#7A5426', '#8A2E4B', '#5A4699', '#3D6B1F', '#7B3F8C', '#1F6670', '#8C4A2F', '#4B5A8C'];
/** «MD» for marta.demo, «LV» for luca.viaggi.demo, «E2» for estate.2019.demo. */
export function initials(username) {
const parts = String(username || '?').replace(/^@/, '').split(/[._]/).filter(Boolean);
if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
return (parts[0] || '?').slice(0, 2).toUpperCase();
}
function colorOf(username) {
let hash = 0;
for (const c of String(username)) hash = (hash * 31 + c.charCodeAt(0)) >>> 0;
return AVATAR_COLORS[hash % AVATAR_COLORS.length];
}
/** An avatar: the latest profile picture when there is one, otherwise initials on a colour from the name. */
export function avatar(username, size = '', thumb = null) {
const el = h(`span.av${size ? '.' + size : ''}`, { 'aria-hidden': 'true', style: { background: colorOf(username) } });
if (thumb) el.append(h('img', { src: `/api/thumbnails/${thumb}`, alt: '', loading: 'lazy' }));
else el.textContent = initials(username);
return el;
}
/** A label («etichetta»): et(text, 'accento', 'lock'). */
export function label(text, kind = '', iconName = null) {
return h(`span.et${kind ? '.' + kind : ''}`, iconName ? icon(iconName) : null, text);
}
+523
View File
@@ -0,0 +1,523 @@
// Scheda account (mockups 05 and 12, spec §4.4, §4.6): header with avatar, name, labels, counts, «Controlla ora» and
// the link to the profile; tabs Contenuti (Post, Storie as a regular 9:16 grid, In evidenza grouped by collection,
// Taggati, Profilo when there is more than one picture), Impostazioni (with «Con queste impostazioni» recomputed at
// every change and the fixed save bar) and Cronologia (the checks with their outcome).
import { api, download, withCarried } from '../core/api.js';
import { caps, serverNow } from '../core/context.js';
import { h, icon, fill, later, local } from '../core/dom.js';
import { refreshEngine } from '../core/engine.js';
import { navigate, setQuery } from '../core/shell.js';
import { t, number, decimal, dayName, shortDay, capitalize } from '../core/text.js';
import { avatar, checkbox, confirmDialog, menu, segmented, showError, toast, toggle } from '../core/ui.js';
import { accountLabels, accountMenu, checkNow, openProfile } from './accounts.js';
import { confirmDelete } from './library.js';
import { Mosaic, justify, tileElement, defaultDayLabel } from './mosaic.js';
import { openViewer } from './viewer.js';
const KINDS = [
{ key: 'post', api: 'posts', stat: 'posts', label: 'scheda.tipi.posts' },
{ key: 'storie', api: 'stories', stat: 'stories', label: 'scheda.tipi.stories', grid: true },
{ key: 'evidenza', api: 'highlights', stat: 'highlightItems', label: 'scheda.tipi.highlights' },
{ key: 'taggati', api: 'tagged', stat: 'tagged', label: 'scheda.tipi.tagged' },
{ key: 'profilo', api: 'profile', stat: 'profilePictures', label: 'scheda.tipi.profile' },
];
const TYPE_FIELDS = [
{ key: 'photos', icon: 'image' },
{ key: 'videos', icon: 'clapperboard' },
{ key: 'stories', icon: 'circle-dashed' },
{ key: 'highlights', icon: 'star' },
{ key: 'tagged', icon: 'square-user' },
{ key: 'profilePicture', icon: 'circle-user' },
];
const PLAN_ICONS = { posts: 'clock', stories: 'circle-dashed', backfill: 'history', load: 'gauge', checks: 'info' };
export default {
async mount(page, route) {
const id = Number(route.params.id);
const tab = route.params.tab || 'contenuti';
let detail;
try {
detail = await api(`/api/accounts/${id}`, { signal: page.signal });
} catch (error) {
if (error.name === 'AbortError') return;
page.back(t('scheda.indietro'), '/account');
page.title(t('scheda.nonTrovato'));
fill(page.body, h('div.vuoto-pagina', icon('users'), h('h2', t('scheda.nonTrovato')), h('p', error.message || t('scheda.nonTrovatoTesto'))));
return;
}
page.back(t('scheda.indietro'), '/account');
const header = h('header.scheda-testa');
page.header(header, `@${detail.account.username}`);
drawHeader(header, detail, async () => {
detail = await api(`/api/accounts/${id}`, { signal: page.signal });
drawHeader(header, detail);
});
const base = `/account/${id}`;
page.tabs(h('nav.linguette', { 'aria-label': `@${detail.account.username}` },
h(`a${tab === 'contenuti' ? '.qui' : ''}`, { href: withCarried(base), 'aria-current': tab === 'contenuti' ? 'page' : null },
t('scheda.linguette.contenuti'), h('i', number(detail.stats.entries))),
h(`a${tab === 'impostazioni' ? '.qui' : ''}`, { href: withCarried(`${base}/impostazioni`), 'aria-current': tab === 'impostazioni' ? 'page' : null }, t('scheda.linguette.impostazioni')),
h(`a${tab === 'cronologia' ? '.qui' : ''}`, { href: withCarried(`${base}/cronologia`), 'aria-current': tab === 'cronologia' ? 'page' : null }, t('scheda.linguette.cronologia'))));
if (tab === 'impostazioni') return settingsTab(page, detail);
if (tab === 'cronologia') return historyTab(page, detail);
return contentsTab(page, route, detail);
},
};
// --------------------------------------------------------------------------------------------- header
function drawHeader(header, detail, reload) {
const a = detail.account;
const s = detail.stats;
const postsBlock = a.state === 'backfilling' && a.postCount
? h('div', h('b', t('scheda.numeri.postDi', { fatti: number(a.posts), totale: number(a.postCount) })), h('span', t('scheda.numeri.postScaricati')))
: h('div', h('b', number(s.posts)), h('span', t('scheda.numeri.post')));
const check = h('button.btn', { type: 'button', disabled: a.state === 'archiveOnly', onclick: () => checkNow(a) }, icon('refresh-cw'), t('account.menu.controlla'));
const link = detail.instagramUrl
? h('button.btn.solo', { type: 'button', title: t('scheda.apriProfilo'), 'aria-label': t('scheda.apriProfilo'), onclick: () => openProfile(a) }, icon('external-link'))
: null;
const more = h('button.btn.solo', { type: 'button', 'aria-label': t('comune.menu'), 'aria-haspopup': 'true' }, icon('ellipsis'));
more.addEventListener('click', () => accountMenu(more, a, (outcome) => {
if (outcome === 'removed') navigate('/account');
else if (reload) reload().catch(showError);
}));
fill(header,
avatar(a.username, 'g', a.avatar),
h('div.nomi', h('h1', `@${a.username}`), h('div.sotto', a.isMine ? t('account.sotto.tuo') : a.displayName, accountLabels(a))),
h('div.numeri',
h('div', h('b', number(s.entries)), h('span', t('scheda.numeri.elementi'))),
postsBlock,
h('div', h('b', number(s.stories)), h('span', t('scheda.numeri.storie'))),
h('div', h('b', number(s.collections)), h('span', t('scheda.numeri.raccolte')))),
h('div.azioni', check, link, more));
}
// --------------------------------------------------------------------------------------------- contents
async function contentsTab(page, route, detail) {
const s = detail.stats;
const available = KINDS.filter((k) => k.key !== 'profilo' || s.profilePictures > 1);
let kind = available.find((k) => k.key === route.query.get('tipo')) || available.find((k) => s[k.stat] > 0) || available[0];
let period = route.query.get('periodo') || '';
let mosaic = null;
const chips = h('div.filtri', { role: 'group', 'aria-label': t('scheda.linguette.contenuti') });
const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '150px' } });
const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, h('div.destra', selectButton)));
const host = h('div');
fill(page.body, host);
function drawTools() {
fill(chips, available.map((k) => h(`button${k === kind ? '.qui' : ''}`, {
type: 'button', 'aria-pressed': String(k === kind),
onclick: () => {
kind = k;
setQuery({ tipo: k.key });
show();
},
}, t(k.label), h('i', number(s[k.stat])))));
fill(periodButton, h('span.val', period ? t(`libreria.periodi.${period}`) : t('libreria.periodi.qualsiasi')), icon('chevron-down', 's'));
selectButton.hidden = kind.key === 'evidenza';
}
periodButton.addEventListener('click', () => menu(periodButton,
['', 'settimana', 'mese', 'anno', 'annoScorso'].map((p) => ({ label: t(p ? `libreria.periodi.${p}` : 'libreria.periodi.qualsiasi'), value: p, checked: p === period, radio: true })),
(value) => {
period = value;
setQuery({ periodo: value || null });
show();
}));
function query() {
const q = new URLSearchParams({ accounts: String(detail.account.id), kind: kind.api });
const today = caps().today;
const add = (n) => new Date(Date.parse(`${today}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10);
const year = Number(today.slice(0, 4));
const range = { settimana: [add(-6), today], mese: [add(-29), today], anno: [`${year}-01-01`, today], annoScorso: [`${year - 1}-01-01`, `${year - 1}-12-31`] }[period];
if (range) {
q.set('from', range[0]);
q.set('to', range[1]);
}
return q.toString();
}
function drawSelection(selected) {
if (!mosaic || !mosaic.selecting) {
page.saveBar(null);
return;
}
const n = selected.size;
page.saveBar(h('div', { style: { display: 'contents' } },
h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')),
h('div.destra',
h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')),
h('button.btn', { type: 'button', disabled: !n, onclick: async () => {
try {
await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv');
toast(t('selezione.esportato'));
} catch (error) {
showError(error);
}
} }, icon('file-down'), t('selezione.esporta')),
h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: async () => {
const removed = await confirmDelete([...mosaic.selected]);
if (removed) {
mosaic.removeTiles(removed);
setSelecting(false);
}
} }, icon('trash-2'), t('selezione.elimina', { n })))));
}
function setSelecting(on) {
if (!mosaic) return;
mosaic.setSelecting(on);
fill(selectButton, icon(on ? 'check' : 'circle-check'), h('span', t(on ? 'libreria.fine' : 'libreria.seleziona')));
selectButton.setAttribute('aria-pressed', String(on));
drawSelection(mosaic.selected);
}
selectButton.addEventListener('click', () => mosaic && setSelecting(!mosaic.selecting));
async function show() {
drawTools();
if (mosaic) mosaic.destroy();
mosaic = null;
page.saveBar(null);
page.body.scrollTop = 0;
if (kind.key === 'evidenza') {
await showHighlights(host, detail, page);
return;
}
const rowHeight = local.get('libreria.tessere', 160);
mosaic = new Mosaic({
scroller: page.body,
host,
query: query(),
mode: kind.grid ? 'grid' : 'justified',
rowHeight,
signal: page.signal,
dayLabel: kind.grid ? storiesDayLabel : defaultDayLabel,
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: `@${detail.account.username}`, onDeleted: (ids) => mosaic.removeTiles(ids) }),
onSelection: drawSelection,
onEmpty: () => fill(host, h('div.vuoto-pagina', icon(kind.grid ? 'circle-dashed' : 'image'), h('p', t('scheda.nessunContenuto')))),
});
try {
await mosaic.start();
} catch (error) {
showError(error);
}
}
const onChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 500);
page.onLibrary((change) => {
if (!change.accountId || change.accountId === detail.account.id) onChange();
});
page.onLeave(() => {
onChange.cancel();
if (mosaic) mosaic.destroy();
});
await show();
}
/** Day header of the stories: «Oggi martedì 13 ottobre, 2 storie», «Sabato 10 ottobre 9 storie». */
function storiesDayLabel(day, count, today) {
const [bold] = defaultDayLabel(day, count, today);
const name = dayName(day, today);
const n = t('libreria.storieGiorno', { n: count });
if (bold === t('tempo.Oggi') || bold === t('tempo.Ieri')) return [bold, `${name}, ${n}`];
return [capitalize(name), n];
}
/** «In evidenza»: the mosaic grouped under the titles of the collections (mockup 12). */
async function showHighlights(host, detail, page) {
const collections = detail.highlights.filter((c) => c.count > 0);
if (!collections.length) {
fill(host, h('div.vuoto-pagina', icon('star'), h('p', t('scheda.nessunContenuto'))));
return;
}
fill(host, h('div.caricamento', t('comune.caricamento')));
const ids = [...new Set(collections.flatMap((c) => c.entryIds))];
const tiles = new Map();
for (let i = 0; i < ids.length; i += 1000) {
const page2 = await api(`/api/library/tiles?ids=${ids.slice(i, i + 1000).join(',')}`, { signal: page.signal });
for (const tile of page2.tiles) tiles.set(tile.id, tile);
}
const flat = [];
const groups = collections.map((c) => {
const list = c.entryIds.map((x) => tiles.get(x)).filter(Boolean);
flat.push(...list);
return { c, list };
});
const source = {
position: (entryId) => ({ index: flat.findIndex((x) => x.id === entryId) + 1, total: flat.length }),
neighbor: async (entryId, delta) => flat[flat.findIndex((x) => x.id === entryId) + delta] || null,
reveal: () => {},
};
const draw = () => {
const width = host.clientWidth || 800;
const rowHeight = local.get('libreria.tessere', 160);
fill(host, groups.map(({ c, list }) => h('section',
h('div.raccolta-titolo', h('b', c.title), h('span', [t('comune.contenuti', { n: list.length }), c.removed ? ` · ${t('scheda.raccoltaTolta')}` : ''].join(''))),
justify(list, width, rowHeight).map((row) => h('div.fila', row.items.map((item) => tileElement(item.tile, item.width, row.height, { today: caps().today })))))));
};
draw();
host.onclick = (e) => {
const el = e.target.closest('.tess[data-id]');
if (!el) return;
const tile = flat.find((x) => x.id === Number(el.dataset.id));
if (tile) openViewer({ tile, source, origin: `@${detail.account.username}`, onDeleted: () => draw() });
};
const observer = new ResizeObserver(later(draw, 150));
observer.observe(host);
page.onLeave(() => observer.disconnect());
}
// --------------------------------------------------------------------------------------------- settings
function settingsTab(page, detail) {
page.body.style.paddingTop = '16px';
const c = caps();
const original = JSON.stringify(detail.settings);
let form = JSON.parse(original);
let plan = detail.plan;
const account = detail.account;
const planBox = h('div.piano', { 'aria-live': 'polite' });
const left = h('div.colonna');
fill(page.body, h('div.imp-account', left, planBox));
const dirty = () => JSON.stringify(form) !== original;
const recompute = later(async () => {
try {
plan = await api(`/api/accounts/${account.id}/plan`, { method: 'POST', body: form, signal: page.signal });
drawPlan();
frequencyNote.textContent = plan.frequencyHint;
} catch (error) {
if (error.name !== 'AbortError' && error.status === 400) planBox.prepend(h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message)));
}
}, 200);
function changed() {
drawSaveBar();
recompute();
}
// Tieni aggiornato.
const keep = toggle({ checked: form.keepUpdated, label: t('impAccount.tieni'), onchange: (v) => { form.keepUpdated = v; changed(); } });
keep.querySelector('span:last-child').style.fontWeight = '650';
// Frequenza.
const frequencyNote = h('span.nota', plan.frequencyHint);
const customFields = h('div.riga-campi');
const postHours = h('input', { type: 'number', min: '1', max: '48', step: '0.5', value: form.customPostHours ?? '', inputmode: 'decimal', id: 'ore-post' });
const storyHours = h('input', { type: 'number', min: '1', max: '24', step: '0.5', value: form.customStoryHours ?? '', inputmode: 'decimal', id: 'ore-storie' });
postHours.addEventListener('input', () => { form.customPostHours = postHours.value === '' ? null : Number(postHours.value); changed(); });
storyHours.addEventListener('input', () => { form.customStoryHours = storyHours.value === '' ? null : Number(storyHours.value); changed(); });
fill(customFields,
h('div', h('label.etichetta', { for: 'ore-post' }, t('impAccount.suMisuraPost')), h('label.campo', postHours, h('span.unita', t('impAccount.ore')))),
h('div', h('label.etichetta', { for: 'ore-storie' }, t('impAccount.suMisuraStorie')), h('label.campo', storyHours, h('span.unita', t('impAccount.ore')))));
customFields.hidden = form.frequency !== 'custom';
const frequency = segmented({
label: t('impAccount.frequenza'),
value: form.frequency,
options: ['low', 'normal', 'high', 'custom'].map((f) => ({ value: f, label: t(`impAccount.frequenze.${f}`) })),
onchange: (v) => {
form.frequency = v;
customFields.hidden = v !== 'custom';
changed();
},
});
// Cosa scaricare.
const types = h('div.tipi', TYPE_FIELDS.map((f) => {
const box = checkbox({ checked: form.types[f.key], labelNode: h('span.testo', t(`impAccount.tipi.${f.key}`)), onchange: (v) => { form.types[f.key] = v; changed(); } });
box.classList.add('tipo');
box.append(icon(f.icon, 's'));
return box;
}));
// Limiti.
const depth = h('select', { id: 'profondita' }, ['all', 'lastPosts', 'fromDate'].map((d) => h('option', { value: d, selected: form.depth === d }, t(`impAccount.profondita.${d}`))));
const lastPosts = h('input', { type: 'number', min: '1', step: '1', value: form.lastPosts ?? 100, id: 'ultimi', inputmode: 'numeric' });
const fromDate = h('input', { type: 'date', value: form.fromDate ?? caps().today, id: 'dal', max: caps().today });
const depthExtra = h('div');
function drawDepthExtra() {
if (form.depth === 'lastPosts') {
if (form.lastPosts == null) form.lastPosts = Number(lastPosts.value) || 100;
fill(depthExtra, h('label.etichetta', { for: 'ultimi' }, t('impAccount.quantiPost')), h('label.campo', lastPosts, h('span.unita', t('impAccount.post'))));
} else if (form.depth === 'fromDate') {
if (!form.fromDate) form.fromDate = fromDate.value;
fill(depthExtra, h('label.etichetta', { for: 'dal' }, t('impAccount.dalGiorno')), h('label.campo', fromDate));
} else depthExtra.replaceChildren();
depthExtra.hidden = form.depth === 'all';
}
depth.addEventListener('change', () => { form.depth = depth.value; drawDepthExtra(); changed(); });
lastPosts.addEventListener('input', () => { form.lastPosts = lastPosts.value === '' ? null : Number(lastPosts.value); changed(); });
fromDate.addEventListener('input', () => { form.fromDate = fromDate.value || null; changed(); });
const perDay = h('input', { type: 'number', min: '1', max: String(detail.maxBackfillPerDay), step: '1', value: form.backfillPerDay, id: 'al-giorno', inputmode: 'numeric' });
perDay.addEventListener('input', () => { form.backfillPerDay = Number(perDay.value) || 0; changed(); });
const maxVideo = h('input', { type: 'number', min: '1', step: '1', value: form.maxVideoMb ?? '', placeholder: t('impAccount.nessunLimite'), id: 'video-oltre', inputmode: 'decimal' });
maxVideo.addEventListener('input', () => { form.maxVideoMb = maxVideo.value === '' ? null : Number(maxVideo.value); changed(); });
const storyVideos = toggle({ checked: form.storyVideos, label: t('impAccount.videoStorie'), onchange: (v) => { form.storyVideos = v; changed(); } });
drawDepthExtra();
// Cartella.
const folderValue = h('span.val', detail.folder);
const folderActions = h('div', { style: { display: 'contents' } });
function drawFolder(path) {
folderValue.textContent = path;
const items = [];
if (!c.foldersReadOnly && c.pickFolder) {
items.push(h('button.btn', { type: 'button', onclick: pickFolder }, t('impAccount.cambia')));
if (form.folder) items.push(h('button.btn.nudo', { type: 'button', onclick: () => { form.folder = null; drawFolder(t('impAccount.predefinita')); changed(); } }, t('impAccount.predefinita')));
}
fill(folderActions, items);
}
async function pickFolder() {
try {
const result = await api(`/api/accounts/${account.id}/pick-folder`, { method: 'POST' });
if (result.message) {
form.folder = result.message;
drawFolder(result.message);
changed();
}
} catch (error) {
showError(error);
}
}
drawFolder(detail.folder);
fill(left,
account.state === 'archiveOnly' ? h('div.avviso', { style: { marginBottom: '12px' } }, icon('archive', 's'), h('span', t('impAccount.archivio'))) : null,
h('div.sezione', keep, h('p.aiuto', { style: { margin: '6px 0 0 46px' } }, t('impAccount.tieniAiuto'))),
h('div.sezione', h('h2.sez', t('impAccount.frequenza')), h('div.frequenza', frequency, frequencyNote), customFields),
h('div.sezione', h('h2.sez', t('impAccount.cosa')), h('p.aiuto', t('impAccount.cosaAiuto')), types),
h('div.sezione', h('h2.sez', t('impAccount.limiti')), h('p.aiuto', t('impAccount.limitiAiuto')),
h('div.riga-campi',
h('div', h('label.etichetta', { for: 'profondita' }, t('impAccount.quanto')), h('label.campo.scelta', depth, icon('chevron-down', 's'))),
h('div', h('label.etichetta', { for: 'al-giorno' }, t('impAccount.storicoGiorno')), h('label.campo', perDay, h('span.unita', t('impAccount.post')))),
h('div', h('label.etichetta', { for: 'video-oltre' }, t('impAccount.saltaVideo')), h('label.campo', maxVideo, h('span.unita', t('impAccount.mb'))))),
h('div.riga-campi', depthExtra),
h('div', { style: { marginTop: '14px' } }, storyVideos)),
h('div.sezione', h('h2.sez', t('impAccount.cartella')), h('p.aiuto', t(c.foldersReadOnly ? 'impAccount.cartellaDocker' : 'impAccount.cartellaAiuto')),
h('div.cartella', h('div.campo.sola', icon('folder', 's'), folderValue), folderActions)));
function drawPlan() {
const lines = plan.lines.map((l) => {
const body = h('div', h('b', l.title), ' ', l.text);
if (l.key === 'load') {
const ratio = Math.min(1, plan.share || 0);
body.append(h('div.misura', { role: 'meter', 'aria-valuemin': '0', 'aria-valuemax': String(plan.dailyBudget), 'aria-valuenow': String(Math.round(plan.opensPerDay)), 'aria-label': l.title },
h('i', { style: { width: `${Math.max(2, ratio * 100)}%` } })),
h('small', t('impAccount.caricoMisura', { usati: decimal(plan.opensPerDay, plan.opensPerDay < 10 ? 1 : 0), totale: number(plan.dailyBudget) })));
body.classList.add('carico');
}
return h('div.voce-piano', icon(PLAN_ICONS[l.key] || 'info', 's'), body);
});
fill(planBox,
h('div.pannello', h('h2', t('impAccount.piano')), lines),
plan.warnings.map((w) => h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', w))),
plan.note ? h('div.avviso', icon('info', 's'), h('span', plan.note)) : null);
}
drawPlan();
function drawSaveBar() {
if (!dirty()) {
page.saveBar(null);
return;
}
page.saveBar(h('div', { style: { display: 'contents' } },
h('span.nota', t('impAccount.modifiche')),
h('div.destra',
h('button.btn', { type: 'button', onclick: () => { leaveAllowed = true; navigate(location.pathname + location.search, { replace: true }); } }, t('impAccount.annulla')),
h('button.btn.primo', { type: 'button', onclick: save }, icon('check'), t('impAccount.salva')))));
}
async function save() {
try {
const updated = await api(`/api/accounts/${account.id}/settings`, { method: 'PUT', body: form });
toast(t('impAccount.salvate', { nome: account.username }));
leaveAllowed = true;
refreshEngine();
navigate(location.pathname + location.search, { replace: true });
void updated;
} catch (error) {
showError(error);
}
}
let leaveAllowed = false;
page.guard(async () => {
if (leaveAllowed || !dirty()) return true;
const choice = await confirmDialog({
title: t('impAccount.modifiche'),
text: t('impAccount.esci'),
buttons: [
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
{ label: t('impAccount.lascia'), value: true, kind: 'pericolo' },
],
});
if (choice) leaveAllowed = true;
return Boolean(choice);
});
const beforeUnload = (e) => {
if (dirty() && !leaveAllowed) {
e.preventDefault();
e.returnValue = '';
}
};
window.addEventListener('beforeunload', beforeUnload);
page.onLeave(() => {
recompute.cancel();
window.removeEventListener('beforeunload', beforeUnload);
});
}
// --------------------------------------------------------------------------------------------- history
async function historyTab(page, detail) {
page.body.style.paddingTop = '16px';
const tbody = h('tbody');
const more = h('button.btn', { type: 'button', hidden: true }, t('cronologia.altri'));
fill(page.body, h('div.cronologia',
h('div.pannello', h('table.tab', h('caption.vh', t('cronologia.titolo')), tbody)),
h('div', { style: { marginTop: '14px' } }, more)));
let before = null;
const today = caps().today;
function when(local) {
if (local.dayDelta === 0) return `${t('tempo.oggi')}, ${local.clock}`;
if (local.dayDelta === -1) return `${t('tempo.ieri')}, ${local.clock}`;
return `${shortDay(local.day, today)}, ${local.clock}`;
}
async function load() {
try {
const data = await api(`/api/accounts/${detail.account.id}/history${before ? `?before=${before}` : ''}`, { signal: page.signal });
if (!data.items.length && !before) {
fill(page.body, h('div.vuoto-pagina', icon('history'), h('p', t('cronologia.vuota'))));
return;
}
for (const item of data.items) {
const split = item.message.indexOf(': ');
const text = split > 0 ? item.message.slice(split + 2) : item.message;
const code = item.code.startsWith('ricetta.') ? item.code.slice('ricetta.'.length) : item.code === 'account.pausa' ? 'pausa' : 'altro';
const kindLabel = t(`cronologia.ricette.${code}`) === `cronologia.ricette.${code}` ? t('cronologia.ricette.altro') : t(`cronologia.ricette.${code}`);
const outcome = { success: ['verde', 'circle-check'], warning: ['ambra', 'triangle-alert'], error: ['rosso', 'octagon-alert'], info: ['', 'check'] }[item.severity] || ['', 'check'];
tbody.append(h('tr',
h('td.quando-cella.dati', when(item.at)),
h('td', h('b', { style: { fontWeight: '600' } }, kindLabel), h('div.muto', { style: { fontSize: '13px' } }, capitalize(text))),
h('td', { style: { textAlign: 'right' } }, h(`span.et${outcome[0] ? '.' + outcome[0] : ''}`, icon(outcome[1]), t(`cronologia.esiti.${item.severity}`)))));
}
before = data.before;
more.hidden = !before;
} catch (error) {
showError(error);
}
}
more.addEventListener('click', load);
await load();
void serverNow;
}
+341
View File
@@ -0,0 +1,341 @@
// Account (mockup 03, spec §4.2): table with avatar, name and labels, the five «Raccoglie» icons, state with its
// second line and the history progress, last and next check, entries in the library, «Tieni aggiornato» acting at
// once, the row menu; filter chips with counts, search, sort, «Aggiungi account». A click on a row opens the card.
import { api, withCarried } from '../core/api.js';
import { caps, serverNow } from '../core/context.js';
import { h, icon, fill, later, local } from '../core/dom.js';
import { refreshEngine, engineState } from '../core/engine.js';
import { navigate, setQuery } from '../core/shell.js';
import { t, number, ago, around, shortDay } from '../core/text.js';
import { avatar, label, menu, toggle, toast, showError, confirmDialog, dialog, radio } from '../core/ui.js';
import { openAddAccounts } from './add-accounts.js';
const FILTERS = ['tutti', 'upToDate', 'backfilling', 'paused', 'archiveOnly', 'needsAttention'];
const SORTS = ['ultimo', 'prossimo', 'nome', 'libreria', 'aggiunta'];
const TYPES = [
{ key: 'photos', icon: 'image' },
{ key: 'videos', icon: 'clapperboard' },
{ key: 'stories', icon: 'circle-dashed' },
{ key: 'highlights', icon: 'star' },
{ key: 'tagged', icon: 'square-user' },
];
/** Labels under the name: «Tu», «Privato», «Pubblico», «Seguito», «Non seguito», «Solo archivio». */
export function accountLabels(a) {
if (a.isMine) return [label(t('account.etichette.tu'), 'accento')];
if (a.state === 'archiveOnly') return [label(t('account.etichette.archivio'))];
return [
a.isPrivate ? label(t('account.etichette.privato'), '', 'lock') : label(t('account.etichette.pubblico')),
a.isFollowed ? label(t('account.etichette.seguito')) : label(t('account.etichette.nonSeguito')),
];
}
/** True while the engine does not work (stopped, paused, not connected): «Prossimo» says «Sospeso». */
function suspended() {
const state = engineState();
return Boolean(state && ['StoppedForVerification', 'Disconnected', 'NotConnected', 'Paused', 'Throttled', 'Off'].includes(state.snapshot.mode));
}
/** Dot colour of an account state. */
export function stateDot(state) {
return { upToDate: 'verde', backfilling: 'accento', unreachable: 'ambra' }[state] || '';
}
/** The second line of the state: news of today, history progress, why paused or unreachable. */
export function stateLine(a) {
switch (a.state) {
case 'backfilling': {
const text = a.postCount ? t('account.sotto.storico', { fatti: number(a.posts), totale: number(a.postCount) }) : t('account.sotto.storicoSenzaTotale', { fatti: number(a.posts) });
return a.backfillResumesTomorrow ? t('account.sotto.riprendeDomani', { testo: text }) : text;
}
case 'paused':
return a.stateChanged ? t('account.sotto.pausa', { giorno: shortDay(a.stateChanged.day, caps().today) }) : t('account.sotto.pausaSenzaData');
case 'unreachable':
return t(`account.sotto.${a.unreachableReason || 'privateNotFollowed'}`);
case 'archiveOnly':
return t('account.sotto.maiContattato');
default: {
if (a.notices.includes('renamed') && a.previousUsername) return t('account.sotto.rinominato', { nome: a.previousUsername });
if (a.notices.includes('unrecognizedFormat')) return t('account.sotto.formato');
if (a.newPostsToday && a.newStoriesToday) {
return t('account.sotto.nuoviEntrambi', { post: t('account.sotto.post', { n: a.newPostsToday }), storie: t('account.sotto.storie', { n: a.newStoriesToday }) });
}
if (a.newPostsToday) return t('account.sotto.nuoviPost', { n: a.newPostsToday });
if (a.newStoriesToday) return t('account.sotto.nuoveStorie', { n: a.newStoriesToday });
return '';
}
}
}
/** «Controlla ora» (spec §7.8): outside the active window Febe asks for a confirmation and then does that one check. */
export async function checkNow(account, token = null) {
try {
const result = await api(`/api/accounts/${account.id}/check-now`, { method: 'POST', body: token ? { token } : {} });
if (result.status === 'needsConfirmation') {
const ok = await confirmDialog({
title: t('account.controlla.titolo'),
text: result.message,
buttons: [
{ label: t('comune.annulla'), value: false, kind: 'nudo' },
{ label: t('account.controlla.conferma', { nome: account.username }), value: true, kind: 'primo', autofocus: true },
],
});
if (ok) await checkNow(account, result.token);
return;
}
toast(result.message, result.status === 'refused' ? 'errore' : '');
refreshEngine();
} catch (error) {
showError(error);
}
}
/** «Rimuovi»: always asks whether to keep or delete the files; keeping them (the default) makes it «Solo archivio». */
export async function removeAccount(account) {
let choice = 'tieni';
const confirmButton = h('button.btn.primo', { type: 'button' }, t('account.rimuovi.confermaTieni'));
const result = await dialog({
title: t('account.rimuovi.titolo', { nome: account.username }),
className: 'piccolo',
build: (close) => {
const set = (value) => {
choice = value;
confirmButton.className = value === 'elimina' ? 'btn pericolo pieno' : 'btn primo';
confirmButton.textContent = t(value === 'elimina' ? 'account.rimuovi.confermaElimina' : 'account.rimuovi.confermaTieni');
};
confirmButton.addEventListener('click', () => close(choice));
return {
body: h('div.contenuto', h('p', t('account.rimuovi.testo')), h('div.scelte',
radio({ name: 'rimuovi', value: 'tieni', checked: true, onchange: set, labelNode: h('span', h('b', t('account.rimuovi.tieni')), h('small', t('account.rimuovi.tieniSpiega'))) }),
radio({ name: 'rimuovi', value: 'elimina', onchange: set, labelNode: h('span', h('b', t('account.rimuovi.elimina')), h('small', t('account.rimuovi.eliminaSpiega', { elementi: t('comune.elementi', { n: account.inLibrary }) }))) }))),
footer: h('footer', h('div.destra', h('button.btn.nudo', { type: 'button', onclick: () => close(undefined) }, t('comune.annulla')), confirmButton)),
};
},
});
if (!result) return false;
try {
const answer = await api(`/api/accounts/${account.id}/remove`, { method: 'POST', body: { deleteFiles: result === 'elimina' } });
toast(answer.message, answer.problems ? 'errore' : '');
return answer.outcome;
} catch (error) {
showError(error);
return false;
}
}
/** The menu of a row (and of the account card). */
export function accountMenu(anchor, account, after) {
const items = [
{ label: t('account.menu.controlla'), value: 'check', icon: 'refresh-cw', disabled: account.state === 'archiveOnly' || account.unreachableReason === 'privateNotFollowed' },
account.state === 'paused'
? { label: t('account.menu.riattiva'), value: 'resume', icon: 'play' }
: { label: t('account.menu.pausa'), value: 'pause', icon: 'pause', disabled: account.state === 'archiveOnly' },
{ label: t('account.menu.apri'), value: 'open', icon: 'external-link' },
];
if (!account.isMine) items.push('hr', { label: t('account.menu.rimuovi'), value: 'remove', icon: 'trash-2', danger: true });
menu(anchor, items, async (value) => {
try {
if (value === 'check') await checkNow(account);
if (value === 'pause' || value === 'resume') {
const result = await api(`/api/accounts/${account.id}/${value}`, { method: 'POST' });
toast(result.message);
refreshEngine();
}
if (value === 'open') openProfile(account);
if (value === 'remove') {
const outcome = await removeAccount(account);
if (outcome && after) after(outcome);
return;
}
if (after) after(value);
} catch (error) {
showError(error);
}
}, { align: 'right' });
}
/** The profile in Alberto's own browser. */
export function openProfile(account) {
const url = `https://www.instagram.com/${encodeURIComponent(account.username)}/`;
if (caps().openUrlNative) api(`/api/accounts/${account.id}/open-on-instagram`, { method: 'POST' }).catch(showError);
else window.open(url, '_blank', 'noopener,noreferrer');
}
export default {
async mount(page, route) {
let data = null;
let filter = FILTERS.includes(route.query.get('filtro')) ? route.query.get('filtro') : 'tutti';
let sort = local.get('account.ordine', 'ultimo');
if (!SORTS.includes(sort)) sort = 'ultimo';
let term = '';
page.title(t('account.titolo'), '');
const search = h('input', { type: 'search', placeholder: t('account.cerca'), 'aria-label': t('account.cerca') });
const addButton = h('button.btn.primo', { type: 'button', onclick: () => add() }, icon('plus'), t('account.aggiungi'));
page.actions(h('label.campo.cerca', { style: { width: '240px' } }, icon('search'), search), addButton);
const chips = h('div.filtri', { role: 'group', 'aria-label': t('account.colonne.stato') });
const sortButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '240px' } });
page.tools(h('div', { style: { display: 'contents' } }, chips, h('div.destra', sortButton)));
const tbody = h('tbody');
const table = h('div.pannello.tabella-account', h('table.tab',
h('thead', h('tr',
h('th', { scope: 'col' }, t('account.colonne.account')),
h('th.col-raccoglie', { scope: 'col' }, t('account.colonne.raccoglie')),
h('th.col-stato', { scope: 'col' }, t('account.colonne.stato')),
h('th.col-ultimo', { scope: 'col' }, t('account.colonne.ultimo')),
h('th.col-prossimo', { scope: 'col' }, t('account.colonne.prossimo')),
h('th.col-libreria.num', { scope: 'col' }, t('account.colonne.libreria')),
h('th.col-tieni', { scope: 'col' }, t('account.colonne.tieni')),
h('th', { scope: 'col' }, h('span.vh', t('account.colonne.azioni'))))),
tbody));
fill(page.body, table);
function drawChips() {
const counts = data.counts;
const value = { tutti: counts.all, upToDate: counts.upToDate, backfilling: counts.backfilling, paused: counts.paused, archiveOnly: counts.archiveOnly, needsAttention: counts.needsAttention };
fill(chips, FILTERS.map((f) => h(`button${f === filter ? '.qui' : ''}`, {
type: 'button', 'aria-pressed': String(f === filter),
onclick: () => {
filter = f;
setQuery({ filtro: f === 'tutti' ? null : f });
draw();
},
}, t(`account.filtri.${f}`), h('i', number(value[f])))));
fill(sortButton, h('span.val', t(`account.ordina.${sort}`)), icon('chevron-down', 's'));
}
function sorted(list) {
const by = {
ultimo: (a, b) => (b.lastCheck || 0) - (a.lastCheck || 0),
prossimo: (a, b) => (a.nextCheck ? a.nextCheck.ms : Infinity) - (b.nextCheck ? b.nextCheck.ms : Infinity),
nome: (a, b) => a.username.localeCompare(b.username),
libreria: (a, b) => b.inLibrary - a.inLibrary,
aggiunta: (a, b) => b.addedAt - a.addedAt,
}[sort];
return [...list].sort((a, b) => (b.isMine - a.isMine) || by(a, b) || a.username.localeCompare(b.username));
}
function visible() {
const q = term.toLowerCase().replace(/^@/, '');
return sorted(data.accounts.filter((a) => {
if (filter === 'needsAttention' ? !a.needsAttention : filter !== 'tutti' && a.state !== filter) return false;
return !q || a.username.includes(q) || (a.displayName || '').toLowerCase().includes(q);
}));
}
function rowOf(a) {
const types = TYPES.map((x) => {
const on = a.types[x.key];
const name = t(`account.raccoglie.${x.key}`);
const svg = icon(x.icon, 's');
if (!on) svg.classList.add('spento');
return h('span', { title: t(on ? 'account.raccoglie.attivo' : 'account.raccoglie.spento', { tipo: name }), role: 'img', 'aria-label': t(on ? 'account.raccoglie.attivo' : 'account.raccoglie.spento', { tipo: name }) }, svg);
});
const line = stateLine(a);
const progress = a.state === 'backfilling' && a.postCount
? h('div.misura.fine', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': String(a.postCount), 'aria-valuenow': String(a.posts), 'aria-label': t('account.stati.backfilling') },
h('i', { style: { width: `${Math.min(100, (a.posts / a.postCount) * 100)}%` } }))
: null;
const sw = toggle({
checked: a.keptUpdated,
label: t('account.tieniEtichetta', { nome: a.username }),
hiddenLabel: true,
disabled: a.state === 'archiveOnly',
onchange: async (value, input) => {
try {
const result = await api(`/api/accounts/${a.id}/keep-updated`, { method: 'POST', body: { value } });
toast(result.message);
await reload();
refreshEngine();
} catch (error) {
input.checked = !value;
showError(error);
}
},
});
if (a.state === 'archiveOnly') sw.querySelector('.int').classList.add('fermo');
const more = h('button.btn.nudo.solo', { type: 'button', 'aria-label': `${t('comune.menu')}: @${a.username}`, 'aria-haspopup': 'true' }, icon('ellipsis'));
more.addEventListener('click', (e) => {
e.stopPropagation();
accountMenu(more, a, () => reload());
});
const href = withCarried(`/account/${a.id}`);
const tr = h('tr', { dataset: { id: String(a.id) } },
h('td', h('div.nome', avatar(a.username, '', a.avatar), h('div',
h('b', h('a', { href, style: { color: 'inherit', textDecoration: 'none' } }, `@${a.username}`)),
h('div.sotto', a.isMine ? t('account.sotto.tuo') : a.displayName, accountLabels(a))))),
h('td.col-raccoglie', h('div.raccoglie', types)),
h('td.col-stato', h('div.condizione', h('div.riga', h(`span.spia${stateDot(a.state) ? '.' + stateDot(a.state) : ''}`, { 'aria-hidden': 'true' }), t(`account.stati.${a.state}`)),
line ? h('div.sotto', line) : null, progress)),
h('td.col-ultimo.dati.muto-cella', a.lastCheck ? ago(a.lastCheck, serverNow(), caps().today) : ''),
h('td.col-prossimo.dati.muto-cella', a.nextCheck ? (suspended() ? t('account.sospeso') : around(a.nextCheck)) : ''),
h('td.col-libreria.num.dati', number(a.inLibrary)),
h('td.col-tieni', sw),
h('td.menu-riga', more));
tr.addEventListener('click', (e) => {
if (e.target.closest('a,button,label,input')) return;
navigate(`/account/${a.id}`);
});
return tr;
}
function draw() {
if (!data) return;
page.count(t('account.quanti', { account: t('comune.account', { n: data.counts.all }), tenuti: number(data.counts.keptUpdated) }));
drawChips();
const rows = visible();
if (!data.accounts.length) {
fill(page.body, h('div.vuoto-pagina', icon('users'), h('h2', t('account.vuoto')), h('p', t('account.vuotoTesto')),
h('button.btn.primo', { type: 'button', onclick: () => add() }, icon('plus'), t('account.aggiungi'))));
return;
}
if (!table.isConnected) fill(page.body, table);
fill(tbody, rows.length ? rows.map(rowOf) : h('tr', h('td', { colspan: '8' }, h('div.caricamento', t('account.nessunoFiltro')))));
}
let loadedAt = 0;
async function reload() {
loadedAt = Date.now();
try {
data = await api('/api/accounts', { signal: page.signal });
draw();
} catch (error) {
showError(error);
}
}
async function add() {
const added = await openAddAccounts();
setQuery({ dialogo: null });
if (added) await reload();
}
sortButton.addEventListener('click', () => menu(sortButton,
SORTS.map((s) => ({ label: t(`account.ordina.${s}`), value: s, checked: s === sort, radio: true })),
(value) => {
sort = value;
local.set('account.ordine', sort);
draw();
}, { align: 'right' }));
const onSearch = later(() => {
term = search.value.trim();
draw();
}, 150);
search.addEventListener('input', onSearch);
const onChange = later(reload, 600);
page.onLibrary(onChange);
page.onLeave(() => {
onSearch.cancel();
onChange.cancel();
});
// «Ultimo controllo» and «verso le» stay current: the engine pushes its state at least every minute.
page.onEngine(() => {
if (Date.now() - loadedAt > 55000) reload();
});
await reload();
if (route.query.get('dialogo') === 'aggiungi') add();
},
};
@@ -0,0 +1,233 @@
// «Aggiungi account» (mockup 04, spec §4.2): from the local copy of the list of followed profiles (with its reading
// date and progress; it is read again only on request) or by user name, one per line; the three starting points on
// the right; the button says how many accounts it adds.
import { api } from '../core/api.js';
import { h, icon, fill, later } from '../core/dom.js';
import { t, number, shortDay } from '../core/text.js';
import { caps } from '../core/context.js';
import { avatar, checkbox, dialog, label, showError, toast } from '../core/ui.js';
const STARTS = ['everything', 'newOnly', 'storiesOnly'];
const DEPTHS = [
{ key: 'all', depth: 'all' },
{ key: 'last50', depth: 'lastPosts', lastPosts: 50 },
{ key: 'last200', depth: 'lastPosts', lastPosts: 200 },
{ key: 'last1000', depth: 'lastPosts', lastPosts: 1000 },
{ key: 'year', depth: 'fromDate' },
];
/** Opens the dialog; resolves to true when accounts were added. */
export function openAddAccounts() {
return dialog({
title: t('aggiungi.titolo'),
className: 'aggiungi',
build: (close) => build(close),
});
}
function build(close) {
let tab = 'seguiti';
let following = null;
let parsed = { names: [], problems: [] };
const chosen = new Set();
let start = 'everything';
let depth = 'all';
const tabFollowed = h('button', { type: 'button', role: 'tab', class: 'qui', 'aria-selected': 'true' }, t('aggiungi.seguiti'), h('i'));
const tabNames = h('button', { type: 'button', role: 'tab', 'aria-selected': 'false' }, t('aggiungi.perNome'));
const tabs = h('div.linguette', { role: 'tablist' }, tabFollowed, tabNames);
const left = h('div.sinistra', { role: 'tabpanel' });
const right = h('div.destra-dialogo');
const footerLeft = h('div', { style: { display: 'flex', alignItems: 'center', gap: '12px', fontSize: '13px', color: 'var(--testo-2)' } });
const addButton = h('button.btn.primo', { type: 'button', disabled: true, onclick: submit });
// ---------------------------------------------------------------------------- left: followed profiles
const search = h('input', { type: 'search', placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cerca') });
const allButton = h('button.btn', { type: 'button' }, t('aggiungi.selezionaTutti'));
const list = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
const progress = h('div.avanzamento', { role: 'status' });
const followedPanel = h('div', { style: { display: 'contents' } }, h('div.cerca-riga', h('label.campo', icon('search'), search), allButton), list, progress);
// ---------------------------------------------------------------------------- left: by user name
const area = h('textarea', { rows: '8', spellcheck: 'false', autocapitalize: 'off', 'aria-describedby': 'aiuto-nomi', placeholder: 'marta.demo\n@luca.viaggi.demo\ninstagram.com/studio.lumen.demo' });
const parsedInfo = h('div.riconosciuti', { role: 'status' });
const problems = h('div.problemi');
const namesPanel = h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px', paddingBottom: '14px', overflow: 'auto' } },
h('label.etichetta', t('aggiungi.area')),
h('label.campo.area', area),
h('p.aiuto', { id: 'aiuto-nomi' }, t('aggiungi.areaAiuto')),
parsedInfo, problems);
function present(p) {
return p.accountId != null;
}
function drawList() {
if (!following) {
fill(list, h('div.caricamento', t('comune.caricamento')));
return;
}
const term = search.value.trim().toLowerCase().replace(/^@/, '');
const shown = following.profiles.filter((p) => !term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term));
if (!shown.length) {
fill(list, h('div.caricamento', following.profiles.length ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
return;
}
fill(list, shown.map((p) => {
const isPresent = present(p);
const box = checkbox({
checked: isPresent || chosen.has(p.username),
disabled: isPresent,
labelNode: h('span', { style: { display: 'contents' } },
avatar(p.username, 'm'),
h('span.chi-nome', h('b', `@${p.username}`), p.displayName ? h('small', p.displayName) : null),
isPresent ? label(t('aggiungi.giaPresente')) : p.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
onchange: (on) => {
if (on) chosen.add(p.username);
else chosen.delete(p.username);
drawRight();
},
});
box.classList.toggle('presente', isPresent);
return box;
}));
}
function drawProgress() {
if (!following) return;
progress.hidden = !following.inProgress;
fill(progress, following.inProgress
? [icon('hourglass', 's'), following.readSoFar ? t('aggiungi.avanzamento', { n: number(following.readSoFar) }) : t('aggiungi.inAttesa')]
: []);
fill(footerLeft,
h('span', following.readDay ? t('aggiungi.lettoIl', { giorno: shortDay(following.readDay, caps().today) }) : t('aggiungi.maiLetto')),
h('button.btn.collegamento', { type: 'button', disabled: following.inProgress, onclick: reread, title: t('aggiungi.rilettura') },
icon('refresh-cw', 's'), following.readDay ? t('aggiungi.rileggi') : t('aggiungi.leggi')));
const count = tabFollowed.querySelector('i');
count.textContent = number(following.total);
}
async function loadFollowing() {
try {
following = await api('/api/following');
} catch (error) {
showError(error);
following = { profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 };
}
drawList();
drawProgress();
drawRight();
}
async function reread() {
try {
following = await api('/api/following/read', { method: 'POST' });
drawProgress();
drawList();
} catch (error) {
showError(error);
}
}
allButton.addEventListener('click', () => {
if (!following) return;
const term = search.value.trim().toLowerCase().replace(/^@/, '');
const shown = following.profiles.filter((p) => !present(p) && (!term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term)));
const all = shown.every((p) => chosen.has(p.username));
for (const p of shown) {
if (all) chosen.delete(p.username);
else chosen.add(p.username);
}
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
drawList();
drawRight();
});
search.addEventListener('input', later(drawList, 120));
const parse = later(async () => {
try {
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text: area.value } });
} catch (error) {
showError(error);
return;
}
const ready = parsed.names.filter((n) => !n.present);
const already = parsed.names.length - ready.length;
fill(parsedInfo, area.value.trim() ? [t('aggiungi.riconosciuti', { n: ready.length }), already ? ` · ${t('aggiungi.presenti', { n: already })}` : ''] : '');
fill(problems, parsed.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
drawRight();
}, 250);
area.addEventListener('input', parse);
// ---------------------------------------------------------------------------- right: starting point
function selection() {
return tab === 'seguiti' ? [...chosen] : parsed.names.filter((n) => !n.present).map((n) => n.username);
}
function drawRight() {
const n = selection().length;
const perDay = following && following.backfillPerDay ? following.backfillPerDay : 300;
const startInputs = STARTS.map((s) => {
const input = h('input.vh', { type: 'radio', name: 'partenza', value: s, checked: s === start });
input.addEventListener('change', () => {
start = s;
drawRight();
});
return h('label', input, h('span.tondo', { 'aria-hidden': 'true' }),
h('span', h('b', t(`aggiungi.partenze.${s}`)), h('small', t(`aggiungi.partenze.${s}Spiega`))));
});
const select = h('select', { 'aria-label': t('aggiungi.quanto') }, DEPTHS.map((d) => h('option', { value: d.key, selected: d.key === depth }, t(`aggiungi.profondita.${d.key}`))));
select.addEventListener('change', () => {
depth = select.value;
});
fill(right,
h('h2.sez', n ? t('aggiungi.perScelti', { n }) : t('aggiungi.perNessuno')),
h('p.aiuto', t('aggiungi.potraiCambiare')),
h('div.partenza', { role: 'radiogroup', 'aria-label': t('aggiungi.potraiCambiare') }, startInputs),
start === 'everything' ? [h('label.etichetta', { for: 'profondita' }, t('aggiungi.quanto')), h('label.campo.scelta', select, icon('chevron-down', 's'))] : null,
h('div.avviso', { style: { marginTop: '14px' } }, icon('info', 's'),
h('span', start === 'everything' ? t('aggiungi.info', { n: number(perDay) }) : t('aggiungi.infoNovita'))));
select.id = 'profondita';
addButton.disabled = n === 0;
addButton.textContent = t('aggiungi.conferma', { n });
}
async function submit() {
const usernames = selection();
if (!usernames.length) return;
const d = DEPTHS.find((x) => x.key === depth) || DEPTHS[0];
addButton.disabled = true;
try {
const result = await api('/api/accounts', { method: 'POST', body: { usernames, start, depth: start === 'everything' ? d.depth : null, lastPosts: d.lastPosts || null } });
toast(result.message);
close(result.added > 0);
} catch (error) {
addButton.disabled = false;
showError(error);
}
}
function setTab(value) {
tab = value;
tabFollowed.classList.toggle('qui', value === 'seguiti');
tabNames.classList.toggle('qui', value === 'nomi');
tabFollowed.setAttribute('aria-selected', String(value === 'seguiti'));
tabNames.setAttribute('aria-selected', String(value === 'nomi'));
fill(left, value === 'seguiti' ? followedPanel : namesPanel);
footerLeft.hidden = value !== 'seguiti';
drawRight();
(value === 'seguiti' ? search : area).focus();
}
tabFollowed.addEventListener('click', () => setTab('seguiti'));
tabNames.addEventListener('click', () => setTab('nomi'));
fill(left, followedPanel);
drawList();
drawRight();
loadFollowing();
return {
body: h('div', { style: { display: 'contents' } }, tabs, h('div.corpo-dialogo', left, right)),
footer: h('footer', footerLeft, h('div.destra', h('button.btn', { type: 'button', onclick: () => close(false) }, t('comune.annulla')), addButton)),
};
}
+373
View File
@@ -0,0 +1,373 @@
// Libreria (mockup 01, spec §4.6): every entry by publication day, filters by kind, account, period and provenance,
// search by account name and caption, tile size, multiple selection to export or delete, viewer on click.
import { api, download } from '../core/api.js';
import { caps } from '../core/context.js';
import { h, icon, fill, later, local } from '../core/dom.js';
import { setQuery } from '../core/shell.js';
import { t, number, shortDay, parseDay } from '../core/text.js';
import { menu, showError, toast, confirmDialog } from '../core/ui.js';
import { Mosaic } from './mosaic.js';
import { openViewer } from './viewer.js';
const KINDS = [
{ key: 'tutto', api: 'all', label: 'libreria.tipi.all' },
{ key: 'foto', api: 'photos', label: 'libreria.tipi.photos' },
{ key: 'video', api: 'videos', label: 'libreria.tipi.videos' },
{ key: 'storie', api: 'stories', label: 'libreria.tipi.stories' },
{ key: 'evidenza', api: 'highlights', label: 'libreria.tipi.highlights' },
{ key: 'taggati', api: 'tagged', label: 'libreria.tipi.tagged' },
];
const PERIODS = ['settimana', 'mese', 'anno', 'annoScorso'];
/** The filter of the page address (Italian names) as the query of the API. */
export function apiQuery(state, today) {
const q = new URLSearchParams();
const kind = KINDS.find((k) => k.key === state.tipo);
if (kind && kind.api !== 'all') q.set('kind', kind.api);
if (state.account) q.set('accounts', state.account);
const range = periodRange(state, today);
if (range.from) q.set('from', range.from);
if (range.to) q.set('to', range.to);
if (state.provenienza === 'importati') q.set('provenance', 'imported');
if (state.provenienza === 'scaricati') q.set('provenance', 'downloaded');
if (state.q) q.set('q', state.q);
return q.toString();
}
function addDays(day, n) {
return new Date(Date.parse(`${day}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10);
}
function periodRange(state, today) {
if (state.dal || state.al) return { from: state.dal || null, to: state.al || null };
const year = today ? parseDay(today).y : new Date().getFullYear();
switch (state.periodo) {
case 'settimana': return { from: addDays(today, -6), to: today };
case 'mese': return { from: addDays(today, -29), to: today };
case 'anno': return { from: `${year}-01-01`, to: today };
case 'annoScorso': return { from: `${year - 1}-01-01`, to: `${year - 1}-12-31` };
default: return {};
}
}
function readState(query) {
return {
tipo: query.get('tipo') || 'tutto',
account: query.get('account') || '',
periodo: query.get('periodo') || '',
dal: query.get('dal') || '',
al: query.get('al') || '',
provenienza: query.get('provenienza') || '',
q: query.get('q') || '',
};
}
export default {
async mount(page, route) {
const state = readState(route.query);
const today = () => caps().today || new Date().toISOString().slice(0, 10);
let accounts = null;
let mosaic = null;
page.title(t('libreria.titolo'), '');
const search = h('input', { type: 'search', placeholder: t('libreria.cerca'), 'aria-label': t('libreria.cerca'), value: state.q });
// In a narrow window the field is short: the placeholder becomes «Cerca» (the accessible name stays complete).
const narrow = window.matchMedia('(max-width: 1000px)');
const placeholder = () => { search.placeholder = t(narrow.matches ? 'libreria.cercaBreve' : 'libreria.cerca'); };
placeholder();
narrow.addEventListener('change', placeholder, { signal: page.signal });
page.actions(h('label.campo.cerca', icon('search'), search));
// Tools: kind chips, the three menus, tile size, selection.
const chips = h('div.filtri', { role: 'group', 'aria-label': t('libreria.filtriTipo') });
const accountButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '118px' } });
const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '111px' } });
const provenanceButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '141px' } });
const filtersButton = h('button.btn.solo-stretto', { type: 'button', 'aria-haspopup': 'true' }, icon('list-filter'), t('libreria.filtri'));
const size = local.get('libreria.tessere', 160);
const slider = h('input.cursore', { type: 'range', min: '96', max: '300', step: '4', value: String(size), 'aria-label': t('libreria.grandezza') });
const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
page.tools(h('div', { style: { display: 'contents' } },
chips,
h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton),
filtersButton,
h('div.destra',
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
selectButton)));
const host = h('div');
fill(page.body, host);
function filtersActive() {
return state.tipo !== 'tutto' || state.account || state.periodo || state.dal || state.al || state.provenienza || state.q;
}
function drawChips() {
fill(chips, KINDS.map((k) => h(`button${k.key === state.tipo ? '.qui' : ''}`, {
type: 'button',
'aria-pressed': String(k.key === state.tipo),
onclick: () => {
state.tipo = k.key;
apply();
},
}, t(k.label))));
}
function menuLabel(button, text, chosen) {
fill(button, h('span.val', text), icon('chevron-down', 's'));
button.classList.toggle('attivo', Boolean(chosen));
}
function drawMenus() {
// A menu shows the name of its filter until a value is chosen (spec §10.3).
const ids = state.account ? state.account.split(',') : [];
let accountText = t('libreria.menuAccount');
if (ids.length === 1 && accounts) {
const a = accounts.find((x) => String(x.id) === ids[0]);
accountText = a ? `@${a.username}` : t('libreria.accountScelti', { n: 1 });
} else if (ids.length) accountText = t('libreria.accountScelti', { n: ids.length });
menuLabel(accountButton, accountText, ids.length);
let periodText = t('libreria.menuPeriodo');
if (state.dal || state.al) periodText = t('libreria.periodi.date', { dal: state.dal ? shortDay(state.dal, today()) : '…', al: state.al ? shortDay(state.al, today()) : '…' });
else if (state.periodo) periodText = t(`libreria.periodi.${state.periodo}`);
menuLabel(periodButton, periodText, state.periodo || state.dal || state.al);
menuLabel(provenanceButton, state.provenienza ? t(`libreria.provenienze.${state.provenienza === 'importati' ? 'imported' : 'downloaded'}`) : t('libreria.menuProvenienza'), state.provenienza);
filtersButton.classList.toggle('primo', Boolean(state.account || state.periodo || state.dal || state.al || state.provenienza));
}
async function loadAccounts() {
if (!accounts) accounts = (await api('/api/accounts', { signal: page.signal })).accounts;
return accounts;
}
async function openAccounts(anchor) {
try {
await loadAccounts();
} catch (error) {
showError(error);
return;
}
const chosen = new Set(state.account ? state.account.split(',') : []);
const field = h('input', { type: 'search', placeholder: t('libreria.cercaAccount'), 'aria-label': t('libreria.cercaAccount') });
const list = h('div');
const header = h('div.cerca-menu', h('label.campo', icon('search', 's'), field));
const drawList = () => {
const term = field.value.trim().toLowerCase().replace(/^@/, '');
const items = [
h('button', { type: 'button', role: 'menuitemcheckbox', 'aria-checked': String(chosen.size === 0), onclick: () => { chosen.clear(); commit(); } },
h('span', t('libreria.tuttiGliAccount')), icon('check', 's segno')),
h('hr'),
];
const shown = accounts.filter((a) => !term || a.username.includes(term) || (a.displayName || '').toLowerCase().includes(term));
for (const a of shown) {
items.push(h('button', {
type: 'button', role: 'menuitemcheckbox', 'aria-checked': String(chosen.has(String(a.id))),
onclick: (e) => {
const id = String(a.id);
if (chosen.has(id)) chosen.delete(id);
else chosen.add(id);
e.currentTarget.setAttribute('aria-checked', String(chosen.has(id)));
commit(false);
},
}, h('span', `@${a.username}`), icon('check', 's segno')));
}
if (!shown.length) items.push(h('div.vuoto', t('libreria.nessunAccount')));
fill(list, items);
};
const commit = (close = true) => {
state.account = [...chosen].join(',');
if (close) handle.close();
apply();
};
field.addEventListener('input', drawList);
drawList();
const handle = menu(anchor, [header, list], () => {}, { width: 280 });
}
function openPeriod(anchor) {
const from = h('input', { type: 'date', value: state.dal, 'aria-label': t('libreria.periodi.dal'), max: today() });
const to = h('input', { type: 'date', value: state.al, 'aria-label': t('libreria.periodi.al'), max: today() });
const items = [
{ label: t('libreria.periodi.qualsiasi'), value: '', checked: !state.periodo && !state.dal && !state.al, radio: true },
...PERIODS.map((p) => ({ label: t(`libreria.periodi.${p}`), value: p, checked: state.periodo === p, radio: true })),
'hr',
h('div.date', h('span', t('libreria.periodi.dal')), h('label.campo', from), h('span', t('libreria.periodi.al')), h('label.campo', to)),
h('div', { style: { padding: '2px 6px 4px' } }, h('button.btn.piccolo', {
type: 'button',
onclick: () => {
state.periodo = '';
state.dal = from.value;
state.al = to.value;
handle.close();
apply();
},
}, t('libreria.periodi.applica'))),
];
const handle = menu(anchor, items, (value) => {
state.periodo = value;
state.dal = '';
state.al = '';
apply();
}, { width: 300 });
}
function openProvenance(anchor) {
menu(anchor, [
{ label: t('libreria.provenienze.tutte'), value: '', checked: !state.provenienza, radio: true },
{ label: t('libreria.provenienze.downloaded'), value: 'scaricati', checked: state.provenienza === 'scaricati', radio: true },
{ label: t('libreria.provenienze.imported'), value: 'importati', checked: state.provenienza === 'importati', radio: true },
], (value) => {
state.provenienza = value;
apply();
});
}
function openFilters(anchor) {
// Narrow window: the three menus behind one button.
menu(anchor, [
{ label: accountButton.textContent, value: 'account', icon: 'users' },
{ label: periodButton.textContent, value: 'periodo', icon: 'calendar' },
{ label: provenanceButton.textContent, value: 'provenienza', icon: 'folder-input' },
], (value) => {
if (value === 'account') openAccounts(anchor);
if (value === 'periodo') openPeriod(anchor);
if (value === 'provenienza') openProvenance(anchor);
});
}
accountButton.addEventListener('click', () => openAccounts(accountButton));
periodButton.addEventListener('click', () => openPeriod(periodButton));
provenanceButton.addEventListener('click', () => openProvenance(provenanceButton));
filtersButton.addEventListener('click', () => openFilters(filtersButton));
slider.addEventListener('input', () => {
const value = Number(slider.value);
local.set('libreria.tessere', value);
if (mosaic) mosaic.setRowHeight(value);
});
const onSearch = later(() => {
state.q = search.value.trim();
apply();
}, 300);
search.addEventListener('input', onSearch);
page.onLeave(() => onSearch.cancel());
// Selection bar.
function drawSelection(selected) {
if (!mosaic || !mosaic.selecting) {
page.saveBar(null);
return;
}
const n = selected.size;
page.saveBar(h('div', { style: { display: 'contents' } },
h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')),
h('div.destra',
h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')),
h('button.btn', { type: 'button', disabled: !n, onclick: () => exportSelected() }, icon('file-down'), t('selezione.esporta')),
h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: () => deleteSelected() }, icon('trash-2'), t('selezione.elimina', { n })))));
}
function setSelecting(on) {
if (!mosaic) return;
mosaic.setSelecting(on);
selectButton.setAttribute('aria-pressed', String(on));
fill(selectButton, icon(on ? 'check' : 'circle-check'), h('span', t(on ? 'libreria.fine' : 'libreria.seleziona')));
drawSelection(mosaic.selected);
}
selectButton.addEventListener('click', () => setSelecting(!mosaic.selecting));
async function exportSelected() {
try {
await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv');
toast(t('selezione.esportato'));
} catch (error) {
showError(error);
}
}
async function deleteSelected() {
const ids = [...mosaic.selected];
const removed = await confirmDelete(ids);
if (removed) {
mosaic.removeTiles(removed);
setSelecting(false);
}
}
// The mosaic.
async function apply() {
setQuery({
tipo: state.tipo === 'tutto' ? null : state.tipo,
account: state.account || null,
periodo: state.periodo || null,
dal: state.dal || null,
al: state.al || null,
provenienza: state.provenienza || null,
q: state.q || null,
});
drawChips();
drawMenus();
if (mosaic) mosaic.destroy();
page.body.scrollTop = 0;
mosaic = new Mosaic({
scroller: page.body,
host,
query: apiQuery(state, today()),
rowHeight: Number(slider.value),
signal: page.signal,
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }),
onSelection: drawSelection,
onTotals: ({ entries, accounts: n }) => page.count(t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })),
onEmpty: () => fill(host, filtersActive()
? h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')))
: h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
});
try {
await mosaic.start();
} catch (error) {
showError(error);
}
drawSelection(mosaic.selected);
}
const onLibraryChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 400);
page.onLibrary(onLibraryChange);
page.onLeave(() => {
onLibraryChange.cancel();
if (mosaic) mosaic.destroy();
});
loadAccounts().then(drawMenus).catch(() => {});
await apply();
void number;
},
};
/**
* «Elimina dalla libreria» with the confirmation of spec §4.6: by default the choice is remembered (state «eliminato»,
* never downloaded again); «Eliminalo e lascia che torni» forgets the entry. Returns the deleted keys, or null.
*/
export async function confirmDelete(ids) {
const n = ids.length;
const mode = await confirmDialog({
title: t('elimina.titolo', { n }),
text: t('elimina.testo', { n }),
extra: h('p.aiuto', t('elimina.tornaSpiega')),
buttons: [
{ label: t('comune.annulla'), value: undefined, kind: 'nudo' },
{ label: t('elimina.torna', { n }), value: 'allowReturn' },
{ label: t('elimina.conferma'), value: 'remember', kind: 'pericolo pieno', autofocus: true },
],
});
if (!mode) return null;
try {
const result = await api('/api/entries/delete', { method: 'POST', body: { ids, mode } });
toast(result.message, result.problems.length ? 'errore' : '');
return ids;
} catch (error) {
showError(error);
return null;
}
}
+526
View File
@@ -0,0 +1,526 @@
// The mosaic of the library (mockup 01) and of the account tabs (mockup 12): entries grouped by day, justified rows
// that keep the proportions of the pictures with 4 px between tiles, or a regular 9:16 grid for stories.
// Fluid with 200,000 entries: the page knows only how many entries each day has (one cheap query); a day group is
// fetched (keyset windows) and drawn only when it comes near the visible area, and emptied again when it goes far,
// keeping its height. Changes of height above the visible area are compensated, so nothing moves under the eyes.
import { api } from '../core/api.js';
import { h, icon, fill, perFrame } from '../core/dom.js';
import { t, dayName, duration, capitalize } from '../core/text.js';
import { avatar } from '../core/ui.js';
const GAP = 4;
const NEAR = '1400px 0px';
const FAR = '7000px 0px';
function aspectOf(tile) {
const c = tile.cover;
if (!c || !c.width || !c.height) return 1;
return Math.min(2.2, Math.max(0.5, c.width / c.height));
}
function older(a, b) {
// true when tile a comes after tile b in display order (published earlier, or same time and smaller id)
return a.publishedAt < b.publishedAt || (a.publishedAt === b.publishedAt && a.id < b.id);
}
export function cursorOf(tile) {
return `${tile.publishedAt}.${tile.id}`;
}
/** Justified rows: every full row exactly fills the width; the last row keeps the target height. */
export function justify(tiles, width, target) {
const rows = [];
let row = [];
let sum = 0;
for (const tile of tiles) {
const ar = aspectOf(tile);
row.push({ tile, ar });
sum += ar;
const full = sum * target + GAP * (row.length - 1);
if (full >= width) {
const withLast = (width - GAP * (row.length - 1)) / sum;
const withoutLast = row.length > 1 ? (width - GAP * (row.length - 2)) / (sum - ar) : Infinity;
if (row.length > 1 && Math.abs(withoutLast - target) < Math.abs(withLast - target) && withoutLast < target * 1.4) {
const last = row.pop();
rows.push({ items: row, height: withoutLast, full: true });
row = [last];
sum = last.ar;
} else {
rows.push({ items: row, height: withLast, full: true });
row = [];
sum = 0;
}
}
}
if (row.length) rows.push({ items: row, height: target, full: false });
for (const r of rows) {
let used = 0;
r.items.forEach((item, i) => {
item.width = Math.max(24, Math.round(item.ar * r.height));
used += item.width + (i > 0 ? GAP : 0);
});
if (r.full && r.items.length) r.items[r.items.length - 1].width += width - used;
r.height = Math.round(r.height);
}
return rows;
}
/** A tile: thumbnail, marks top-right, on hover account and time, selection circle. */
export function tileElement(tile, width, height, { selected = false, today = '', ring = true } = {}) {
const cover = tile.cover;
const marks = [];
if (tile.kind === 'story' && ring) marks.push(h('span.anello', { title: t('libreria.tipiTessera.story') }, icon('circle-dashed')));
if (cover && cover.kind === 'video') marks.push(h('span', icon('play'), duration(cover.duration || 0)));
if (tile.files > 1) marks.push(h('span', icon('layers'), String(tile.files)));
const when = tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : `${dayName(tile.day, today)}, ${tile.time}`;
const description = [t('libreria.tessera', { tipo: t(`libreria.tipiTessera.${tile.kind}`), account: tile.username, quando: when })];
if (tile.files > 1) description.push(t('libreria.tesseraFile', { n: tile.files }));
if (cover && cover.kind === 'video') description.push(t('libreria.tesseraDurata', { durata: duration(cover.duration || 0) }));
const el = h(`button.tess${selected ? '.scelta' : ''}`, {
type: 'button',
style: { width: `${width}px`, height: `${height}px` },
dataset: { id: String(tile.id) },
'aria-label': description.join(', '),
'aria-pressed': selected ? 'true' : null,
},
cover && cover.thumb
? h('img', { src: `/api/thumbnails/${cover.thumb}`, alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' })
: h('span.tess.vuota', { style: { width: '100%', height: '100%' } }, icon('image')),
marks.length ? h('span.segno', marks) : null,
h('span.sel', { role: 'checkbox', 'aria-checked': String(selected), 'aria-label': t('libreria.scegliTessera'), title: t('libreria.scegliTessera') }, icon('check')),
h('span.chi', avatar(tile.username, 'p'), h('span', `@${tile.username}`), h('small', tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : tile.time)));
return el;
}
/** The default day header: «Oggi martedì 13 ottobre, 14 nuovi elementi». */
export function defaultDayLabel(day, count, today) {
const name = dayName(day, today);
if (day === today) return [t('tempo.Oggi'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.nuoviOggi', { n: count }) })];
const yesterday = new Date(Date.parse(`${today}T12:00:00Z`) - 86400000).toISOString().slice(0, 10);
if (day === yesterday) return [t('tempo.Ieri'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.elementiGiorno', { n: count }) })];
return [capitalize(name), t('libreria.elementiGiorno', { n: count })];
}
export class Mosaic {
/**
* scroller: the scrolling element (.corpo); host: where the groups go; query: filter as a query string;
* mode: 'justified' or 'grid' (9:16 stories); rowHeight: target height of the rows;
* onOpen(tile), onSelection(set), onTotals({ entries, accounts, today }), onEmpty(), dayLabel(day, count, today).
*/
constructor(options) {
this.scroller = options.scroller;
this.host = options.host;
this.query = options.query || '';
this.mode = options.mode || 'justified';
this.rowHeight = options.rowHeight || 160;
this.onOpen = options.onOpen || (() => {});
this.onSelection = options.onSelection || (() => {});
this.onTotals = options.onTotals || (() => {});
this.onEmpty = options.onEmpty || (() => {});
this.dayLabel = options.dayLabel || defaultDayLabel;
this.signal = options.signal;
this.sections = [];
this.byDay = new Map();
this.selected = new Set();
this.selecting = false;
this.today = '';
this.avgAspect = this.mode === 'grid' ? 0.5625 : 0.95;
this.width = 0;
this.pendingNew = 0;
this.root = h('div.mosaico');
this.pill = h('div.nuovi-in-cima', { hidden: true });
fill(this.host, this.pill, this.root);
this.near = new IntersectionObserver((entries) => this.onNear(entries), { root: this.scroller, rootMargin: NEAR });
this.far = new IntersectionObserver((entries) => this.onFar(entries), { root: this.scroller, rootMargin: FAR });
this.resize = new ResizeObserver(perFrame(() => this.onResize()));
this.resize.observe(this.root);
this.root.addEventListener('click', (e) => this.onClick(e));
}
destroy() {
this.near.disconnect();
this.far.disconnect();
this.resize.disconnect();
}
/** Loads the days of the filter and draws the groups that are visible. */
async start() {
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
this.today = data.today;
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
this.width = this.root.clientWidth || this.host.clientWidth || 800;
for (const section of this.sections) this.unobserve(section);
this.sections = [];
this.byDay.clear();
this.root.replaceChildren();
for (const day of data.days) this.root.append(this.createSection(day).el);
if (!data.days.length) this.onEmpty();
}
createSection(day) {
const section = { day: day.day, count: day.count, cursor: day.cursor, tiles: [], complete: false, loading: null, rendered: false, near: false, stale: false };
const [bold, rest] = this.dayLabel(day.day, day.count, this.today);
section.header = h('header.giorno', h('b', bold), rest ? h('span', rest) : null);
section.rows = h('div.righe', { style: { height: `${this.estimate(day.count)}px` } });
section.el = h('section.gruppo-giorno', { dataset: { day: day.day }, 'aria-label': `${bold} ${rest || ''}` }, section.header, section.rows);
this.byDay.set(day.day, section);
this.sections.push(section);
this.near.observe(section.el);
this.far.observe(section.el);
return section;
}
unobserve(section) {
this.near.unobserve(section.el);
this.far.unobserve(section.el);
}
estimate(count) {
const width = Math.max(200, this.width || 800);
if (this.mode === 'grid') {
const tileHeight = Math.round(this.rowHeight * 1.25);
const perRow = Math.max(1, Math.floor((width + GAP) / (Math.round(tileHeight * 0.5625) + GAP)));
return Math.ceil(count / perRow) * (tileHeight + GAP);
}
const rows = Math.max(1, Math.ceil((count * this.avgAspect * this.rowHeight) / width));
return rows * (this.rowHeight * 0.96 + GAP);
}
onNear(entries) {
for (const entry of entries) {
const section = this.sections.find((s) => s.el === entry.target);
if (!section) continue;
section.near = entry.isIntersecting;
if (entry.isIntersecting) this.wake(section);
}
}
onFar(entries) {
for (const entry of entries) {
if (entry.isIntersecting) continue;
const section = this.sections.find((s) => s.el === entry.target);
if (section && section.rendered) this.unrender(section);
}
}
async wake(section) {
try {
while (!section.complete && section.near) await this.load(section);
if (section.near && !section.rendered && section.el.isConnected) this.render(section);
} catch (error) {
if (error.name !== 'AbortError') console.error(error);
}
}
/** Fetches the next window from where a group is, and hands the tiles to every group they belong to. */
load(section) {
if (section.loading) return section.loading;
const missing = section.count - section.tiles.length;
const limit = Math.min(600, Math.max(120, missing + 40));
const cursor = section.tiles.length ? cursorOf(section.tiles[section.tiles.length - 1]) : section.cursor;
section.loading = api(`/api/library?${this.query}${this.query ? '&' : ''}cursor=${encodeURIComponent(cursor)}&limit=${limit}`, { signal: this.signal })
.then((page) => {
const touched = new Set();
for (const tile of page.tiles) {
const target = this.byDay.get(tile.day);
if (!target || target.complete) continue;
const last = target.tiles[target.tiles.length - 1];
if (last && !older(tile, last)) continue;
target.tiles.push(tile);
touched.add(target);
}
if (!page.older) {
const index = this.sections.indexOf(section);
for (const s of this.sections.slice(index)) s.complete = true;
}
for (const s of touched) {
if (s.tiles.length >= s.count) s.complete = true;
this.learn(s.tiles);
}
if (!touched.has(section) && !section.complete) section.complete = true; // nothing more for this day
for (const s of touched) if (s !== section && s.near && s.complete && !s.rendered) this.render(s);
})
.finally(() => {
section.loading = null;
});
return section.loading;
}
learn(tiles) {
if (this.mode === 'grid' || !tiles.length) return;
const sample = tiles.slice(0, 200);
const mean = sample.reduce((a, tile) => a + aspectOf(tile), 0) / sample.length;
this.avgAspect = this.avgAspect * 0.7 + mean * 0.3;
}
/** Runs fn and keeps what is visible in place when a group above the visible area changes height. */
keepView(section, fn) {
const scrollerTop = this.scroller.getBoundingClientRect().top;
const rect = section.el.getBoundingClientRect();
const above = rect.bottom <= scrollerTop + 1;
const before = section.el.offsetHeight;
fn();
const after = section.el.offsetHeight;
if (above && after !== before) this.scroller.scrollTop += after - before;
}
render(section) {
const width = this.root.clientWidth || this.width;
this.width = width;
const rows = this.layout(section.tiles, width);
const nodes = rows.map((row) => h(this.mode === 'grid' ? 'div.griglia-storie' : 'div.fila',
row.items.map((item) => tileElement(item.tile, item.width, row.height, { selected: this.selected.has(item.tile.id), today: this.today, ring: this.mode !== 'grid' }))));
this.keepView(section, () => {
section.rows.style.height = '';
fill(section.rows, nodes);
section.rendered = true;
section.renderedWidth = width;
});
}
layout(tiles, width) {
if (this.mode !== 'grid') return justify(tiles, width, this.rowHeight);
const height = Math.round(this.rowHeight * 1.25);
const w = Math.round(height * 0.5625);
const perRow = Math.max(1, Math.floor((width + GAP) / (w + GAP)));
const rows = [];
for (let i = 0; i < tiles.length; i += perRow) rows.push({ height, items: tiles.slice(i, i + perRow).map((tile) => ({ tile, width: w })) });
return rows;
}
unrender(section) {
const height = section.rows.offsetHeight;
section.rows.style.height = `${height}px`;
section.rows.replaceChildren();
section.rendered = false;
}
onResize() {
const width = this.root.clientWidth;
if (!width || Math.abs(width - this.width) < 2) return;
this.relayout(width);
}
/** Lays everything out again (new width or new tile size), keeping the group at the top of the view in place. */
relayout(width = this.root.clientWidth) {
const anchor = this.topSection();
const offset = anchor ? this.scroller.scrollTop - anchor.el.offsetTop : 0;
const ratio = anchor && anchor.el.offsetHeight ? offset / anchor.el.offsetHeight : 0;
this.width = width;
for (const section of this.sections) {
if (section.rendered) this.render(section);
else section.rows.style.height = `${this.estimate(section.count)}px`;
}
if (anchor) this.scroller.scrollTop = anchor.el.offsetTop + ratio * anchor.el.offsetHeight;
}
setRowHeight(height) {
this.rowHeight = height;
this.relayout();
}
topSection() {
const top = this.scroller.getBoundingClientRect().top;
return this.sections.find((s) => s.el.getBoundingClientRect().bottom > top + 1) || null;
}
// ------------------------------------------------------------------------------------------- selection and clicks
setSelecting(on) {
this.selecting = on;
this.root.classList.toggle('scegli', on);
if (!on) this.clearSelection();
}
clearSelection() {
this.selected.clear();
for (const el of this.root.querySelectorAll('.tess.scelta')) this.markTile(el, false);
this.onSelection(this.selected);
}
markTile(el, on) {
el.classList.toggle('scelta', on);
el.setAttribute('aria-pressed', on ? 'true' : 'false');
const sel = el.querySelector('.sel');
if (sel) sel.setAttribute('aria-checked', String(on));
}
toggle(id, el) {
const on = !this.selected.has(id);
if (on) this.selected.add(id);
else this.selected.delete(id);
if (el) this.markTile(el, on);
if (!this.selecting && on) this.setSelecting(true);
this.onSelection(this.selected);
}
onClick(e) {
const el = e.target.closest('.tess[data-id]');
if (!el) return;
const id = Number(el.dataset.id);
if (e.target.closest('.sel') || this.selecting) {
e.preventDefault();
this.toggle(id, el);
return;
}
const tile = this.findTile(id);
if (tile) this.onOpen(tile);
}
findTile(id) {
for (const s of this.sections) {
const tile = s.tiles.find((x) => x.id === id);
if (tile) return tile;
}
return null;
}
// ------------------------------------------------------------------------------------------- viewer navigation
/** Position of an entry among all the entries of the filter (1-based) and the total. */
position(id) {
let before = 0;
for (const s of this.sections) {
const i = s.tiles.findIndex((x) => x.id === id);
if (i >= 0) return { index: before + i + 1, total: this.sections.reduce((a, x) => a + x.count, 0) };
before += s.count;
}
return { index: 0, total: this.sections.reduce((a, x) => a + x.count, 0) };
}
/** The entry before (delta −1) or after (+1) an entry, loading the next group when needed. */
async neighbor(id, delta) {
let si = this.sections.findIndex((s) => s.tiles.some((x) => x.id === id));
if (si < 0) return null;
let i = this.sections[si].tiles.findIndex((x) => x.id === id) + delta;
for (;;) {
const s = this.sections[si];
if (i >= 0 && i < s.tiles.length) return s.tiles[i];
if (delta > 0 && !s.complete) {
await this.load(s);
continue;
}
si += delta;
if (si < 0 || si >= this.sections.length) return null;
const next = this.sections[si];
if (!next.complete && next.tiles.length === 0) await this.load(next);
i = delta > 0 ? 0 : next.tiles.length - 1;
}
}
/** Scrolls so that an entry is visible (after the viewer moved far). */
reveal(id) {
const el = this.root.querySelector(`.tess[data-id="${id}"]`);
if (el) el.scrollIntoView({ block: 'nearest' });
}
// ------------------------------------------------------------------------------------------- changes
/** Removes entries (after a deletion) and updates the counts of their days. */
removeTiles(ids) {
const set = new Set(ids);
for (const s of [...this.sections]) {
const before = s.tiles.length;
s.tiles = s.tiles.filter((x) => !set.has(x.id));
const removed = before - s.tiles.length;
if (!removed) continue;
s.count -= removed;
for (const id of ids) this.selected.delete(id);
if (s.count <= 0) {
this.unobserve(s);
this.keepView(s, () => s.el.remove());
this.sections.splice(this.sections.indexOf(s), 1);
this.byDay.delete(s.day);
continue;
}
const [bold, rest] = this.dayLabel(s.day, s.count, this.today);
fill(s.header, h('b', bold), rest ? h('span', rest) : null);
if (s.rendered) this.render(s);
}
this.onSelection(this.selected);
}
/**
* The library changed: new days appear at the top and changed days are reloaded, without moving what is on screen.
* A group being looked at is not redrawn under the eyes: «N nuovi elementi in cima» offers to show them.
*/
async refresh() {
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
const todayChanged = data.today !== this.today;
this.today = data.today;
const wanted = new Map(data.days.map((d) => [d.day, d]));
let added = 0;
for (const s of [...this.sections]) {
if (!wanted.has(s.day)) {
this.unobserve(s);
this.keepView(s, () => s.el.remove());
this.sections.splice(this.sections.indexOf(s), 1);
this.byDay.delete(s.day);
}
}
let previous = null;
for (const day of data.days) {
let s = this.byDay.get(day.day);
if (!s) {
s = this.createSection(day);
this.sections.splice(previous ? this.sections.indexOf(previous) + 1 : 0, 0, ...this.sections.splice(this.sections.indexOf(s), 1));
const anchor = previous ? previous.el.nextSibling : this.root.firstChild;
this.keepView(s, () => this.root.insertBefore(s.el, anchor));
added += day.count;
} else if (s.count !== day.count || todayChanged) {
const grew = day.count - s.count;
if (s.rendered && this.isVisible(s)) {
s.stale = day;
if (grew > 0) added += grew;
} else {
this.reset(s, day);
}
}
previous = s;
}
if (added > 0) this.showPill(added);
if (!this.sections.length) this.onEmpty();
}
reset(s, day) {
s.count = day.count;
s.cursor = day.cursor;
s.tiles = [];
s.complete = false;
s.stale = false;
const [bold, rest] = this.dayLabel(s.day, s.count, this.today);
fill(s.header, h('b', bold), rest ? h('span', rest) : null);
if (s.rendered) {
this.keepView(s, () => {
s.rows.style.height = `${this.estimate(s.count)}px`;
s.rows.replaceChildren();
s.rendered = false;
});
}
if (s.near) this.wake(s);
}
isVisible(s) {
const top = this.scroller.getBoundingClientRect();
const rect = s.el.getBoundingClientRect();
return rect.bottom > top.top && rect.top < top.bottom;
}
showPill(count) {
if (this.scroller.scrollTop < 4 && !this.sections.some((s) => s.stale)) return;
this.pendingNew += count;
fill(this.pill, h('button.btn', {
type: 'button',
onclick: () => {
for (const s of this.sections) if (s.stale) this.reset(s, s.stale);
this.pendingNew = 0;
this.pill.hidden = true;
this.scroller.scrollTo({ top: 0 });
},
}, icon('arrow-left', 's'), t('libreria.nuoviInCima', { n: this.pendingNew })));
this.pill.querySelector('svg').style.transform = 'rotate(90deg)';
this.pill.hidden = false;
}
}
@@ -0,0 +1,21 @@
// Pages that arrive with the second part of the interface (Attività, Importa, Impostazioni, Browser), and the page for
// unknown addresses. The next agent replaces each route of js/routes.js with its own module.
import { h, icon, fill } from '../core/dom.js';
import { withCarried } from '../core/api.js';
import { t } from '../core/text.js';
export default {
mount(page, route) {
const key = route.params.key;
if (key === 'nonTrovata') {
page.title(t('pagine.nonTrovata'));
fill(page.body, h('div.vuoto-pagina', icon('info'), h('h2', t('pagine.nonTrovata')), h('p', t('pagine.nonTrovataTesto')),
h('a.btn', { href: withCarried('/libreria') }, t('pagine.vaiLibreria'))));
return;
}
const title = route.params.section ? `${t('pagine.impostazioni')}: ${t(`pagine.sezioni.${route.params.section}`)}` : t(`pagine.${key}`);
page.title(title);
fill(page.body, h('div.vuoto-pagina.prossimamente', icon('hourglass'), h('h2', title), h('p', t('pagine.prossimamente'))));
},
};
+265
View File
@@ -0,0 +1,265 @@
// Visualizzatore (mockup 02, spec §4.6): covers the whole window; arrows and arrow keys move through the files of the
// series and then to the next entry; Esc closes; videos start muted. The side panel shows the data, the files and the
// provenance, and the actions: «Mostra nella cartella» (desktop) or «Scarica» (browser), «Apri su Instagram» (in
// Alberto's own browser, never in Febe's), «Elimina dalla libreria».
import { api, withCarried } from '../core/api.js';
import { caps, serverNow } from '../core/context.js';
import { h, icon, fill } from '../core/dom.js';
import { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from '../core/text.js';
import { avatar, label, showError, toast } from '../core/ui.js';
import { confirmDelete } from './library.js';
const KIND_ICON = { post: 'image', story: 'circle-dashed', highlight: 'star', tagged: 'square-user', profile: 'circle-user' };
/**
* Opens the viewer on a tile. source: { position(id), neighbor(id, delta), reveal(id) } (the mosaic, or a plain list).
* origin: «Libreria» or the account name. onDeleted(ids): called after a deletion.
*/
export function openViewer({ tile, source, origin, onDeleted }) {
const opener = document.activeElement;
let entry = null;
let fileIndex = 0;
let zoomed = false;
let token = 0;
const where = h('span.dove');
const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x'));
const zoomButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.ingrandisci'), title: t('vis.ingrandisci'), onclick: () => setZoom(!zoomed) }, icon('zoom-in'));
const fullButton = h('button.tondino', {
type: 'button', 'aria-label': t('vis.schermoIntero'), title: t('vis.schermoIntero'),
onclick: () => (document.fullscreenElement ? document.exitFullscreen() : box.requestFullscreen && box.requestFullscreen().catch(() => {})),
}, icon('maximize'));
const prev = h('button.freccia.sx', { type: 'button', 'aria-label': t('vis.precedente'), onclick: () => step(-1) }, icon('chevron-left'));
const next = h('button.freccia.dx', { type: 'button', 'aria-label': t('vis.successivo'), onclick: () => step(1) }, icon('chevron-right'));
const stage = h('div.scena');
const strip = h('div.serie', { role: 'group', 'aria-label': t('vis.serie') });
const panelTop = h('div.alto');
const panelBottom = h('div.basso');
const box = h('div.vis', { role: 'dialog', 'aria-modal': 'true', 'aria-label': t('vis.etichetta') },
h('div.palco',
h('div.palco-testa', closeButton, where, h('div.destra', zoomButton, fullButton)),
h('div', { style: { position: 'relative', flex: '1', minHeight: '0', display: 'flex' } }, prev, stage, next),
strip),
h('aside.scheda', panelTop, panelBottom));
function onKey(e) {
if (document.querySelector('.velo.finestra, .menu')) return; // a dialog or a menu over the viewer has the keys
if (e.target.closest && e.target.closest('input,textarea,select,video')) {
if (e.key !== 'Escape') return;
}
if (e.key === 'Escape') {
if (document.fullscreenElement) return;
e.preventDefault();
close();
} else if (e.key === 'ArrowLeft') {
e.preventDefault();
step(-1);
} else if (e.key === 'ArrowRight') {
e.preventDefault();
step(1);
} else if (e.key === 'Tab') {
const items = [...box.querySelectorAll('button:not([disabled]),a[href],video')].filter((el) => el.offsetParent !== null);
if (!items.length) return;
if (e.shiftKey && document.activeElement === items[0]) {
items[items.length - 1].focus();
e.preventDefault();
} else if (!e.shiftKey && document.activeElement === items[items.length - 1]) {
items[0].focus();
e.preventDefault();
}
}
}
function close() {
document.removeEventListener('keydown', onKey, true);
for (const v of box.querySelectorAll('video')) v.pause();
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
box.remove();
document.body.style.overflow = '';
if (entry && source && source.reveal) source.reveal(entry.id);
if (opener && document.contains(opener)) opener.focus();
}
function setZoom(on) {
zoomed = on;
stage.classList.toggle('ingrandita', on);
zoomButton.setAttribute('aria-pressed', String(on));
}
async function load(id, index = 0) {
const mine = ++token;
try {
const data = await api(`/api/entries/${id}`);
if (mine !== token) return;
entry = data;
fileIndex = index < 0 ? entry.media.length - 1 : Math.min(index, entry.media.length - 1);
draw();
} catch (error) {
showError(error);
}
}
async function step(delta) {
if (!entry) return;
const target = fileIndex + delta;
if (target >= 0 && target < entry.media.length) {
fileIndex = target;
drawMedia();
drawStrip();
drawPanel();
return;
}
if (!source || !source.neighbor) return;
const other = await source.neighbor(entry.id, delta);
if (other) await load(other.id, delta > 0 ? 0 : -1);
}
function draw() {
drawWhere();
drawMedia();
drawStrip();
drawPanel();
}
function drawWhere() {
if (source && source.position) {
const p = source.position(entry.id);
where.textContent = p.index ? t('vis.dove', { origine: origin, n: number(p.index), totale: number(p.total) }) : origin;
} else where.textContent = origin;
}
function drawMedia() {
setZoom(false);
for (const v of stage.querySelectorAll('video')) v.pause();
const media = entry.media[fileIndex];
if (!media) {
fill(stage, h('div.mancante', icon('info', 'l'), h('p', t('vis.eliminato'))));
return;
}
const thumb = media.thumb ? `/api/thumbnails/${media.thumb}` : null;
if (!media.available) {
fill(stage, h('div.mancante', thumb ? h('img', { src: thumb, alt: '' }) : icon('image', 'l'),
h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante'))));
return;
}
const src = `/api/media/${media.id}/file`;
if (media.kind === 'video') {
fill(stage, h('video', { src, poster: thumb, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata', 'aria-label': t('libreria.tipiTessera.' + entry.kind) }));
const video = stage.querySelector('video');
video.muted = true; // spec §10.3: videos start without sound
} else {
const img = h('img', { src, alt: entry.caption ? entry.caption.slice(0, 140) : `@${entry.account.username}` });
img.addEventListener('click', () => setZoom(!zoomed));
fill(stage, img);
}
prev.disabled = false;
next.disabled = false;
}
function drawStrip() {
if (entry.media.length < 2) {
strip.hidden = true;
strip.replaceChildren();
return;
}
strip.hidden = false;
fill(strip, entry.media.map((m, i) => h(`button${i === fileIndex ? '.qui' : ''}`, {
type: 'button',
'aria-label': t('vis.fileN', { n: i + 1, totale: entry.media.length }),
'aria-current': i === fileIndex ? 'true' : null,
onclick: () => {
fileIndex = i;
drawMedia();
drawStrip();
drawPanel();
},
}, m.thumb ? h('img', { src: `/api/thumbnails/${m.thumb}`, alt: '', loading: 'lazy' }) : null, m.kind === 'video' ? icon('play') : null)));
}
function row(term, value) {
return value == null || value === '' ? null : [h('dt', term), h('dd', value)];
}
function drawPanel() {
const a = entry.account;
const media = entry.media[fileIndex];
const today = caps().today;
const kindText = t(`libreria.tipiTessera.${entry.kind}`);
const mediaText = media ? t(media.kind === 'video' ? 'comune.video' : 'comune.foto') : '';
const typeLabel = entry.media.length > 1
? t('vis.tipoFile', { tipo: kindText, media: mediaText, n: fileIndex + 1, totale: entry.media.length })
: t('vis.tipoSingolo', { tipo: kindText, media: mediaText });
const published = `${capitalize(dayName(entry.publishedDay))} ${entry.publishedDay.slice(0, 4)}, ${entry.publishedTime}`;
const downloaded = entry.downloaded ? `${shortDay(entry.downloaded.day)} ${entry.downloaded.day.slice(0, 4)}, ${entry.downloaded.clock}` : null;
fill(panelTop,
h('div.chi-vis', avatar(a.username, 'm', a.avatar), h('div', h('b', `@${a.username}`), a.displayName ? h('span', a.displayName) : null),
a.isFollowed ? label(t('vis.seguito'), 'accento', 'user-check') : null),
h('div.etichette', label(typeLabel, '', KIND_ICON[entry.kind] || 'image'), a.isPrivate ? label(t('vis.privato'), '', 'lock') : null),
h('div.quando', h('b', published), h('span', t('vis.pubblicato', { quando: ago(entry.publishedAt, serverNow(), today, entry.publishedDay) }))),
h('section', h('h3', t('vis.didascalia')), entry.caption ? h('p.didascalia', entry.caption) : h('p.didascalia.muto', t('vis.senzaDidascalia'))),
h('section', h('h3', t('vis.file')), h('dl',
media ? row(t('vis.nome'), media.fileName) : null,
media && media.width && media.height ? row(t('vis.dimensioni'), t('vis.pixel', { l: number(media.width), a: number(media.height) })) : null,
media && media.bytes ? row(t('vis.peso'), bytes(media.bytes)) : null,
media && media.duration ? row(t('vis.durata'), duration(media.duration)) : null,
media ? row(t('vis.cartella'), media.folder) : null,
row(t('vis.codice'), entry.code || entry.instagramId),
entry.author ? row(t('vis.autore'), `@${entry.author}`) : null,
entry.media.length > 1 ? row(t('vis.posizione'), t('vis.posizioneDi', { n: fileIndex + 1, totale: entry.media.length })) : null,
entry.highlights.length ? row(t('vis.raccolte'), entry.highlights.join(', ')) : null)),
h('section', h('h3', t('vis.provenienza')), h('dl',
row(t('vis.origine'), t(entry.provenance === 'imported' ? 'vis.importato' : 'vis.scaricato')),
row(t('vis.quando'), downloaded))));
const c = caps();
const actions = [];
if (media && media.available) {
actions.push(c.showInFolder
? h('button.btn', { type: 'button', onclick: () => showInFolder(media.id) }, icon('folder-open'), t('vis.mostra'))
: h('a.btn', { href: `/api/media/${media.id}/file?download=1`, download: media.fileName || '' }, icon('download'), t('vis.scarica')));
}
if (entry.instagramUrl) {
actions.push(c.openUrlNative
? h('button.btn', { type: 'button', onclick: () => openNative(entry.id) }, icon('external-link'), t('vis.apri'))
: h('a.btn', { href: entry.instagramUrl, target: '_blank', rel: 'noopener noreferrer' }, icon('external-link'), t('vis.apri')));
}
if (entry.state !== 'deleted') {
actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina')));
}
fill(panelBottom, actions);
}
async function showInFolder(mediaId) {
try {
const result = await api('/api/media/show-in-folder', { method: 'POST', body: { mediaId } });
toast(result.message);
} catch (error) {
showError(error);
}
}
async function openNative(id) {
try {
await api(`/api/entries/${id}/open-on-instagram`, { method: 'POST' });
} catch (error) {
showError(error);
}
}
async function remove() {
const id = entry.id;
const following = source && source.neighbor ? (await source.neighbor(id, 1)) || (await source.neighbor(id, -1)) : null;
const removed = await confirmDelete([id]);
if (!removed) return;
if (onDeleted) onDeleted(removed);
if (following) await load(following.id, 0);
else close();
}
document.addEventListener('keydown', onKey, true);
document.body.append(box);
closeButton.focus();
load(tile.id, 0);
void withCarried;
}
+22
View File
@@ -0,0 +1,22 @@
// The pages of Febe. Each entry: a pattern on the Italian address, the item of the sidebar it lights up, and the
// module that draws it (loaded on demand). The server answers every address without an extension with index.html,
// so a new page needs only a line here and its module in js/pages/ (see src/Febe.Web/LEGGIMI.md).
const placeholder = () => import('./pages/placeholder.js');
export const routes = [
{ pattern: /^\/$/, redirect: '/libreria' },
{ pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') },
{ pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.js') },
{ pattern: /^\/account\/(?<id>\d+)(?:\/(?<tab>contenuti|impostazioni|cronologia))?\/?$/, nav: 'account', page: () => import('./pages/account.js') },
{ pattern: /^\/attivita\/?$/, nav: 'attivita', page: placeholder, data: { key: 'attivita' } },
{ pattern: /^\/importa\/?$/, nav: 'importa', page: placeholder, data: { key: 'importa' } },
{ pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' },
{
pattern: /^\/impostazioni\/(?<section>generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/,
nav: 'impostazioni',
page: placeholder,
data: { key: 'impostazioni' },
},
{ pattern: /^\/browser\/?$/, nav: 'attivita', page: placeholder, data: { key: 'browser' } },
];
+18
View File
@@ -0,0 +1,18 @@
// Applies the theme before the first paint (classic script, loaded in <head>): no flash of the wrong colours.
(function () {
var forced = null;
var saved = null;
try {
forced = new URLSearchParams(location.search).get('tema') || sessionStorage.getItem('febe.tema');
} catch (e) {
forced = null;
}
try {
saved = localStorage.getItem('febe.tema');
} catch (e) {
saved = null;
}
var choice = forced === 'chiaro' || forced === 'scuro' ? forced : saved || 'sistema';
var dark = choice === 'scuro' || (choice === 'sistema' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.setAttribute('data-tema', dark ? 'scuro' : 'chiaro');
})();
+488
View File
@@ -0,0 +1,488 @@
{
"lingua": "it",
"app": {
"nome": "Febe",
"salta": "Vai al contenuto",
"dimostrazione": "Dimostrazione",
"titoloPagina": "{pagina} · Febe"
},
"nav": {
"principale": "Navigazione principale",
"libreria": "Libreria",
"account": "Account",
"attivita": "Attività",
"importa": "Importa",
"impostazioni": "Impostazioni",
"fermo": "Serve il tuo intervento"
},
"stato": {
"riquadro": "Stato del motore",
"profiliOggi": "Profili aperti oggi",
"usatiDi": "{usati} di {limite}",
"collegato": "Collegato",
"daCollegare": "Da collegare",
"nessunAccount": "Nessun account",
"verifica": "Verifica richiesta",
"scollegato": "Sessione chiusa",
"nonDisponibile": "Stato del motore non disponibile"
},
"arresto": {
"apriBrowser": "Apri il browser",
"riprendi": "Riprendi",
"riprendiSpento": "«Riprendi» si attiva dopo che hai usato il browser."
},
"tempo": {
"oggi": "oggi",
"ieri": "ieri",
"domani": "domani",
"Oggi": "Oggi",
"Ieri": "Ieri",
"adesso": "adesso",
"minutiFa": "1 min fa|{n} min fa",
"oreFa": "1 ora fa|{n} ore fa",
"giorniFa": "1 giorno fa|{n} giorni fa",
"settimaneFa": "1 settimana fa|{n} settimane fa",
"mesiFa": "1 mese fa|{n} mesi fa",
"anniFa": "1 anno fa|{n} anni fa",
"verso": "verso le {ora}",
"versoUna": "verso l'{ora}",
"alle": "alle {ora}",
"allUna": "all'{ora}",
"il": "il {giorno}",
"giornoOra": "{giorno}, {ora}",
"giorni": ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"],
"mesi": ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"]
},
"unita": {
"byte": "{n} byte",
"kB": "{n} kB",
"MB": "{n} MB",
"GB": "{n} GB"
},
"comune": {
"annulla": "Annulla",
"chiudi": "Chiudi",
"caricamento": "Caricamento…",
"riprova": "Riprova",
"errore": "Febe non ha risposto: controlla che il programma sia acceso, poi riprova.",
"erroreTitolo": "Qualcosa non ha funzionato",
"salvato": "Salvato.",
"menu": "Altre azioni",
"elementi": "1 elemento|{n} elementi",
"account": "1 account|{n} account",
"post": "1 post|{n} post",
"storie": "1 storia|{n} storie",
"file": "1 file|{n} file",
"contenuti": "1 contenuto|{n} contenuti",
"foto": "foto",
"video": "video"
},
"libreria": {
"titolo": "Libreria",
"quanti": "{elementi} di {account}",
"cerca": "Cerca per account o didascalia",
"cercaBreve": "Cerca",
"filtriTipo": "Tipo di contenuto",
"tipi": {
"all": "Tutto",
"photos": "Foto",
"videos": "Video",
"stories": "Storie",
"highlights": "In evidenza",
"tagged": "Taggati"
},
"menuAccount": "Account",
"menuPeriodo": "Periodo",
"menuProvenienza": "Provenienza",
"filtri": "Filtri",
"cercaAccount": "Cerca un account",
"tuttiGliAccount": "Tutti gli account",
"accountScelti": "{n} account",
"nessunAccount": "Nessun account con questo nome",
"periodi": {
"qualsiasi": "Qualsiasi data",
"settimana": "Ultimi 7 giorni",
"mese": "Ultimi 30 giorni",
"anno": "Quest'anno",
"annoScorso": "L'anno scorso",
"dal": "Dal",
"al": "al",
"applica": "Mostra questo periodo",
"date": "Dal {dal} al {al}"
},
"provenienze": {
"tutte": "Qualsiasi provenienza",
"downloaded": "Scaricati da Instagram",
"imported": "Importati"
},
"grandezza": "Grandezza delle tessere",
"piccole": "Tessere più piccole",
"grandi": "Tessere più grandi",
"seleziona": "Seleziona",
"fine": "Fine",
"giornoNuovi": "{giorno}, {n}",
"nuoviOggi": "1 nuovo elemento|{n} nuovi elementi",
"elementiGiorno": "1 elemento|{n} elementi",
"storieGiorno": "1 storia|{n} storie",
"nuoviInCima": "1 nuovo elemento in cima|{n} nuovi elementi in cima",
"vuota": "La libreria è ancora vuota",
"vuotaTesto": "Aggiungi gli account da seguire: i loro contenuti arrivano qui poco per volta.",
"nessuno": "Nessun elemento con questi filtri",
"nessunoTesto": "Cambia o togli un filtro per vedere altro.",
"togliFiltri": "Togli i filtri",
"tessera": "{tipo} di @{account}, {quando}",
"tesseraFile": "{n} file",
"tesseraDurata": "video di {durata}",
"scegliTessera": "Scegli questo elemento",
"tipiTessera": {
"post": "Post",
"story": "Storia",
"highlight": "Contenuto in evidenza",
"tagged": "Post in cui è taggato",
"profile": "Foto del profilo"
}
},
"selezione": {
"scelti": "1 elemento scelto|{n} elementi scelti",
"nessuno": "Tocca le tessere per sceglierle",
"esporta": "Esporta l'elenco",
"elimina": "Elimina 1 elemento|Elimina {n} elementi",
"annulla": "Annulla la scelta",
"esportato": "Elenco esportato: il file CSV è nei download del browser."
},
"elimina": {
"titolo": "Eliminare questo elemento dalla libreria?|Eliminare {n} elementi dalla libreria?",
"testo": "I file vengono cancellati dal disco e non si recuperano. Febe ricorda la scelta: l'elemento resta nell'elenco come «eliminato» e non viene scaricato di nuovo.|I file vengono cancellati dal disco e non si recuperano. Febe ricorda la scelta: gli elementi restano nell'elenco come «eliminati» e non vengono scaricati di nuovo.",
"conferma": "Elimina dalla libreria",
"torna": "Eliminalo e lascia che torni|Eliminali e lascia che tornino",
"tornaSpiega": "Con «lascia che torni» Febe dimentica l'elemento: se è ancora su Instagram, al prossimo controllo lo scarica di nuovo."
},
"vis": {
"etichetta": "Visualizzatore",
"chiudi": "Chiudi (Esc)",
"dove": "{origine}, elemento {n} di {totale}",
"precedente": "Precedente",
"successivo": "Successivo",
"ingrandisci": "Ingrandisci",
"schermoIntero": "Schermo intero",
"serie": "File della serie",
"fileN": "File {n} di {totale}",
"didascalia": "Didascalia",
"senzaDidascalia": "Senza didascalia.",
"dati": "Dati",
"file": "File",
"provenienza": "Provenienza",
"nome": "Nome",
"dimensioni": "Dimensioni",
"pixel": "{l} × {a} pixel",
"peso": "Peso",
"durata": "Durata",
"cartella": "Cartella",
"codice": "Codice",
"autore": "Autore",
"posizione": "Posizione",
"posizioneDi": "{n} di {totale}",
"raccolte": "Raccolte",
"origine": "Origine",
"quando": "Quando",
"scoperto": "Trovato",
"scaricato": "Scaricato da Instagram",
"importato": "Importato",
"pubblicato": "Pubblicato {quando}",
"mostra": "Mostra nella cartella",
"scarica": "Scarica",
"apri": "Apri su Instagram",
"elimina": "Elimina dalla libreria",
"mancante": "Il file non è sul disco: forse è stato spostato o cancellato fuori da Febe.",
"videoMancante": "Il video non è sul disco: qui si vede solo la sua copertina.",
"tipoFile": "{tipo}, {media} {n} di {totale}",
"tipoSingolo": "{tipo}, {media}",
"seguito": "Seguito",
"privato": "Profilo privato",
"pubblico": "Profilo pubblico",
"cartellaAperta": "Cartella aperta.",
"eliminato": "Questo elemento è stato eliminato dalla libreria."
},
"account": {
"titolo": "Account",
"quanti": "{account}, {tenuti} tenuti aggiornati",
"cerca": "Cerca un account",
"aggiungi": "Aggiungi account",
"filtri": {
"tutti": "Tutti",
"upToDate": "Aggiornati",
"backfilling": "Storico in corso",
"paused": "In pausa",
"archiveOnly": "Solo archivio",
"needsAttention": "Da controllare"
},
"colonne": {
"account": "Account",
"raccoglie": "Raccoglie",
"stato": "Stato",
"ultimo": "Ultimo controllo",
"prossimo": "Prossimo",
"libreria": "In libreria",
"tieni": "Tieni aggiornato",
"azioni": "Azioni"
},
"ordina": {
"etichetta": "Ordina",
"ultimo": "Ordina per ultimo controllo",
"prossimo": "Ordina per prossimo controllo",
"nome": "Ordina per nome",
"libreria": "Ordina per elementi in libreria",
"aggiunta": "Ordina per data di aggiunta"
},
"stati": {
"upToDate": "Aggiornato",
"backfilling": "Storico in corso",
"paused": "In pausa",
"archiveOnly": "Solo archivio",
"unreachable": "Non raggiungibile"
},
"etichette": {
"tu": "Tu",
"privato": "Privato",
"pubblico": "Pubblico",
"seguito": "Seguito",
"nonSeguito": "Non seguito",
"archivio": "Solo archivio"
},
"sotto": {
"tuo": "Il tuo profilo",
"nuoviPost": "1 nuovo post oggi|{n} nuovi post oggi",
"nuoveStorie": "1 nuova storia oggi|{n} nuove storie oggi",
"nuoviEntrambi": "{post} e {storie} oggi",
"post": "1 nuovo post|{n} nuovi post",
"storie": "1 nuova storia|{n} nuove storie",
"storico": "{fatti} di {totale} post",
"storicoSenzaTotale": "{fatti} post finora",
"riprendeDomani": "{testo}, riprende domani",
"pausa": "Messo in pausa da te il {giorno}",
"pausaSenzaData": "Messo in pausa da te",
"privateNotFollowed": "È privato e non lo segui",
"notFound": "Il profilo non esiste più",
"blocked": "Il profilo non è visibile",
"renamed": "Ha cambiato nome: indica il nuovo",
"rinominato": "Prima si chiamava @{nome}",
"formato": "Risposte in un formato non riconosciuto",
"maiContattato": "Mai contattato su Instagram"
},
"raccoglie": {
"photos": "Foto dei post",
"videos": "Video e reel",
"stories": "Storie",
"highlights": "Storie in evidenza",
"tagged": "Post in cui è taggato",
"attivo": "{tipo}: sì",
"spento": "{tipo}: no"
},
"tieniEtichetta": "Tieni aggiornato @{nome}",
"sospeso": "Sospeso",
"menu": {
"controlla": "Controlla ora",
"pausa": "Metti in pausa",
"riattiva": "Riattiva",
"apri": "Apri su Instagram",
"rimuovi": "Rimuovi…"
},
"vuoto": "Nessun account ancora",
"vuotoTesto": "Aggiungi i profili da archiviare: dai profili che segui o per nome utente.",
"nessunoFiltro": "Nessun account in questo gruppo",
"rimuovi": {
"titolo": "Rimuovere @{nome}?",
"testo": "Febe smette di controllarlo. Che cosa vuoi fare dei suoi file?",
"tieni": "Tieni i file",
"tieniSpiega": "L'account resta in libreria come «Solo archivio» e non viene più contattato.",
"elimina": "Elimina anche i file",
"eliminaSpiega": "Cancella dal disco {elementi} di questo account. Non si recuperano.",
"confermaTieni": "Rendi «Solo archivio»",
"confermaElimina": "Rimuovi e cancella i file"
},
"controlla": {
"titolo": "Controllare adesso?",
"conferma": "Controlla adesso @{nome}"
}
},
"aggiungi": {
"titolo": "Aggiungi account",
"seguiti": "Dai profili che segui",
"perNome": "Per nome utente",
"cerca": "Cerca tra i profili che segui",
"selezionaTutti": "Seleziona tutti",
"togliTutti": "Togli tutti",
"giaPresente": "Già in Febe",
"privato": "Privato",
"lettoIl": "Elenco letto il {giorno}",
"maiLetto": "L'elenco dei profili che segui non è ancora stato letto.",
"rileggi": "Rileggi l'elenco",
"leggi": "Leggi l'elenco",
"avanzamento": "Letti {n} profili, continuo alla prossima sessione",
"inAttesa": "Lettura chiesta: comincia alla prossima sessione",
"rilettura": "Febe rilegge l'elenco a ritmo umano, dentro i tetti: può servire più di una sessione.",
"nessunSeguito": "Nessun profilo con questo nome nell'elenco.",
"area": "Nomi utente o indirizzi dei profili",
"areaAiuto": "Uno per riga: nome.utente, @nome.utente oppure instagram.com/nome.utente",
"riconosciuti": "1 nome pronto|{n} nomi pronti",
"presenti": "1 già in Febe|{n} già in Febe",
"riga": "Riga {n}: {motivo}",
"perScelti": "Per l'account scelto|Per i {n} account scelti",
"perNessuno": "Scegli gli account a sinistra",
"potraiCambiare": "Potrai cambiare tutto dopo, account per account.",
"partenze": {
"everything": "Scarica tutto e tieni aggiornato",
"everythingSpiega": "Lo storico arriva poco per volta, poi solo le novità.",
"newOnly": "Solo le novità da oggi",
"newOnlySpiega": "Niente storico: parte da ciò che pubblica da oggi.",
"storiesOnly": "Solo le storie",
"storiesOnlySpiega": "Storie del giorno e storie in evidenza."
},
"quanto": "Quanto indietro nel tempo",
"profondita": {
"all": "Tutti i contenuti",
"last50": "Gli ultimi 50 post",
"last200": "Gli ultimi 200 post",
"last1000": "Gli ultimi 1.000 post",
"year": "Dall'inizio dell'anno"
},
"info": "Lo storico arriva poco per volta: al massimo {n} post al giorno per account.",
"infoNovita": "I primi controlli partono alla prossima sessione, dentro la fascia oraria.",
"conferma": "Aggiungi 1 account|Aggiungi {n} account",
"aggiunti": "1 account aggiunto.|{n} account aggiunti."
},
"scheda": {
"indietro": "Account",
"linguette": {
"contenuti": "Contenuti",
"impostazioni": "Impostazioni",
"cronologia": "Cronologia"
},
"numeri": {
"elementi": "elementi",
"post": "post",
"postDi": "{fatti} di {totale}",
"postScaricati": "post scaricati",
"storie": "storie",
"raccolte": "raccolte in evidenza",
"taggati": "taggati"
},
"tipi": {
"posts": "Post",
"stories": "Storie",
"highlights": "In evidenza",
"tagged": "Taggati",
"profile": "Profilo"
},
"apriProfilo": "Apri il profilo su Instagram",
"nessunContenuto": "Nessun contenuto di questo tipo, per ora.",
"raccolta": "{titolo}",
"raccoltaTolta": "Non è più sul profilo",
"nonTrovato": "Account non trovato",
"nonTrovatoTesto": "Forse è stato rimosso. Torna all'elenco degli account."
},
"impAccount": {
"tieni": "Tieni aggiornato",
"tieniAiuto": "Febe torna a controllare questo account e scarica i nuovi contenuti poco dopo la pubblicazione. Con «no» fa un solo scaricamento, poi lo mette in pausa.",
"frequenza": "Frequenza dei controlli",
"frequenze": {
"low": "Bassa",
"normal": "Normale",
"high": "Alta",
"custom": "Su misura"
},
"suMisuraPost": "Controlla i post ogni",
"suMisuraStorie": "Storie, al massimo ogni",
"ore": "ore",
"cosa": "Cosa scaricare",
"cosaAiuto": "Quello che togli resta in libreria, ma non viene più aggiornato.",
"tipi": {
"photos": "Foto dei post",
"videos": "Video e reel",
"stories": "Storie",
"highlights": "Storie in evidenza",
"tagged": "Post in cui è taggato",
"profilePicture": "Foto del profilo"
},
"limiti": "Limiti per questo account",
"limitiAiuto": "Valgono insieme ai limiti generali: vince sempre il più stretto.",
"quanto": "Quanto indietro nel tempo",
"profondita": {
"all": "Tutti i contenuti",
"lastPosts": "Gli ultimi post",
"fromDate": "Da una data"
},
"quantiPost": "Quanti post",
"dalGiorno": "Dal giorno",
"storicoGiorno": "Storico, massimo al giorno",
"post": "post",
"saltaVideo": "Salta i video oltre",
"mb": "MB",
"nessunLimite": "Nessun limite",
"videoStorie": "Scarica anche i video delle storie",
"cartella": "Cartella",
"cartellaAiuto": "Se la lasci com'è, i file vanno nella libreria, in una cartella con il nome dell'account.",
"cambia": "Cambia…",
"predefinita": "Usa la cartella predefinita",
"cartellaDocker": "In Docker le cartelle si cambiano dal contenitore: qui sono in sola lettura.",
"piano": "Con queste impostazioni",
"caricoMisura": "{usati} dei {totale} disponibili ogni giorno",
"modifiche": "Modifiche non salvate",
"annulla": "Annulla le modifiche",
"salva": "Salva le impostazioni",
"salvate": "Impostazioni di @{nome} salvate.",
"archivio": "«Solo archivio»: Febe non contatta questo account. Le impostazioni valgono se lo riattivi.",
"esci": "Hai modifiche non salvate. Vuoi lasciarle?",
"lascia": "Lascia le modifiche"
},
"cronologia": {
"titolo": "Cronologia dei controlli",
"vuota": "Nessun controllo registrato per questo account.",
"altri": "Mostra i controlli precedenti",
"ricette": {
"ProfileCheck": "Controllo del profilo",
"AccountStories": "Storie",
"Backfill": "Storico",
"FollowingSweep": "Giro dei profili che segui",
"Highlight": "Raccolta in evidenza",
"Tagged": "Taggati",
"Reels": "Reel",
"SinglePost": "Post singolo",
"FollowingList": "Elenco dei profili che segui",
"pausa": "Messo in pausa",
"altro": "Evento"
},
"esiti": {
"success": "Scaricato",
"info": "Fatto",
"warning": "Da controllare",
"error": "Non riuscito"
}
},
"pagine": {
"attivita": "Attività",
"importa": "Importa",
"impostazioni": "Impostazioni",
"browser": "Browser di Febe",
"sezioni": {
"generali": "Generali",
"limiti": "Limiti e comportamento",
"collegamento": "Collegamento a Instagram",
"notifiche": "Notifiche",
"dati": "Dati e copie di sicurezza",
"informazioni": "Informazioni"
},
"prossimamente": "Questa pagina arriva con la seconda parte dell'interfaccia.",
"nonTrovata": "Pagina non trovata",
"nonTrovataTesto": "L'indirizzo non corrisponde a nessuna pagina di Febe.",
"vaiLibreria": "Vai alla libreria"
},
"accesso": {
"titolo": "Accedi a Febe",
"password": "Password",
"entra": "Entra",
"aiuto": "È la password scelta per il contenitore (FEBE_PASSWORD).",
"sbagliata": "Password sbagliata.",
"uscita": "Esci"
}
}
+219
View File
@@ -0,0 +1,219 @@
using System.Net;
using System.Text.Json;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Engine;
using Febe.Web.Library;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>The accounts API (spec §4.2, §4.4, §7.8).</summary>
[TestClass]
public sealed class AccountsApiTests
{
[TestMethod]
public async Task TheListCountsEveryGroupAndTheSwitchActsAtOnce()
{
var engine = new RecordingEngine();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IEngineControl>(engine));
var marta = await server.AddAccountWithEntriesAsync("marta.demo", 5, Make.T0, TimeSpan.FromHours(3));
var paused = await server.Db.Accounts.AddAsync(Make.Account("trattoria.demo") with { State = AccountState.Paused, KeepUpdated = false });
await server.Db.Accounts.AddAsync(Make.Account("chiuso.demo") with { State = AccountState.Unreachable, UnreachableReason = UnreachableReason.PrivateNotFollowed, KeepUpdated = false });
await server.Db.Accounts.AddAsync(Make.Account("estate.2019.demo") with { InstagramId = null, State = AccountState.ArchiveOnly, KeepUpdated = false });
await server.Db.Accounts.AddAsync(Make.Account("studio.lumen.demo") with { State = AccountState.Backfilling, PostCount = 1280 });
var list = await server.GetJsonAsync("/api/accounts");
var counts = list.GetProperty("counts");
Assert.AreEqual(5, counts.Int("all"));
Assert.AreEqual(counts.Int("all"), counts.Int("upToDate") + counts.Int("backfilling") + counts.Int("paused") + counts.Int("archiveOnly") + 1, "plus one unreachable");
Assert.AreEqual(1, counts.Int("needsAttention"));
Assert.AreEqual(2, counts.Int("keptUpdated"));
var row = list.Items("accounts").Single(a => a.Str("username") == "marta.demo");
Assert.AreEqual(5, row.Int("inLibrary"));
Assert.IsTrue(row.GetProperty("types").Bool("photos"));
Assert.IsFalse(row.GetProperty("types").Bool("tagged"));
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/keep-updated", new { value = false });
Assert.AreEqual(HttpStatusCode.OK, status);
var stored = await server.Db.Accounts.GetAsync(marta.Id);
Assert.IsFalse(stored!.KeepUpdated);
Assert.AreEqual(AccountState.Paused, stored.State, "«no»: the single download is done, the account rests");
Assert.AreEqual(1, engine.AccountsChanged);
(status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{paused.Id}/keep-updated", new { value = true });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual(AccountState.Backfilling, (await server.Db.Accounts.GetAsync(paused.Id))!.State, "its history was never completed");
var archive = list.Items("accounts").Single(a => a.Str("username") == "estate.2019.demo");
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{archive.Long("id")}/keep-updated", new { value = true })).Status);
}
[TestMethod]
public async Task CheckNowGoesThroughTheEngineWithItsConfirmation()
{
var engine = new RecordingEngine();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IEngineControl>(engine));
var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var (_, first) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/check-now", new { });
Assert.AreEqual("needsConfirmation", first.Str("status"));
Assert.AreEqual("gettone-1", first.Str("token"));
var (_, second) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/check-now", new { token = "gettone-1" });
Assert.AreEqual("queued", second.Str("status"));
CollectionAssert.AreEqual(new[] { (account.Id, (string?)null), (account.Id, (string?)"gettone-1") }, engine.Checks);
}
[TestMethod]
public async Task RemovingKeepsTheFilesByDefaultAndDeletesThemOnlyWhenAsked()
{
await using var server = await WebTestServer.StartAsync();
var keep = await server.AddAccountWithEntriesAsync("marta.demo", 3, Make.T0, TimeSpan.FromHours(3));
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{keep.Id}/remove", new { deleteFiles = false });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual("archived", result.Str("outcome"));
Assert.AreEqual(AccountState.ArchiveOnly, (await server.Db.Accounts.GetAsync(keep.Id))!.State);
Assert.HasCount(3, await server.Db.Entries.ListByAccountAsync(keep.Id));
var gone = await server.Db.Accounts.AddAsync(Make.Account("luca.viaggi.demo"));
var folder = server.Library.Layout.AccountFolder(gone);
Directory.CreateDirectory(Path.Combine(folder, "post"));
await File.WriteAllBytesAsync(Path.Combine(folder, "post", "a.jpg"), [1, 2, 3]);
await server.Db.Entries.AddAsync(Make.Entry(gone.Id, "x1", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(5), "post/a.jpg")]);
(status, result) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{gone.Id}/remove", new { deleteFiles = true });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual("removed", result.Str("outcome"));
Assert.AreEqual(1, result.Int("deletedEntries"));
Assert.IsNull(await server.Db.Accounts.GetAsync(gone.Id));
Assert.IsFalse(File.Exists(Path.Combine(folder, "post", "a.jpg")));
var mine = await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{mine.Id}/remove", new { deleteFiles = false })).Status);
}
[TestMethod]
public async Task SettingsAreValidatedSavedAndExplainedByThePlan()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.Db.Accounts.AddAsync(Make.Account("studio.lumen.demo") with { PostCount = 1280, State = AccountState.Backfilling });
var detail = await server.GetJsonAsync($"/api/accounts/{account.Id}");
var settings = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(detail.GetProperty("settings").GetRawText())!;
Assert.AreEqual("normal", settings["frequency"].GetString());
Assert.IsTrue(detail.GetProperty("plan").Items("lines").Any(l => l.Str("key") == "backfill" && l.Str("text").Contains("mancano 1.280 post", StringComparison.Ordinal)));
StringAssert.Contains(detail.GetProperty("plan").Str("frequencyHint"), "ogni 3 ore");
var custom = new Dictionary<string, object?>(settings.ToDictionary(k => k.Key, k => (object?)k.Value))
{
["frequency"] = "custom",
["customPostHours"] = 0.2,
};
var (status, error) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/plan", custom);
Assert.AreEqual(HttpStatusCode.BadRequest, status);
StringAssert.Contains(error.Str("message"), "Su misura");
custom["customPostHours"] = 2;
custom["customStoryHours"] = 4;
var (planStatus, plan) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/plan", custom);
Assert.AreEqual(HttpStatusCode.OK, planStatus);
StringAssert.Contains(plan.Str("frequencyHint"), "ogni 2 ore");
Assert.AreEqual(Frequency.Normal, (await server.Db.Accounts.GetAsync(account.Id))!.Frequency, "the plan never saves");
custom["maxVideoMb"] = 200;
custom["depth"] = "lastPosts";
custom["lastPosts"] = 500;
var (saveStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", custom);
Assert.AreEqual(HttpStatusCode.OK, saveStatus);
Assert.AreEqual("custom", saved.GetProperty("settings").Str("frequency"));
var stored = (await server.Db.Accounts.GetAsync(account.Id))!;
Assert.AreEqual(TimeSpan.FromHours(2), stored.CustomPostInterval);
Assert.AreEqual(200L * 1024 * 1024, stored.Limits.MaxVideoBytes);
Assert.AreEqual(500, stored.Limits.LastPosts);
custom["folder"] = "/altrove/foto";
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", custom)).Status,
"in Docker (the default shell of the tests) folders are read-only");
}
[TestMethod]
public async Task AccountsAreAddedFromTheFollowedListOrByNameWithAStartingPoint()
{
await using var server = await WebTestServer.StartAsync();
await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
await server.Db.Following.UpsertAsync(
[
new FollowingRecord { InstagramId = "77", Username = "anna.orto.demo", DisplayName = "Anna", IsPrivate = true, ReadAt = Make.T0 },
new FollowingRecord { InstagramId = "78", Username = "marta.demo", DisplayName = "Marta", ReadAt = Make.T0 },
]);
var following = await server.GetJsonAsync("/api/following");
Assert.AreEqual(2, following.Int("total"));
Assert.AreEqual("2026-10-13", following.Str("readDay"));
Assert.IsFalse(following.Bool("inProgress"));
Assert.AreEqual(300, following.Int("backfillPerDay"));
Assert.AreEqual(JsonValueKind.Number, following.Items("profiles").Single(p => p.Str("username") == "marta.demo").GetProperty("accountId").ValueKind, "already present");
var (_, parsed) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts/parse", new { text = "@anna.orto.demo\nhttps://www.instagram.com/Nuovo.Profilo/?hl=it\nmarta.demo\ninstagram.com/p/DBx3kQ2/\nnome con spazi\n\nanna.orto.demo" });
var names = parsed.Items("names").ToList();
CollectionAssert.AreEqual(new[] { "anna.orto.demo", "nuovo.profilo", "marta.demo" }, names.Select(n => n.Str("username")).ToList());
Assert.IsTrue(names[0].Bool("followed"));
Assert.IsTrue(names[2].Bool("present"));
Assert.HasCount(3, parsed.Items("problems").ToList(), "a post address, a name with spaces, a repeated line");
var (status, added) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "anna.orto.demo", "nuovo.profilo", "marta.demo" }, start = "everything", depth = "lastPosts", lastPosts = 200 });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual(2, added.Int("added"));
var anna = (await server.Db.Accounts.FindByUsernameAsync("anna.orto.demo"))!;
Assert.IsTrue(anna.IsFollowed);
Assert.IsTrue(anna.IsPrivate);
Assert.AreEqual("77", anna.InstagramId);
Assert.AreEqual(AccountState.Backfilling, anna.State);
Assert.AreEqual(200, anna.Limits.LastPosts);
(status, added) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "solo.storie.demo" }, start = "storiesOnly" });
Assert.AreEqual(1, added.Int("added"));
var stories = (await server.Db.Accounts.FindByUsernameAsync("solo.storie.demo"))!;
Assert.AreEqual(ContentTypes.Stories | ContentTypes.Highlights, stories.ContentTypes);
Assert.AreEqual(AccountState.UpToDate, stories.State);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "x.demo" }, start = "tutto" })).Status);
}
[TestMethod]
public void UserNamesAndProfileAddressesAreRecognizedOnePerLine()
{
var (names, problems) = UsernameParser.Parse("marta.demo\r\n@Luca.Viaggi\n instagram.com/studio.lumen.demo \nhttps://www.instagram.com/reel/abc/\nhttps://esempio.it/marta\n.punto\ndue..punti\n" + new string('a', 31));
CollectionAssert.AreEqual(new[] { "marta.demo", "luca.viaggi", "studio.lumen.demo" }, names.Select(n => n.Username).ToList());
Assert.HasCount(5, problems);
Assert.IsTrue(problems.All(p => p.Reason.Length > 10), "every refusal says why");
Assert.IsEmpty(UsernameParser.Parse(" \n\n").Names);
}
/// <summary>An engine that records the commands of the interface.</summary>
private sealed class RecordingEngine : IEngineControl
{
public List<(long, string?)> Checks { get; } = [];
public int AccountsChanged { get; private set; }
public Task PauseAsync(CancellationToken ct) => Task.CompletedTask;
public Task<ResumeResult> ResumeAsync(CancellationToken ct) => Task.FromResult(new ResumeResult(true, "Ripreso."));
public Task<CheckNowResult> CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct)
{
Checks.Add((accountId, confirmationToken));
return Task.FromResult(confirmationToken is null
? new CheckNowResult(CheckNowStatus.NeedsConfirmation, "Fuori fascia: confermi?", "gettone-1")
: new CheckNowResult(CheckNowStatus.Queued, "Confermato."));
}
public Task RequestFollowingListAsync(CancellationToken ct) => Task.CompletedTask;
public Task NotifyAccountsChangedAsync(CancellationToken ct)
{
AccountsChanged++;
return Task.CompletedTask;
}
}
}
+287
View File
@@ -0,0 +1,287 @@
using System.Net;
using System.Text.Json;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
/// <summary>
/// Demo mode (spec §10.6): the seeded library is coherent (the counts add up, times are plausible), every path lives
/// in the temporary folder, and the scenes chosen by address change what the engine reports.
/// </summary>
[TestClass]
public sealed class DemoTests
{
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");
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();
var root = s_demo?.Root;
if (s_demo is not null)
{
await s_demo.DisposeAsync();
}
if (root is not null)
{
Assert.IsFalse(Directory.Exists(root), "the temporary folder of the demo is removed at the end");
}
s_temp?.Dispose();
}
private static async Task<JsonElement> GetAsync(string path)
{
using var response = await Client.GetAsync(path);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
[TestMethod]
public async Task TheAccountsAreTheDemoOnesInEveryStateAndTheirCountsAddUp()
{
var list = await GetAsync("/api/accounts");
var rows = list.Items("accounts").ToList();
var counts = list.GetProperty("counts");
Assert.HasCount(38, rows);
Assert.AreEqual(Demo.World.Accounts, rows.Count);
Assert.AreEqual(rows.Count, counts.Int("all"));
var mine = rows.Where(r => r.Bool("isMine")).ToList();
Assert.HasCount(1, mine);
Assert.AreEqual("tuo.profilo", mine[0].Str("username"));
Assert.AreEqual(Demo.World.MineId, mine[0].Long("id"));
foreach (var row in rows.Where(r => !r.Bool("isMine")))
{
Assert.EndsWith(".demo", row.Str("username"), "demo accounts are recognizable as such");
}
var states = rows.GroupBy(r => r.Str("state")).ToDictionary(g => g.Key, g => g.Count());
foreach (var state in new[] { "upToDate", "backfilling", "paused", "archiveOnly", "unreachable" })
{
Assert.IsTrue(states.ContainsKey(state), $"no account in state {state}");
}
Assert.AreEqual(states["upToDate"], counts.Int("upToDate"));
Assert.AreEqual(states["backfilling"], counts.Int("backfilling"));
Assert.AreEqual(states["paused"], counts.Int("paused"));
Assert.AreEqual(states["archiveOnly"], counts.Int("archiveOnly"));
Assert.AreEqual(rows.Count(r => r.Bool("needsAttention")), counts.Int("needsAttention"));
Assert.AreEqual(rows.Count(r => r.Bool("keptUpdated")), counts.Int("keptUpdated"));
Assert.AreEqual(rows.Count, states.Values.Sum());
// Backfill as in mockup 03: «340 di 1.280 post».
var lumen = rows.Single(r => r.Str("username") == "studio.lumen.demo");
Assert.AreEqual("backfilling", lumen.Str("state"));
Assert.AreEqual(340, lumen.Int("posts"));
Assert.AreEqual(1280, lumen.GetProperty("postCount").GetInt32());
// The library holds exactly what the accounts hold, and the days add up to the same total.
var days = await GetAsync("/api/library/days");
var inLibrary = rows.Sum(r => r.Int("inLibrary"));
Assert.AreEqual(Demo.World.Entries, days.Int("entries"));
Assert.AreEqual(inLibrary, days.Int("entries"));
Assert.AreEqual(days.Int("entries"), days.Items("days").Sum(d => d.Int("count")));
Assert.IsGreaterThan(10_000, inLibrary, "thousands of entries, so the mosaic is exercised for real");
// Each account card agrees with its row.
foreach (var row in rows.Where(r => r.Int("inLibrary") > 0).Take(12))
{
var detail = await GetAsync($"/api/accounts/{row.Long("id")}");
var stats = detail.GetProperty("stats");
Assert.AreEqual(row.Int("inLibrary"), stats.Int("entries"), row.Str("username"));
Assert.AreEqual(stats.Int("entries"), stats.Int("posts") + stats.Int("stories") + stats.Int("highlightItems") + stats.Int("tagged"), row.Str("username"));
Assert.AreEqual(row.Int("posts"), stats.Int("posts"), row.Str("username"));
}
}
[TestMethod]
public async Task TheLibraryPagesThroughEveryEntryWithPlausibleTimesAndEveryKind()
{
var days = await GetAsync("/api/library/days");
var now = days.Long("now");
var total = days.Int("entries");
var seen = new HashSet<long>();
var kinds = new HashSet<string>();
var provenances = new HashSet<string>();
var multiFile = 0;
var videos = 0;
long previous = long.MaxValue;
string? cursor = null;
var pages = 0;
do
{
var page = await GetAsync("/api/library?limit=600" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor)));
foreach (var tile in page.Items("tiles"))
{
Assert.IsTrue(seen.Add(tile.Long("id")), "every entry appears once");
var published = tile.Long("publishedAt");
Assert.IsLessThanOrEqualTo(now, published, "nothing is published in the future");
Assert.IsLessThanOrEqualTo(previous, published, "newest first");
previous = published;
kinds.Add(tile.Str("kind"));
provenances.Add(tile.Str("provenance"));
multiFile += tile.Int("files") > 1 ? 1 : 0;
if (tile.GetProperty("cover").ValueKind == JsonValueKind.Object && tile.GetProperty("cover").Str("kind") == "video")
{
videos++;
}
}
cursor = page.GetProperty("older").ValueKind == JsonValueKind.String ? page.Str("older") : null;
pages++;
}
while (cursor is not null && pages < 100);
Assert.AreEqual(total, seen.Count, "paging reaches every entry of the day counts");
foreach (var kind in new[] { "post", "story", "highlight", "tagged" })
{
Assert.Contains(kind, kinds);
}
Assert.Contains("imported", provenances);
Assert.Contains("downloaded", provenances);
Assert.IsGreaterThan(0, multiFile, "some posts have more files");
Assert.IsGreaterThan(0, videos, "some entries are videos");
}
[TestMethod]
public async Task EntriesAreDiscoveredAfterPublicationAndTheirFilesLiveInTheTemporaryFolder()
{
var page = await GetAsync("/api/library?limit=400");
var checkedPhotos = 0;
var checkedVideos = 0;
foreach (var tile in page.Items("tiles").Where((_, i) => i % 8 == 0))
{
var entry = await GetAsync($"/api/entries/{tile.Long("id")}");
Assert.IsGreaterThanOrEqualTo(entry.Long("publishedAt"), entry.GetProperty("discovered").Long("ms"), "found after publication");
if (entry.GetProperty("downloaded").ValueKind == JsonValueKind.Object)
{
Assert.IsGreaterThanOrEqualTo(entry.GetProperty("discovered").Long("ms"), entry.GetProperty("downloaded").Long("ms"));
}
foreach (var media in entry.Items("media"))
{
using var file = await Client.GetAsync($"/api/media/{media.Long("id")}/file");
if (media.Str("kind") == "photo")
{
Assert.AreEqual(HttpStatusCode.OK, file.StatusCode);
Assert.AreEqual("image/jpeg", file.Content.Headers.ContentType?.MediaType);
var bytes = await file.Content.ReadAsByteArrayAsync();
Assert.IsTrue(bytes.Length > 3 && bytes[0] == 0xFF && bytes[1] == 0xD8, "a real JPEG");
checkedPhotos++;
}
else
{
// Videos have only their cover in the demo.
Assert.AreEqual(HttpStatusCode.NotFound, file.StatusCode);
checkedVideos++;
}
}
}
Assert.IsGreaterThan(0, checkedPhotos);
Assert.IsGreaterThan(0, checkedVideos + checkedPhotos);
var root = Path.GetFullPath(Demo.Root) + Path.DirectorySeparatorChar;
Assert.IsNotEmpty(Demo.World.Pictures);
foreach (var path in Demo.World.Pictures.Values)
{
Assert.StartsWith(root, Path.GetFullPath(path), "demo files never leave the temporary folder");
Assert.IsTrue(File.Exists(path), path);
}
var thumb = page.Items("tiles").Select(t => t.GetProperty("cover")).First(c => c.ValueKind == JsonValueKind.Object && c.GetProperty("thumb").ValueKind == JsonValueKind.String).Str("thumb");
using var thumbnail = await Client.GetAsync($"/api/thumbnails/{thumb}");
Assert.AreEqual(HttpStatusCode.OK, thumbnail.StatusCode);
}
[TestMethod]
public async Task ScenesChangeWhatTheEngineReports()
{
var normal = await GetAsync("/api/engine?scena=normale");
Assert.AreEqual(JsonValueKind.Null, normal.GetProperty("snapshot").GetProperty("banner").ValueKind);
Assert.AreEqual("connected", normal.GetProperty("connection").Str("state"));
CollectionAssert.Contains(new[] { "Resting", "OutsideWindow" }, normal.GetProperty("snapshot").Str("mode"));
var session = await GetAsync("/api/engine?scena=sessione");
Assert.AreEqual("InSession", session.GetProperty("snapshot").Str("mode"));
var stopped = await GetAsync("/api/engine?scena=fermo");
Assert.AreEqual("StoppedForVerification", stopped.GetProperty("snapshot").Str("mode"));
Assert.AreEqual(JsonValueKind.Object, stopped.GetProperty("snapshot").GetProperty("banner").ValueKind);
Assert.AreEqual("verification", stopped.GetProperty("connection").Str("state"));
// The scene also travels in a header (the interface sends it on every call).
using var request = new HttpRequestMessage(HttpMethod.Get, "/api/engine");
request.Headers.Add(DemoRequest.SceneHeader, "scollegato");
using var response = await Client.SendAsync(request);
using var disconnected = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.AreEqual("NotConnected", disconnected.RootElement.GetProperty("snapshot").Str("mode"));
Assert.AreEqual("notConnected", disconnected.RootElement.GetProperty("connection").Str("state"));
foreach (var scene in new[] { normal, session, stopped, disconnected.RootElement })
{
foreach (var budget in scene.GetProperty("snapshot").Items("allBudgets"))
{
Assert.IsLessThanOrEqualTo(budget.Long("limitToday"), budget.Long("usedToday"), budget.Str("label"));
}
}
// Asking for a check while stopped is refused with a message.
var marta = (await GetAsync("/api/accounts")).Items("accounts").First(r => r.Str("username") == "marta.demo").Long("id");
using var check = new HttpRequestMessage(HttpMethod.Post, $"/api/accounts/{marta}/check-now?scena=fermo")
{
Content = new StringContent("{}", System.Text.Encoding.UTF8, "application/json"),
};
check.Headers.Add("Origin", $"{Demo.Address.Scheme}://{Demo.Address.Authority}");
using var answer = await Client.SendAsync(check);
using var body = JsonDocument.Parse(await answer.Content.ReadAsStringAsync());
Assert.AreEqual(HttpStatusCode.OK, answer.StatusCode);
Assert.AreEqual("refused", body.RootElement.Str("status"));
Assert.IsFalse(string.IsNullOrWhiteSpace(body.RootElement.Str("message")));
}
[TestMethod]
public async Task TheEditionCanBeChosenByAddress()
{
var desktop = await GetAsync("/api/capabilities");
Assert.IsTrue(desktop.Bool("demo"));
Assert.AreEqual("desktop", desktop.Str("edition"));
Assert.IsTrue(desktop.Bool("showInFolder"));
Assert.IsFalse(desktop.Bool("foldersReadOnly"));
Assert.AreEqual("none", desktop.Str("access"));
var docker = await GetAsync("/api/capabilities?veste=docker");
Assert.AreEqual("docker", docker.Str("edition"));
Assert.IsFalse(docker.Bool("showInFolder"));
Assert.IsTrue(docker.Bool("foldersReadOnly"));
Assert.IsFalse(docker.Bool("autostart"));
// The addresses that open a dialog or a step directly are pages of the interface.
foreach (var page in new[] { "/account?dialogo=aggiungi", "/importa?passo=3", "/libreria?scena=fermo&tema=scuro" })
{
using var response = await Client.GetAsync(page);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, page);
StringAssert.Contains(await response.Content.ReadAsStringAsync(), "<div id=\"app\"", page);
}
}
}
@@ -0,0 +1,349 @@
using System.Net;
using System.Text.Json;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Api;
using Febe.Web.Hosting;
using Febe.Web.Security;
namespace Febe.Tests.Web;
/// <summary>The embedded interface, the page addresses and the access checks of spec §13.1.</summary>
[TestClass]
public sealed class HostingAndSecurityTests
{
private static readonly string[] Pages =
[
"/", "/libreria", "/account", "/account/12", "/account/12/impostazioni", "/attivita", "/importa",
"/impostazioni/generali", "/impostazioni/limiti", "/impostazioni/collegamento", "/impostazioni/notifiche",
"/impostazioni/dati", "/impostazioni/informazioni", "/browser",
];
[TestMethod]
public void TheEmbeddedInterfaceHasEveryFileAndRefusesPathsOutsideIt()
{
var files = new EmbeddedWwwroot();
foreach (var path in new[] { "index.html", "accesso.html", "css/febe.css", "js/app.js", "testi/it.json", "img/marchio.svg", "icone/image.svg", "caratteri/archivo-latin-standard-normal.woff2" })
{
var info = files.GetFileInfo(path);
Assert.IsTrue(info.Exists, path);
Assert.IsGreaterThan(0L, info.Length, path);
using var stream = info.CreateReadStream();
Assert.AreEqual(info.Length, stream.Length, path);
}
Assert.IsTrue(files.GetFileInfo("/css/febe.css").Exists, "a leading slash is accepted");
foreach (var bad in new[] { "../Febe.Web.dll", "css/../index.html", "./index.html", "css\\febe.css", "C:/index.html", "css//febe.css", "nonexistent.js", "" })
{
Assert.IsFalse(files.GetFileInfo(bad).Exists, bad);
}
var icons = files.GetDirectoryContents("icone").Select(f => f.Name).ToList();
Assert.Contains("image.svg", icons);
Assert.IsFalse(files.GetDirectoryContents("../").Exists);
Assert.IsTrue(files.GetDirectoryContents(string.Empty).Any(f => f.IsDirectory && f.Name == "css"));
// The text resource is valid JSON with the Italian texts.
using var texts = JsonDocument.Parse(files.ReadText("testi/it.json")!);
Assert.AreEqual("Libreria", texts.RootElement.GetProperty("nav").GetProperty("libreria").GetString());
}
[TestMethod]
public void TheIconSpriteHasOneSymbolPerLucideFileWithoutItsOwnStroke()
{
var files = new EmbeddedWwwroot();
var sprite = SystemApi.BuildSprite(files);
var count = files.Files.Count(f => f.StartsWith("icone/", StringComparison.Ordinal) && f.EndsWith(".svg", StringComparison.Ordinal));
Assert.AreEqual(count, sprite.Split("<symbol ").Length - 1);
StringAssert.Contains(sprite, "id=\"i-layout-grid\"");
Assert.DoesNotContain("stroke-width=\"2\"", sprite, "stroke 1,75 comes from the style sheet");
}
[TestMethod]
public async Task ItalianPageAddressesAnswerWithTheApplicationAndTheApiStaysJson()
{
await using var server = await WebTestServer.StartAsync();
foreach (var page in Pages)
{
using var response = await server.Client.GetAsync(page);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, page);
Assert.AreEqual("text/html", response.Content.Headers.ContentType?.MediaType, page);
StringAssert.Contains(await response.Content.ReadAsStringAsync(), "<div id=\"app\"></div>", page);
Assert.IsTrue(response.Headers.Contains("Content-Security-Policy"), page);
}
using (var css = await server.Client.GetAsync("/css/febe.css"))
{
Assert.AreEqual("text/css", css.Content.Headers.ContentType?.MediaType);
Assert.AreEqual("nosniff", css.Headers.GetValues("X-Content-Type-Options").Single());
}
using (var js = await server.Client.GetAsync("/js/app.js"))
{
Assert.AreEqual("text/javascript", js.Content.Headers.ContentType?.MediaType);
}
using (var missing = await server.Client.GetAsync("/js/non-esiste.js"))
{
Assert.AreEqual(HttpStatusCode.NotFound, missing.StatusCode);
}
using var api = await server.Client.GetAsync("/api/non-esiste");
Assert.AreEqual(HttpStatusCode.NotFound, api.StatusCode);
Assert.AreEqual("application/json", api.Content.Headers.ContentType?.MediaType);
StringAssert.Contains(await api.Content.ReadAsStringAsync(), "sconosciuto");
var capabilities = await server.GetJsonAsync("/api/capabilities");
Assert.AreEqual("docker", capabilities.Str("edition"));
Assert.IsTrue(capabilities.Bool("foldersReadOnly"));
Assert.IsFalse(capabilities.Bool("showInFolder"));
Assert.AreEqual("2026-10-13", capabilities.Str("today"));
}
[TestMethod]
public async Task HostAndOriginChecksStopOtherPagesAndOtherNames()
{
await using var server = await WebTestServer.StartAsync();
using (var foreignHost = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities"))
{
foreignHost.Headers.Host = "attacco.example:80";
using var response = await server.Client.SendAsync(foreignHost);
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode, "DNS rebinding: a foreign host name is refused");
}
using (var crossOrigin = server.Request(HttpMethod.Post, "/api/engine/pause", origin: "http://attacco.example"))
using (var response = await server.Client.SendAsync(crossOrigin))
{
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
}
using (var nullOrigin = server.Request(HttpMethod.Post, "/api/engine/pause", origin: "null"))
using (var response = await server.Client.SendAsync(nullOrigin))
{
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
}
using (var crossSite = server.Request(HttpMethod.Post, "/api/engine/pause", origin: null))
{
crossSite.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "cross-site");
using var response = await server.Client.SendAsync(crossSite);
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
}
using (var events = server.Request(HttpMethod.Get, "/api/eventi", origin: "http://attacco.example"))
using (var response = await server.Client.SendAsync(events))
{
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, "the event stream counts as a command channel");
}
using (var sameOrigin = server.Request(HttpMethod.Post, "/api/engine/pause"))
using (var response = await server.Client.SendAsync(sameOrigin))
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync());
}
using (var sameSite = server.Request(HttpMethod.Post, "/api/engine/pause", origin: null))
{
sameSite.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
using var response = await server.Client.SendAsync(sameSite);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
}
[TestMethod]
public async Task TheDesktopTokenOpensTheInterfaceOnceAndThenLivesInAStrictCookie()
{
var token = AccessToken.Create();
await using var server = await WebTestServer.StartAsync(new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.Token, AccessToken = token });
using (var bare = await server.Client.GetAsync("/api/capabilities"))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, bare.StatusCode);
}
using (var page = await server.Client.GetAsync("/libreria"))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, page.StatusCode);
}
using (var wrong = await server.Client.GetAsync("/libreria?gettone=sbagliato"))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, wrong.StatusCode);
}
string cookie;
using (var first = await server.Client.GetAsync($"/libreria?tema=scuro&gettone={token}"))
{
Assert.AreEqual(HttpStatusCode.Redirect, first.StatusCode);
Assert.AreEqual("/libreria?tema=scuro", first.Headers.Location?.OriginalString, "the token leaves the address at once");
cookie = first.Headers.GetValues("Set-Cookie").Single();
StringAssert.Contains(cookie, AccessToken.CookieName + "=");
StringAssert.Contains(cookie.ToLowerInvariant(), "httponly");
StringAssert.Contains(cookie.ToLowerInvariant(), "samesite=strict");
}
using (var withCookie = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities"))
{
withCookie.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
using var response = await server.Client.SendAsync(withCookie);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
using (var withHeader = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities"))
{
withHeader.Headers.TryAddWithoutValidation(AccessToken.HeaderName, token);
using var response = await server.Client.SendAsync(withHeader);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
// The token is necessary but not sufficient: commands from another origin are refused even with it.
using (var forged = server.Request(HttpMethod.Post, "/api/engine/pause", origin: "http://127.0.0.1:1"))
{
forged.Headers.TryAddWithoutValidation(AccessToken.HeaderName, token);
using var response = await server.Client.SendAsync(forged);
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
}
}
[TestMethod]
public async Task ThePasswordOpensASessionAndRepeatedFailuresLockTheLogin()
{
await using var server = await WebTestServer.StartAsync(new FebeWebOptions
{
Access = AccessMode.Password,
Password = "una password lunga",
Lockout = new LockoutOptions { AttemptsPerClient = 3, AttemptsOverall = 50 },
});
using (var page = await server.Client.GetAsync("/libreria"))
{
Assert.AreEqual(HttpStatusCode.Redirect, page.StatusCode);
StringAssert.StartsWith(page.Headers.Location?.OriginalString, "/accesso?torna=");
}
using (var api = await server.Client.GetAsync("/api/accounts"))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, api.StatusCode);
}
using (var login = await server.Client.GetAsync("/accesso"))
{
Assert.AreEqual(HttpStatusCode.OK, login.StatusCode, "the login page is public");
}
using (var css = await server.Client.GetAsync("/css/febe.css"))
{
Assert.AreEqual(HttpStatusCode.OK, css.StatusCode, "and so is what it needs");
}
var (wrong, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" });
Assert.AreEqual(HttpStatusCode.Unauthorized, wrong);
string cookie;
using (var ok = server.Request(HttpMethod.Post, "/api/accesso", new { password = "una password lunga" }))
using (var response = await server.Client.SendAsync(ok))
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
cookie = response.Headers.GetValues("Set-Cookie").Single();
StringAssert.Contains(cookie.ToLowerInvariant(), "httponly");
StringAssert.Contains(cookie.ToLowerInvariant(), "samesite=strict");
}
using (var authed = new HttpRequestMessage(HttpMethod.Get, "/api/accounts"))
{
authed.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
using var response = await server.Client.SendAsync(authed);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
// A login from another page is refused before the password is even checked.
var (foreign, _) = await SendWithOrigin(server, "/api/accesso", new { password = "una password lunga" }, "http://attacco.example");
Assert.AreEqual(HttpStatusCode.Forbidden, foreign);
// The right password cleared the earlier failure: the third failure from now on locks the login.
Assert.AreEqual(HttpStatusCode.Unauthorized, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" })).Status);
Assert.AreEqual(HttpStatusCode.Unauthorized, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" })).Status);
Assert.AreEqual(HttpStatusCode.TooManyRequests, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" })).Status);
Assert.AreEqual(HttpStatusCode.TooManyRequests, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "una password lunga" })).Status,
"while locked even the right password waits");
using (var logout = server.Request(HttpMethod.Post, "/api/uscita"))
{
logout.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
using var response = await server.Client.SendAsync(logout);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
using (var after = new HttpRequestMessage(HttpMethod.Get, "/api/accounts"))
{
after.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
using var response = await server.Client.SendAsync(after);
Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
[TestMethod]
public void TheLockoutCoversOneClientAndAllClientsAndEndsByItself()
{
var now = Make.T0;
var access = new PasswordAccess("segreta", new LockoutOptions { AttemptsPerClient = 2, AttemptsOverall = 3, LockFor = TimeSpan.FromMinutes(15) }, () => now);
Assert.AreEqual(LoginStatus.WrongPassword, access.TryLogin("x", "a").Status);
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("x", "a").Status);
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("segreta", "a").Status);
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("x", "b").Status, "the third failure overall locks every client");
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("segreta", "c").Status, "even one that never failed");
now += TimeSpan.FromMinutes(16);
var ok = access.TryLogin("segreta", "a");
Assert.AreEqual(LoginStatus.Accepted, ok.Status);
Assert.IsTrue(access.IsValid(ok.SessionId));
now += TimeSpan.FromDays(31);
Assert.IsFalse(access.IsValid(ok.SessionId), "sessions expire");
}
[TestMethod]
public async Task TheEventStreamStartsWithTheEngine()
{
await using var server = await WebTestServer.StartAsync();
using var request = new HttpRequestMessage(HttpMethod.Get, "/api/eventi");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
using var response = await server.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual("text/event-stream", response.Content.Headers.ContentType?.MediaType);
using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
string? eventName = null;
string? data = null;
while (data is null)
{
var line = await reader.ReadLineAsync(timeout.Token);
if (line is null)
{
break;
}
if (line.StartsWith("event: ", StringComparison.Ordinal))
{
eventName = line[7..];
}
else if (line.StartsWith("data: ", StringComparison.Ordinal))
{
data = line[6..];
}
}
Assert.AreEqual("motore", eventName);
using var json = JsonDocument.Parse(data!);
Assert.AreEqual("Off", json.RootElement.GetProperty("snapshot").GetProperty("mode").GetString(), "without an engine Febe says «Motore spento»");
Assert.AreEqual("Motore spento", json.RootElement.GetProperty("snapshot").GetProperty("headline").GetString());
}
private static async Task<(HttpStatusCode Status, string Body)> SendWithOrigin(WebTestServer server, string path, object body, string origin)
{
using var request = server.Request(HttpMethod.Post, path, body, origin);
using var response = await server.Client.SendAsync(request);
return (response.StatusCode, await response.Content.ReadAsStringAsync());
}
}
+206
View File
@@ -0,0 +1,206 @@
using System.Net;
using System.Text;
using System.Text.Json;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Library;
namespace Febe.Tests.Web;
/// <summary>The library API (spec §4.6): day groups, keyset windows, filters, viewer data, deletion, CSV export.</summary>
[TestClass]
public sealed class LibraryApiTests
{
[TestMethod]
public async Task WindowsFollowTheCursorsWithoutGapsOrRepeatsAndDaysAddUp()
{
await using var server = await WebTestServer.StartAsync();
await server.AddAccountWithEntriesAsync("marta.demo", 40, Make.T0, TimeSpan.FromHours(5));
await server.AddAccountWithEntriesAsync("luca.viaggi.demo", 23, Make.T0 - TimeSpan.FromMinutes(30), TimeSpan.FromHours(7), EntryKind.Story);
var days = await server.GetJsonAsync("/api/library/days");
Assert.AreEqual(63, days.Int("entries"));
Assert.AreEqual(2, days.Int("accounts"));
Assert.AreEqual(63, days.Items("days").Sum(d => d.Int("count")), "the counts of the days add up to the total");
var dayNames = days.Items("days").Select(d => d.Str("day")).ToList();
CollectionAssert.AreEqual(dayNames.OrderByDescending(d => d, StringComparer.Ordinal).ToList(), dayNames, "newest day first");
var seen = new List<(long Ms, long Id)>();
string? cursor = null;
var pages = 0;
do
{
var page = await server.GetJsonAsync("/api/library?limit=7" + (cursor is null ? string.Empty : "&cursor=" + cursor));
seen.AddRange(page.Items("tiles").Select(t => (t.Long("publishedAt"), t.Long("id"))));
cursor = page.GetProperty("older").ValueKind == JsonValueKind.Null ? null : page.Str("older");
pages++;
}
while (cursor is not null && pages < 50);
Assert.HasCount(63, seen);
Assert.HasCount(63, seen.Select(s => s.Id).Distinct());
for (var i = 1; i < seen.Count; i++)
{
Assert.IsTrue(seen[i].Ms < seen[i - 1].Ms || (seen[i].Ms == seen[i - 1].Ms && seen[i].Id < seen[i - 1].Id), "display order: newest first");
}
// The cursor of a day starts exactly at that day.
foreach (var day in days.Items("days").Take(4))
{
var page = await server.GetJsonAsync($"/api/library?limit={day.Int("count")}&cursor={day.Str("cursor")}");
Assert.IsTrue(page.Items("tiles").All(t => t.Str("day") == day.Str("day")), day.Str("day"));
Assert.AreEqual(day.Int("count"), page.Items("tiles").Count());
}
// Going back up from a cursor gives the newer entries.
var middle = await server.GetJsonAsync("/api/library?limit=10&cursor=" + Uri.EscapeDataString($"{seen[30].Ms}.{seen[30].Id}"));
Assert.AreEqual(seen[31].Id, middle.Items("tiles").First().Long("id"));
var newer = await server.GetJsonAsync("/api/library?limit=5&direction=newer&cursor=" + Uri.EscapeDataString($"{seen[30].Ms}.{seen[30].Id}"));
CollectionAssert.AreEqual(seen.Skip(25).Take(5).Select(s => s.Id).ToList(), newer.Items("tiles").Select(t => t.Long("id")).ToList());
}
[TestMethod]
public async Task FiltersByKindAccountSearchAndPeriod()
{
await using var server = await WebTestServer.StartAsync();
var marta = await server.AddAccountWithEntriesAsync("marta.demo", 10, Make.T0, TimeSpan.FromDays(1), caption: "Tramonto sul molo");
await server.AddAccountWithEntriesAsync("luca.viaggi.demo", 6, Make.T0, TimeSpan.FromDays(1), EntryKind.Story);
Assert.AreEqual(6, (await server.GetJsonAsync("/api/library/days?kind=stories")).Int("entries"));
Assert.AreEqual(10, (await server.GetJsonAsync("/api/library/days?kind=photos")).Int("entries"));
Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days?kind=videos")).Int("entries"), "«Video» concerns posts; story videos are under «Storie»");
Assert.AreEqual(10, (await server.GetJsonAsync($"/api/library/days?accounts={marta.Id}")).Int("entries"));
Assert.AreEqual(10, (await server.GetJsonAsync("/api/library/days?q=tramonto")).Int("entries"), "caption search ignores case");
Assert.AreEqual(6, (await server.GetJsonAsync("/api/library/days?q=luca")).Int("entries"), "account name search");
Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days?provenance=imported")).Int("entries"));
Assert.AreEqual(6, (await server.GetJsonAsync("/api/library/days?from=2026-10-08&to=2026-10-10")).Int("entries"), "three local days, both accounts");
var (status, body) = await server.SendJsonAsync(HttpMethod.Get, "/api/library?cursor=nonvalido");
Assert.AreEqual(HttpStatusCode.BadRequest, status);
StringAssert.Contains(body.Str("message"), "non valida");
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library/days?kind=gatti")).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library/days?from=13/10/2026")).Status);
}
[TestMethod]
public async Task TheViewerGetsDataFilesAndProvenanceAndDeletionIsRemembered()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var folder = server.Library.Layout.AccountFolder(account);
Directory.CreateDirectory(Path.Combine(folder, "post"));
var bytes = TestImages.Jpeg(TestImages.Scene(3, 120, 150));
await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_1.jpg"), bytes);
var added = await server.Db.Entries.AddAsync(
Make.Entry(account.Id, "1", Make.T0, caption: "Luce della sera") with { State = EntryState.Downloaded },
[Make.Stored(Make.Photo(1), Make.Sha(1), "post/foto_1.jpg") with { Bytes = bytes.Length }, Make.Stored(Make.Video(2), Make.Sha(2), "post/video_2.mp4")]);
var id = added.Stored.Entry.Id;
var entry = await server.GetJsonAsync($"/api/entries/{id}");
Assert.AreEqual("post", entry.Str("kind"));
Assert.AreEqual("Luce della sera", entry.Str("caption"));
Assert.AreEqual("C1", entry.Str("code"));
Assert.AreEqual("https://www.instagram.com/p/C1/", entry.Str("instagramUrl"));
Assert.AreEqual("2026-10-13", entry.Str("publishedDay"));
Assert.AreEqual("10:00", entry.Str("publishedTime"), "local time of Alberto's zone (Rome, UTC+2 in October)");
var media = entry.Items("media").ToList();
Assert.HasCount(2, media);
Assert.IsTrue(media[0].Bool("available"));
Assert.AreEqual("foto_1.jpg", media[0].Str("fileName"));
Assert.AreEqual(Path.Combine("marta.demo", "post"), media[0].Str("folder"));
Assert.IsFalse(media[1].Bool("available"), "a file missing from disk is said, not hidden");
using (var file = await server.Client.GetAsync($"/api/media/{media[0].Long("id")}/file?download=1"))
{
Assert.AreEqual(HttpStatusCode.OK, file.StatusCode);
Assert.AreEqual("image/jpeg", file.Content.Headers.ContentType?.MediaType);
Assert.AreEqual("foto_1.jpg", file.Content.Headers.ContentDisposition?.FileName?.Trim('"'));
CollectionAssert.AreEqual(bytes, await file.Content.ReadAsByteArrayAsync());
}
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{media[1].Long("id")}/file")).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/thumbnails/nonvalida")).Status);
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/thumbnails/" + Make.Sha(99))).Status);
using (var neutral = await server.Client.GetAsync("/api/thumbnails/video"))
{
Assert.AreEqual("image/jpeg", neutral.Content.Headers.ContentType?.MediaType);
}
// Without the desktop, «Mostra nella cartella» does not exist: the page offers «Scarica».
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/media/show-in-folder", new { mediaId = media[0].Long("id") })).Status);
var changes = server.Changes.SubscribeAsync().GetAsyncEnumerator();
var next = changes.MoveNextAsync().AsTask();
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete", new { ids = new[] { id }, mode = "remember" });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual(1, result.Int("deleted"));
Assert.AreEqual(1, result.Int("filesRemoved"));
Assert.IsFalse(File.Exists(Path.Combine(folder, "post", "foto_1.jpg")));
Assert.AreEqual(EntryState.Deleted, (await server.Db.Entries.GetAsync(id))!.State, "remembered: never downloaded again");
Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days")).Int("entries"));
Assert.IsTrue(await next.WaitAsync(TimeSpan.FromSeconds(5)), "the open pages hear about it");
Assert.AreEqual("deleted", changes.Current.Reason);
await changes.DisposeAsync();
var after = await server.GetJsonAsync($"/api/entries/{id}");
Assert.AreEqual("deleted", after.Str("state"));
Assert.AreEqual(JsonValueKind.Null, after.GetProperty("instagramUrl").ValueKind);
}
[TestMethod]
public async Task DeletionCanLetTheEntryComeBack()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.AddAccountWithEntriesAsync("marta.demo", 2, Make.T0, TimeSpan.FromHours(1));
var ids = (await server.Db.Entries.ListByAccountAsync(account.Id)).Select(e => e.Id).ToList();
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete", new { ids, mode = "allowReturn" });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.IsEmpty(await server.Db.Entries.ListByAccountAsync(account.Id), "forgotten: a later check may download them again");
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete", new { ids = Array.Empty<long>() })).Status);
}
[TestMethod]
public void CsvFieldsAreQuotedForExcelAndFormulasAreDefused()
{
Assert.AreEqual(string.Empty, CsvExport.Field(null));
Assert.AreEqual("semplice", CsvExport.Field("semplice"));
Assert.AreEqual("\"a;b\"", CsvExport.Field("a;b"));
Assert.AreEqual("\"dice \"\"ciao\"\"\"", CsvExport.Field("dice \"ciao\""));
Assert.AreEqual("\"riga\nnuova\"", CsvExport.Field("riga\nnuova"));
Assert.AreEqual("\" spazio\"", CsvExport.Field(" spazio"));
Assert.AreEqual("\"'=1+1\"", CsvExport.Field("=1+1"));
Assert.AreEqual("\"'@marta ciao\"", CsvExport.Field("@marta ciao"));
Assert.AreEqual("\"'-3\"", CsvExport.Field("-3"));
Assert.AreEqual("a;\"b;c\";", CsvExport.Line(["a", "b;c", null]));
}
[TestMethod]
public async Task TheExportIsUtf8WithBomSemicolonsAndOneLinePerEntry()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.AddAccountWithEntriesAsync("marta.demo", 3, Make.T0, TimeSpan.FromDays(1), caption: "Città; mare e \"sole\"\nseconda riga");
var ids = (await server.Db.Entries.ListByAccountAsync(account.Id)).Select(e => e.Id).ToList();
using var request = server.Request(HttpMethod.Post, "/api/entries/export", new { ids });
using var response = await server.Client.SendAsync(request);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual("text/csv", response.Content.Headers.ContentType?.MediaType);
Assert.AreEqual("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
StringAssert.EndsWith(response.Content.Headers.ContentDisposition?.FileName?.Trim('"'), ".csv");
var bytes = await response.Content.ReadAsByteArrayAsync();
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes.Take(3).ToArray(), "UTF-8 with BOM for Excel");
var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
StringAssert.StartsWith(text, string.Join(';', CsvExport.Header) + "\r\n");
StringAssert.Contains(text, "\"Città; mare e \"\"sole\"\"\nseconda riga\"");
StringAssert.Contains(text, "marta.demo;Post;13/10/2026;10:00:00;");
Assert.AreEqual(4, text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Length, "header and three entries");
// By filter: the same query the page uses.
using var byFilter = server.Request(HttpMethod.Post, "/api/entries/export", new { query = "kind=photos&from=2026-10-12" });
using var filtered = await server.Client.SendAsync(byFilter);
var filteredText = Encoding.UTF8.GetString(await filtered.Content.ReadAsByteArrayAsync());
Assert.AreEqual(3, filteredText.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Length, "header and the two entries of 12 and 13 October");
}
}
@@ -0,0 +1,157 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
using Febe.Web;
using Febe.Web.Library;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web.Support;
/// <summary>
/// Febe.Web on a real Kestrel listening on 127.0.0.1 with a free port (no test server package needed), with a
/// temporary database and library, and an HttpClient pointed at it.
/// </summary>
internal sealed class WebTestServer : IAsyncDisposable
{
private WebTestServer(TempFolder temp, FebeDatabase db, FebeLibrary library, ManualClock clock, WebApplication app, Uri address)
{
Temp = temp;
Db = db;
Library = library;
Clock = clock;
App = app;
Address = address;
Client = NewClient();
}
public TempFolder Temp { get; }
public FebeDatabase Db { get; }
public FebeLibrary Library { get; }
public ManualClock Clock { get; }
public WebApplication App { get; }
public Uri Address { get; }
/// <summary>A client without cookies of its own (each test decides what to send).</summary>
public HttpClient Client { get; }
/// <summary>«http://127.0.0.1:port», the value of Origin for requests coming from the interface.</summary>
public string Origin => $"{Address.Scheme}://{Address.Authority}";
public LibraryChanges Changes => App.Services.GetRequiredService<LibraryChanges>();
public static async Task<WebTestServer> StartAsync(FebeWebOptions? options = null, Action<IServiceCollection>? services = null)
{
var temp = new TempFolder("web");
var db = await FebeDatabase.OpenAsync(temp.Combine("dati"));
var clock = new ManualClock(Make.T0);
var library = new FebeLibrary(db, new DataFolderLayout(temp.Combine("dati")), new LibraryLayout(temp.Combine("libreria")), clock);
options ??= new FebeWebOptions { Access = AccessMode.None };
options = options with { AllowedHosts = options.AllowedHosts.Count == 0 ? FebeWebOptions.LoopbackHosts(0) : options.AllowedHosts };
var app = FebeWebHost.Build(options, FebeListen.Loopback(0), s =>
{
s.AddSingleton<IFebeStorage>(db);
s.AddSingleton(library);
s.AddSingleton<IClock>(clock);
services?.Invoke(s);
});
await app.StartAsync();
return new WebTestServer(temp, db, library, clock, app, FebeWebHost.BoundAddress(app));
}
public HttpClient NewClient(bool cookies = false, bool redirects = false)
{
var handler = new HttpClientHandler { AllowAutoRedirect = redirects, UseCookies = cookies, CookieContainer = new CookieContainer() };
return new HttpClient(handler) { BaseAddress = Address, Timeout = TimeSpan.FromSeconds(30) };
}
/// <summary>A request as the interface sends it (Origin of the interface on commands).</summary>
public HttpRequestMessage Request(HttpMethod method, string path, object? body = null, string? origin = "")
{
var request = new HttpRequestMessage(method, path);
if (body is not null)
{
request.Content = new StringContent(body as string ?? JsonSerializer.Serialize(body, Json), Encoding.UTF8, "application/json");
}
if (origin is not null)
{
request.Headers.TryAddWithoutValidation("Origin", origin.Length == 0 ? Origin : origin);
}
return request;
}
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
public async Task<JsonElement> GetJsonAsync(string path)
{
using var response = await Client.GetAsync(path);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
public async Task<(HttpStatusCode Status, JsonElement Body)> SendJsonAsync(HttpMethod method, string path, object? body = null)
{
using var request = Request(method, path, body);
using var response = await Client.SendAsync(request);
var text = await response.Content.ReadAsStringAsync();
var json = text.Length > 0 && (response.Content.Headers.ContentType?.MediaType?.Contains("json", StringComparison.Ordinal) ?? false)
? JsonDocument.Parse(text).RootElement.Clone()
: default;
return (response.StatusCode, json);
}
/// <summary>Adds an account with a few stored entries spread over days (no files on disk).</summary>
public async Task<Account> AddAccountWithEntriesAsync(string username, int entries, DateTimeOffset newest, TimeSpan step, EntryKind kind = EntryKind.Post, string? caption = null)
{
var account = await Db.Accounts.AddAsync(Make.Account(username));
var items = new List<NewEntry>();
for (var i = 0; i < entries; i++)
{
var media = Make.Stored(kind == EntryKind.Story ? Make.Video() : Make.Photo(), Make.Sha((1000 * username.Length) + i + 1), $"post/{username}-{i}.jpg");
items.Add(new NewEntry(Make.Entry(account.Id, $"{username}-{i}", newest - (step * i), kind, caption) with { State = EntryState.Downloaded }, [media]));
}
await Db.Entries.AddManyAsync(items);
return account;
}
public async ValueTask DisposeAsync()
{
Client.Dispose();
await App.StopAsync();
await App.DisposeAsync();
await Db.DisposeAsync();
Temp.Dispose();
}
}
/// <summary>Small JSON helpers for the API answers.</summary>
internal static class JsonAnswers
{
public static string Str(this JsonElement e, string name) => e.GetProperty(name).GetString() ?? string.Empty;
public static int Int(this JsonElement e, string name) => e.GetProperty(name).GetInt32();
public static long Long(this JsonElement e, string name) => e.GetProperty(name).GetInt64();
public static bool Bool(this JsonElement e, string name) => e.GetProperty(name).GetBoolean();
public static JsonElement.ArrayEnumerator Items(this JsonElement e, string name) => e.GetProperty(name).EnumerateArray();
public static Task<T?> ReadAsync<T>(this HttpContent content) => content.ReadFromJsonAsync<T>(WebTestServer.Json);
}
+6
View File
@@ -0,0 +1,6 @@
// Chooses three followed profiles in the «Aggiungi account» dialog (mockup 04).
await new Promise((r) => setTimeout(r, 800));
const boxes = [...document.querySelectorAll('.aggiungi .elenco input[type=checkbox]:not(:disabled)')];
for (const i of [0, 2, 5]) if (boxes[i]) boxes[i].click();
await new Promise((r) => setTimeout(r, 400));
return document.querySelector('.aggiungi footer .btn.primo')?.textContent;
+7
View File
@@ -0,0 +1,7 @@
// Moves the pointer over the widest tile near the top of the mosaic (hover state of mockup 01).
const tiles = [...document.querySelectorAll('.tess[data-id]')];
const wide = tiles
.filter((t) => t.getBoundingClientRect().top < 500)
.sort((a, b) => b.getBoundingClientRect().width - a.getBoundingClientRect().width)[0];
const r = wide.getBoundingClientRect();
return { hover: [Math.round(r.left + r.width / 2), Math.round(r.top + r.height / 2)], label: wide.getAttribute('aria-label') };
+9
View File
@@ -0,0 +1,9 @@
// Opens a post with more files in the viewer and shows its second file (mockup 02).
const tiles = [...document.querySelectorAll('.tess[data-id]')];
const multi = tiles.find((t) => t.querySelector('use[href="#i-layers"]') && !t.querySelector('use[href="#i-circle-dashed"]') && !t.querySelector('use[href="#i-play"]')) || tiles[0];
multi.click();
await new Promise((r) => setTimeout(r, 1500));
const second = document.querySelectorAll('.vis .serie button')[1];
if (second) second.click();
await new Promise((r) => setTimeout(r, 1200));
return document.querySelector('.vis .dove')?.textContent;
+119
View File
@@ -0,0 +1,119 @@
// node tools/schermate/schermata.mjs <indirizzo> <file.png> [larghezza] [altezza] [attesa-ms] [passo.js]
//
// Screenshot of Febe's own interface (spec §10.7) through the DevTools protocol of a Chromium without window:
// exact viewport at scale 1.25 (like the mockups), console errors printed, an optional step (a JS file evaluated in
// the page and awaited; when it returns { hover: [x, y] } the pointer is moved there, so :hover styles show).
//
// Only for Febe's own interface: the address must be on this computer (127.0.0.1 or localhost). Instagram is never
// opened this way (spec §2, rule 4). Needs Node 22 or later (global WebSocket) and a Chromium: set FEBE_CHROMIUM, or
// the Playwright build under /opt/pw-browsers is used.
import { spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const [address, out, width = '1440', height = '900', wait = '3000', step] = process.argv.slice(2);
if (!address || !out) {
console.error('Uso: node tools/schermate/schermata.mjs <indirizzo> <file.png> [larghezza] [altezza] [attesa-ms] [passo.js]');
process.exit(2);
}
const target = new URL(address);
if (!['127.0.0.1', 'localhost', '[::1]'].includes(target.hostname)) {
console.error('Solo l\'interfaccia di Febe su questo computer (127.0.0.1 o localhost).');
process.exit(2);
}
function findChromium() {
if (process.env.FEBE_CHROMIUM) return process.env.FEBE_CHROMIUM;
const root = '/opt/pw-browsers';
if (existsSync(root)) {
for (const name of readdirSync(root).filter((n) => /^chromium-\d+$/.test(n)).sort().reverse()) {
const candidate = join(root, name, 'chrome-linux', 'chrome');
if (existsSync(candidate)) return candidate;
}
}
console.error('Chromium non trovato: indica il percorso in FEBE_CHROMIUM.');
process.exit(2);
}
const profile = mkdtempSync(join(tmpdir(), 'febe-schermata-'));
const port = 9300 + Math.floor(Math.random() * 500);
const chrome = spawn(findChromium(), [
'--headless', '--no-sandbox', '--disable-gpu', '--hide-scrollbars', '--disable-background-networking',
'--disable-component-update', '--no-first-run', '--no-default-browser-check', '--disable-extensions',
`--user-data-dir=${profile}`, `--remote-debugging-port=${port}`, '--remote-debugging-address=127.0.0.1', 'about:blank',
], { stdio: 'ignore' });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function finish(code) {
chrome.kill('SIGKILL');
setTimeout(() => {
try {
rmSync(profile, { recursive: true, force: true });
} catch {
// the profile stays in the temporary folder
}
process.exit(code);
}, 300);
}
let ws;
for (let i = 0; i < 50 && !ws; i++) {
try {
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = list.find((t) => t.type === 'page');
if (page) ws = new WebSocket(page.webSocketDebuggerUrl);
} catch {
// Chromium is still starting
}
if (!ws) await sleep(200);
}
if (!ws) {
console.error('Chromium non risponde.');
finish(1);
} else {
await new Promise((r) => ws.addEventListener('open', r));
let id = 0;
const pending = new Map();
ws.addEventListener('message', (e) => {
const msg = JSON.parse(e.data);
if (msg.id && pending.has(msg.id)) {
pending.get(msg.id)(msg);
pending.delete(msg.id);
} else if (msg.method === 'Runtime.consoleAPICalled' && ['error', 'warning'].includes(msg.params.type)) {
console.log(`console.${msg.params.type}:`, msg.params.args.map((a) => a.value ?? a.description).join(' '));
} else if (msg.method === 'Runtime.exceptionThrown') {
console.log('eccezione:', msg.params.exceptionDetails.exception?.description || msg.params.exceptionDetails.text);
} else if (msg.method === 'Log.entryAdded' && msg.params.entry.level === 'error') {
console.log('errore:', msg.params.entry.text, msg.params.entry.url || '');
}
});
const send = (method, params = {}) => new Promise((resolve) => {
const n = ++id;
pending.set(n, resolve);
ws.send(JSON.stringify({ id: n, method, params }));
});
await send('Runtime.enable');
await send('Log.enable');
await send('Page.enable');
await send('Emulation.setDeviceMetricsOverride', { width: Number(width), height: Number(height), deviceScaleFactor: 1.25, mobile: false });
await send('Page.navigate', { url: target.href });
await sleep(Number(wait));
if (step) {
const code = readFileSync(step, 'utf8');
const r = await send('Runtime.evaluate', { expression: `(async () => { ${code} })()`, awaitPromise: true, returnByValue: true });
const value = r.result?.result?.value;
if (r.result?.exceptionDetails) console.log('errore nel passo:', r.result.exceptionDetails.exception?.description);
else if (value !== undefined) console.log('passo:', JSON.stringify(value));
if (value && typeof value === 'object' && Array.isArray(value.hover)) {
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: value.hover[0], y: value.hover[1] });
}
await sleep(800);
}
const shot = await send('Page.captureScreenshot', { format: 'png' });
writeFileSync(out, Buffer.from(shot.result.data, 'base64'));
console.log('salvata', out);
ws.close();
finish(0);
}
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
# Retakes the screenshots of docs/schermate from a running demo (spec §10.7):
# dotnet run --project src/Febe.Server -- --demo --porta 8490 (in another terminal)
# bash tools/schermate/tutte.sh [porta] [cartella]
# One screenshot at a time: Chromium and the demo share the computer.
set -u
here="$(cd "$(dirname "$0")" && pwd)"
port="${1:-8480}"
out="${2:-$here/../../docs/schermate}"
b="http://127.0.0.1:$port"
mkdir -p "$out"
shot() { echo "== $2"; timeout 90 node "$here/schermata.mjs" "$1" "$out/$2" "${3:-1440}" "${4:-900}" "${5:-3000}" ${6:-}; }
shot "$b/libreria?tema=chiaro" 01-libreria.png 1440 900 3000 "$here/passi/puntatore.js"
shot "$b/libreria?tema=chiaro" 02-visualizzatore.png 1440 900 3000 "$here/passi/visualizzatore.js"
shot "$b/account?tema=chiaro" 03-account.png
shot "$b/account?tema=chiaro" 03-account-telefono.png 390 844
shot "$b/account?dialogo=aggiungi&tema=chiaro" 04-aggiungi-account.png 1440 900 3000 "$here/passi/aggiungi.js"
shot "$b/account/3/impostazioni?tema=chiaro" 05-account-impostazioni.png
shot "$b/libreria?scena=fermo&tema=scuro" 11-libreria-fermo-tema-scuro.png
shot "$b/account/2?tema=scuro&tipo=storie" 12-account-storie-tema-scuro.png
shot "$b/libreria?tema=chiaro" 14-finestra-stretta.png 860 900
shot "$b/libreria?tema=chiaro" 14-telefono.png 390 844
shot "$b/account/2/cronologia?tema=chiaro" account-cronologia.png