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

+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));
}
}
}