Files
Febe/src/Febe.Web/Api/AccountsApi.cs
T
Claude 0ceffffe50 Interfaccia: correzioni della revisione (web-1, web-2, web-3, web-4, web-5, web-6, web-7, web-9, web-10, web-11, web-12, web-13, web-14, web-15)
Il browser preso dalle pagine Browser e Collegamento si restituisce uscendo senza «Ho finito» (anche chiudendo o ricaricando la scheda); dopo «Ho finito» la vista remota si chiude e non si riprende il browser. Vista remota: AltGr/Option come testo, pulsante rilasciato anche fuori dalla vista. Mosaico e scheda account senza risposte vecchie né viste sovrascritte; nuovi elementi dopo la libreria vuota; intestazione sempre aggiornata. Indietro del browser con la richiesta delle modifiche non salvate; nulla resta registrato da una pagina lasciata mentre caricava; maniglie della fascia trascinabili. «Da una data» come giorno locale; niente «@null» nel riquadro di stato; orari futuri dei fermi «verso le». Prove nel browser vero (InterfaceTests).

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

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
2026-10-14 01:38:13 +00:00

618 lines
33 KiB
C#

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, clock.LocalZone) 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, zone),
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);
}