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

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