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
325 lines
16 KiB
C#
325 lines
16 KiB
C#
using Febe.Core.Abstractions;
|
||
using Febe.Core.Domain;
|
||
|
||
namespace Febe.Core.Engine;
|
||
|
||
/// <summary>What the «Con queste impostazioni» panel needs (spec §4.4, mockup 05).</summary>
|
||
public sealed record AccountPlanInput
|
||
{
|
||
/// <summary>The account with the settings being edited (not yet saved).</summary>
|
||
public required Account Account { get; init; }
|
||
|
||
/// <summary>All the other accounts, to compute the load on the daily budgets (the edited account is ignored here by id).</summary>
|
||
public IReadOnlyList<Account> OtherAccounts { get; init; } = [];
|
||
|
||
/// <summary>The effective caution profile (settings applied).</summary>
|
||
public required CautionProfile Profile { get; init; }
|
||
|
||
/// <summary>Posts of this account already in the library (for the backfill estimate).</summary>
|
||
public int ArchivedPosts { get; init; }
|
||
|
||
public EngineOptions Options { get; init; } = EngineOptions.Default;
|
||
|
||
/// <summary>
|
||
/// Start of the gradual start in force (<c>motore.avvio-graduale-dal</c>) and the current time: the warning about
|
||
/// halved budgets is given only while the ramp lasts. Null (unknown) keeps the warning.
|
||
/// </summary>
|
||
public DateTimeOffset? GradualStartSince { get; init; }
|
||
|
||
public DateTimeOffset? Now { get; init; }
|
||
}
|
||
|
||
/// <summary>A line of the panel: «Nuovi post» — «controllati ogni 3 ore circa, tra le 7:30 e le 23:30».</summary>
|
||
public sealed record PlanLine(string Title, string Text);
|
||
|
||
/// <summary>The consequences of an account's settings, with real numbers (spec §4.5).</summary>
|
||
public sealed record AccountPlanEstimate
|
||
{
|
||
public required IReadOnlyList<PlanLine> Lines { get; init; }
|
||
|
||
/// <summary>Warnings: requested accounts and frequencies exceed what the budgets allow (checks get sparser, not forced).</summary>
|
||
public required IReadOnlyList<string> Warnings { get; init; }
|
||
|
||
/// <summary>The engine contacts this account at all (not paused, not «Solo archivio», reachable).</summary>
|
||
public bool Contacted { get; init; }
|
||
|
||
/// <summary>Profile checks as wished by the frequency.</summary>
|
||
public TimeSpan? ProfileCheckWanted { get; init; }
|
||
|
||
/// <summary>Profile checks as they will really happen (sparser when the budget is short).</summary>
|
||
public TimeSpan? ProfileCheckEvery { get; init; }
|
||
|
||
/// <summary>Planned interval between story checks (null with stories off).</summary>
|
||
public TimeSpan? StoryInterval { get; init; }
|
||
|
||
public double? StoryChecksPerDay { get; init; }
|
||
|
||
/// <summary>Profile openings per day caused by this account (after thinning).</summary>
|
||
public double ProfileOpensPerDay { get; init; }
|
||
|
||
/// <summary>Profile openings per day asked by all the accounts together (before thinning).</summary>
|
||
public double TotalProfileOpensPerDay { get; init; }
|
||
|
||
/// <summary>Daily budget of profiles opened (full, without gradual start or halving).</summary>
|
||
public int DailyProfileBudget { get; init; }
|
||
|
||
/// <summary>Share of the daily profile budget taken by this account, 0–1.</summary>
|
||
public double ShareOfDailyBudget { get; init; }
|
||
|
||
/// <summary>All the accounts together ask more than the budget allows.</summary>
|
||
public bool OverBudget { get; init; }
|
||
|
||
public int? BackfillRemainingPosts { get; init; }
|
||
|
||
/// <summary>Days the backfill needs (null when the number of posts is not known yet).</summary>
|
||
public int? BackfillDays { get; init; }
|
||
}
|
||
|
||
/// <summary>
|
||
/// The «Con queste impostazioni» calculator (spec §4.4): a pure function the web layer can call at every change.
|
||
/// The numbers are estimates from medians; they say «circa».
|
||
/// </summary>
|
||
public static class AccountPlanCalculator
|
||
{
|
||
/// <summary>Mean of the next-check jitter (log-normal, median 1, σ 0.25, truncated to [0.6, 1.8]).</summary>
|
||
private const double MeanCheckJitter = 1.03;
|
||
|
||
/// <summary>Mean of the story jitter (median 0.75, σ 0.25, truncated to [0.45, 1]).</summary>
|
||
private const double MeanStoryJitter = 0.74;
|
||
|
||
public static AccountPlanEstimate Calculate(AccountPlanInput input)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(input);
|
||
var account = input.Account;
|
||
var profile = input.Profile;
|
||
var options = input.Options;
|
||
var window = CautionProfileRules.WindowLength(profile.WindowStart, profile.WindowEnd);
|
||
var windowText = $"tra le {Clock(profile.WindowStart)} e le {Clock(profile.WindowEnd)}";
|
||
var lines = new List<PlanLine>();
|
||
var warnings = new List<string>();
|
||
|
||
var all = input.OtherAccounts.Where(a => a.Id == 0 || a.Id != account.Id).Append(account).ToList();
|
||
var contactable = all.Where(CheckPolicy.IsContactable).ToList();
|
||
var totalDemand = contactable.Sum(a => ProfileOpensPerDay(a, window, options));
|
||
var budget = profile.Budgets.TryGetValue(ActionKind.ProfileOpen, out var b) ? b.PerDay : 0;
|
||
var overBudget = budget > 0 && totalDemand > budget;
|
||
var thinning = overBudget ? totalDemand / budget : 1.0;
|
||
|
||
var contacted = CheckPolicy.IsContactable(account);
|
||
var own = contacted ? ProfileOpensPerDay(account, window, options) : 0;
|
||
TimeSpan? wanted = null;
|
||
TimeSpan? every = null;
|
||
TimeSpan? storyInterval = null;
|
||
double? storyChecks = null;
|
||
|
||
if (!contacted)
|
||
{
|
||
lines.Add(new PlanLine("Controlli", NotContactedText(account)));
|
||
}
|
||
else
|
||
{
|
||
// New posts.
|
||
if (CheckPolicy.WantsProfileChecks(account))
|
||
{
|
||
wanted = account.IsFollowed ? CheckPolicy.ProfileCheckInterval(account) : CheckPolicy.VisitInterval(account, window, options.MinimumStoryChecksPerDay);
|
||
every = TimeSpan.FromTicks((long)(wanted.Value.Ticks * MeanCheckJitter * thinning));
|
||
var text = account.IsFollowed
|
||
? $"scoperti dal giro dei profili che segui, di norma entro {Minutes(profile.PauseMin)}–{Minutes(profile.PauseMax)} minuti dalla pubblicazione, {windowText}. Il profilo si riapre solo per riconciliare, {ItalianText.Every(Round(every.Value))} circa."
|
||
: $"controllati {ItalianText.Every(Round(every.Value))} circa, {windowText}.";
|
||
lines.Add(new PlanLine("Nuovi post", text));
|
||
}
|
||
else
|
||
{
|
||
lines.Add(new PlanLine("Nuovi post", "non scaricati con queste impostazioni."));
|
||
}
|
||
|
||
// Stories.
|
||
if (CheckPolicy.WantsStories(account))
|
||
{
|
||
storyInterval = CheckPolicy.StoryInterval(account, window, options.MinimumStoryChecksPerDay);
|
||
storyChecks = Math.Max(options.MinimumStoryChecksPerDay, 1 + (window / (storyInterval.Value * MeanStoryJitter)));
|
||
var how = account.IsFollowed && options.SweepCoversFollowedStories
|
||
? "a ogni giro dei profili che segui e"
|
||
: string.Empty;
|
||
lines.Add(new PlanLine(
|
||
"Storie",
|
||
$"controllate {how} almeno {ItalianText.Number(options.MinimumStoryChecksPerDay)} volte al giorno; fra due controlli passano al massimo {ItalianText.Duration(storyInterval.Value)} circa. Restano 24 ore, quindi nessuna dovrebbe scadere prima di essere vista."
|
||
.Replace(" ", " ", StringComparison.Ordinal)));
|
||
}
|
||
else
|
||
{
|
||
lines.Add(new PlanLine("Storie", "spente."));
|
||
}
|
||
}
|
||
|
||
// History.
|
||
var (backfillText, remaining, days) = Backfill(input, all);
|
||
lines.Add(new PlanLine("Storico", backfillText));
|
||
|
||
// Weight on the daily budget.
|
||
var ownAfter = own / thinning;
|
||
var share = budget > 0 ? ownAfter / budget : 0;
|
||
lines.Add(new PlanLine(
|
||
"Carico",
|
||
contacted
|
||
? $"circa {ItalianText.Decimal(ownAfter, ownAfter < 10 ? 1 : 0)} aperture del profilo al giorno, su {ItalianText.Number(budget)} disponibili ogni giorno per tutti gli account."
|
||
: "nessuno."));
|
||
|
||
if (overBudget)
|
||
{
|
||
warnings.Add(
|
||
$"Con {ItalianText.Count(contactable.Count, "account", "account")} e queste frequenze servirebbero circa {ItalianText.Number((long)Math.Ceiling(totalDemand))} aperture di profili al giorno, "
|
||
+ $"ma il tetto è {ItalianText.Number(budget)}: i controlli si diradano ({(thinning < 1.15 ? "un po' più radi" : $"circa {ItalianText.Decimal(thinning, 1)} volte più radi")}), non si forzano.");
|
||
}
|
||
|
||
var sessionsPerDay = SessionsPerDay(profile, window);
|
||
var homeBudget = profile.Budgets.TryGetValue(ActionKind.Home, out var home) ? home.PerDay : 0;
|
||
if (contactable.Any(a => a.IsFollowed) && homeBudget > 0 && sessionsPerDay * options.SweepProbability > homeBudget)
|
||
{
|
||
warnings.Add($"Il tetto della home ({ItalianText.Number(homeBudget)} al giorno) è più basso del numero di sessioni: alcuni giri dei seguiti salteranno e i nuovi post arriveranno più tardi.");
|
||
}
|
||
|
||
var rampOver = input.GradualStartSince is { } since && input.Now is { } at && at - since >= TimeSpan.FromDays(profile.RampUpDays);
|
||
if (profile.GradualStart && profile.RampUpDays > 0 && !rampOver)
|
||
{
|
||
warnings.Add($"Con l'avvio graduale, nei primi {ItalianText.Count(profile.RampUpDays, "giorno", "giorni")} dopo il collegamento i tetti partono dalla metà: tutto è più lento.");
|
||
}
|
||
|
||
return new AccountPlanEstimate
|
||
{
|
||
Lines = lines,
|
||
Warnings = warnings,
|
||
Contacted = contacted,
|
||
ProfileCheckWanted = wanted,
|
||
ProfileCheckEvery = every,
|
||
StoryInterval = storyInterval,
|
||
StoryChecksPerDay = storyChecks,
|
||
ProfileOpensPerDay = ownAfter,
|
||
TotalProfileOpensPerDay = totalDemand,
|
||
DailyProfileBudget = budget,
|
||
ShareOfDailyBudget = share,
|
||
OverBudget = overBudget,
|
||
BackfillRemainingPosts = remaining,
|
||
BackfillDays = days,
|
||
};
|
||
}
|
||
|
||
/// <summary>Profile openings per day an account asks for (visits, reconciliations, tagged tab).</summary>
|
||
public static double ProfileOpensPerDay(Account account, TimeSpan window, EngineOptions? options = null)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(account);
|
||
options ??= EngineOptions.Default;
|
||
if (!CheckPolicy.IsContactable(account))
|
||
{
|
||
return 0;
|
||
}
|
||
|
||
double visits;
|
||
if (CheckPolicy.WantsProfileChecks(account))
|
||
{
|
||
var interval = account.IsFollowed ? CheckPolicy.ProfileCheckInterval(account) : CheckPolicy.VisitInterval(account, window, options.MinimumStoryChecksPerDay);
|
||
visits = ChecksPerDay(interval * MeanCheckJitter, window);
|
||
}
|
||
else if (!account.IsFollowed && CheckPolicy.WantsStories(account))
|
||
{
|
||
visits = ChecksPerDay(CheckPolicy.StoryInterval(account, window, options.MinimumStoryChecksPerDay) * MeanStoryJitter, window);
|
||
}
|
||
else
|
||
{
|
||
visits = 0;
|
||
}
|
||
|
||
return (account.ContentTypes & ContentTypes.Tagged) != 0 ? visits * 2 : visits;
|
||
}
|
||
|
||
/// <summary>Checks a day at an interval, counting the morning catch-up after the night.</summary>
|
||
public static double ChecksPerDay(TimeSpan interval, TimeSpan window)
|
||
{
|
||
if (interval <= TimeSpan.Zero)
|
||
{
|
||
return 0;
|
||
}
|
||
|
||
if (interval >= TimeSpan.FromHours(24))
|
||
{
|
||
return 24 / interval.TotalHours;
|
||
}
|
||
|
||
return 1 + (window / interval);
|
||
}
|
||
|
||
/// <summary>Sessions a day with median session length and median pause.</summary>
|
||
public static double SessionsPerDay(CautionProfile profile, TimeSpan window)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(profile);
|
||
var session = Math.Sqrt(profile.SessionMin.TotalMinutes * profile.SessionMax.TotalMinutes);
|
||
var pause = Math.Sqrt(profile.PauseMin.TotalMinutes * profile.PauseMax.TotalMinutes);
|
||
return window.TotalMinutes / (session + pause);
|
||
}
|
||
|
||
private static (string Text, int? Remaining, int? Days) Backfill(AccountPlanInput input, List<Account> all)
|
||
{
|
||
var account = input.Account;
|
||
var profile = input.Profile;
|
||
if (account.BackfillCompletedAt is { } done && account.State != AccountState.Backfilling)
|
||
{
|
||
return ($"completato il {ItalianText.Day(DateOnly.FromDateTime(done.UtcDateTime))}.", 0, 0);
|
||
}
|
||
|
||
if (account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from)
|
||
{
|
||
return ($"dipende da quanti post ci sono dopo il {ItalianText.Day(DateOnly.FromDateTime(from.UtcDateTime))}: lo saprò strada facendo.", null, null);
|
||
}
|
||
|
||
if (account.State is not (AccountState.Backfilling or AccountState.UpToDate) || !CheckPolicy.WantsProfileChecks(account))
|
||
{
|
||
return ("nessuno storico da scaricare con queste impostazioni.", null, null);
|
||
}
|
||
|
||
int? target = account.Limits.Depth == HistoryDepth.LastPosts
|
||
? account.Limits.LastPosts is { } last ? Math.Min(last, account.PostCount ?? last) : account.PostCount
|
||
: account.PostCount;
|
||
if (target is null)
|
||
{
|
||
return ("il numero dei post non è ancora noto: lo saprò dopo il primo controllo del profilo.", null, null);
|
||
}
|
||
|
||
var remaining = Math.Max(0, target.Value - input.ArchivedPosts);
|
||
if (remaining == 0)
|
||
{
|
||
return ("tutto già in libreria.", 0, 0);
|
||
}
|
||
|
||
var sharing = Math.Max(1, all.Count(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a)));
|
||
var pagesPerDay = profile.Budgets.TryGetValue(ActionKind.BackfillPage, out var pages) ? pages.PerDay : 0;
|
||
var byBudget = pagesPerDay * input.Options.PostsPerBackfillPage / (double)sharing;
|
||
var perDay = Math.Min(Math.Min(account.Limits.BackfillPostsPerDay, profile.BackfillPostsPerAccountPerDay), byBudget);
|
||
if (perDay <= 0)
|
||
{
|
||
return ("fermo: il limite di storico al giorno è zero.", remaining, null);
|
||
}
|
||
|
||
var days = (int)Math.Ceiling(remaining / perDay);
|
||
var text = $"mancano {ItalianText.Count(remaining, "post", "post")}, servono circa {ItalianText.Count(days, "giorno", "giorni")} ({ItalianText.Number((long)Math.Floor(perDay))} post al giorno"
|
||
+ (sharing switch { <= 1 => string.Empty, 2 => ", a turno con un altro account", _ => $", a turno con altri {ItalianText.Number(sharing - 1)} account" }) + ").";
|
||
return (text, remaining, days);
|
||
}
|
||
|
||
private static string NotContactedText(Account account) => account.State switch
|
||
{
|
||
AccountState.ArchiveOnly => "«Solo archivio»: Febe non contatta questo account.",
|
||
AccountState.Paused => "in pausa: Febe non controlla questo account finché non lo riattivi.",
|
||
AccountState.Unreachable => "non raggiungibile: Febe non lo contatta finché non lo verifichi.",
|
||
_ => "Febe non contatta questo account.",
|
||
};
|
||
|
||
private static string Clock(TimeOnly time) => time.Hour.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + time.Minute.ToString("00", System.Globalization.CultureInfo.InvariantCulture);
|
||
|
||
private static string Minutes(TimeSpan span) => ItalianText.Number((long)Math.Round(span.TotalMinutes));
|
||
|
||
/// <summary>Rounds an interval for display: to 5 minutes under 2 hours, to half an hour above.</summary>
|
||
private static TimeSpan Round(TimeSpan interval) => interval < TimeSpan.FromHours(2)
|
||
? TimeSpan.FromMinutes(Math.Max(5, Math.Round(interval.TotalMinutes / 5) * 5))
|
||
: TimeSpan.FromMinutes(Math.Round(interval.TotalMinutes / 30) * 30);
|
||
}
|