using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Storage; namespace Febe.Core.Engine; /// /// Builds the snapshot of the engine for the interface. Reads only: it never draws from the engine's random source, /// so watching the engine does not change what it does. Future times are indicative and written «verso le». /// public sealed class EngineMonitor : IEngineMonitor { private static readonly ActionKind[] Main = [ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.DataDownload]; private readonly EngineServices _s; private readonly EngineHost _host; internal EngineMonitor(EngineServices services, EngineHost host) { _s = services; _host = host; } public IAsyncEnumerable SubscribeAsync(CancellationToken ct = default) => _s.Events.SubscribeAsync(ct); public async Task GetSnapshotAsync(CancellationToken ct = default) { var now = _s.Clock.Now; var zone = _s.Clock.LocalZone; var runtime = _s.Runtime; var breaker = _s.Breaker.State; var profile = runtime.Profile; var window = await _s.Planner.GetWindowAtAsync(now, ct).ConfigureAwait(false); var nextWindow = window ?? await _s.Planner.GetNextWindowAsync(now, ct).ConfigureAwait(false); var session = runtime.CurrentSession; var mode = ModeOf(runtime, breaker, session, window); var resumes = ResumesAround(mode, runtime, breaker, nextWindow, now); // Read once: the headline and the flag of the snapshot say the same thing. var copyMissing = mode == EngineMode.NotConnected && runtime.SessionCopyMissing; var (headline, details, sidebar) = Texts(mode, copyMissing, runtime, breaker, session, resumes, now, zone); var budgets = _s.Governor.GetEffectiveBudgets(now); var statuses = await _s.Governor.GetBudgetStatusAsync(ct).ConfigureAwait(false); var views = statuses.Select(b => View(b, breaker, now, zone)).ToList(); var accounts = (await _s.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id); return new EngineSnapshot { At = now, Mode = mode, Headline = headline, Details = details, SidebarLine = sidebar, ResumesAround = resumes, Banner = Banner(breaker, now, zone), Profile = profile.Kind, ProfileLine = $"Profilo «{ItalianText.Profile(profile.Kind)}»", ReductionNote = ReductionNote(budgets, now, zone), Today = await StripAsync(now, zone, session, runtime, profile, accounts, ct).ConfigureAwait(false), MainBudgets = [.. Main.Select(k => views.First(v => v.Kind == k))], AllBudgets = views, ProfilesOpenedToday = views.First(v => v.Kind == ActionKind.ProfileOpen), Queue = await QueueAsync(now, zone, mode, session, runtime, accounts, ct).ConfigureAwait(false), RecentActions = await RecentAsync(now, zone, ct).ConfigureAwait(false), SuspendedRecipes = [.. _host.SuspendedRecipes.Select(r => new SuspendedRecipeView(r.Key, ItalianText.Capitalize(SessionComposer.RecipeName(r.Key)), r.Value))], Breaker = breaker, SessionCopyMissing = copyMissing, }; } private static EngineMode ModeOf(EngineRuntime runtime, BreakerState breaker, SessionContext? session, ActiveWindow? window) { if (breaker.Status == BreakerStatus.Challenge) { return EngineMode.StoppedForVerification; } if (breaker.Status == BreakerStatus.Disconnected) { return EngineMode.Disconnected; } if (runtime.IsConnected == false) { return EngineMode.NotConnected; } if (breaker.Status == BreakerStatus.Throttled) { return EngineMode.Throttled; } if (runtime.IsPaused) { return EngineMode.Paused; } if (runtime.UserIsDriving) { return EngineMode.UserDriving; } if (!runtime.IsRunning) { return EngineMode.Off; } if (session is not null) { return EngineMode.InSession; } if (window is null) { return EngineMode.OutsideWindow; } return runtime.HadSessionSinceStart ? EngineMode.Resting : EngineMode.Starting; } private static DateTimeOffset? ResumesAround(EngineMode mode, EngineRuntime runtime, BreakerState breaker, ActiveWindow? nextWindow, DateTimeOffset now) { switch (mode) { case EngineMode.Throttled: return breaker.Until; case EngineMode.Resting or EngineMode.Starting or EngineMode.OutsideWindow: var next = runtime.NextSessionAt; if (mode == EngineMode.OutsideWindow && nextWindow is not null && (next is null || next < nextWindow.Start)) { next = nextWindow.Start; } return next is { } n && n < now ? now : next; default: return null; } } private static (string Headline, IReadOnlyList Details, string Sidebar) Texts( EngineMode mode, bool copyMissing, EngineRuntime runtime, BreakerState breaker, SessionContext? session, DateTimeOffset? resumes, DateTimeOffset now, TimeZoneInfo zone) { var around = resumes is { } r ? ItalianText.Around(r, now, zone) : null; switch (mode) { case EngineMode.InSession when session is not null: { var activity = runtime.Activity ?? "Sto per iniziare il prossimo passo"; var left = session.PlannedEnd - now; var timing = left > TimeSpan.FromMinutes(1) ? $"Iniziata {ItalianText.At(session.StartedAt, zone)}, ancora {ItalianText.Duration(left)} circa." : $"Iniziata {ItalianText.At(session.StartedAt, zone)}, sta per finire."; if (session.OutsideWindowAccountId is not null) { timing += " Controllo fuori fascia confermato da te."; } var sidebar = runtime.Activity is { } a && a.StartsWith("Sto ", StringComparison.Ordinal) ? ItalianText.Capitalize(a[4..]) : "In sessione"; return ("In sessione", [activity, timing], sidebar); } case EngineMode.Resting: return ("In ascolto", [$"Riprende {around ?? "a breve"}.", "Fra una sessione e l'altra il browser resta sulla pagina vuota."], $"Riprende {around ?? "a breve"}"); case EngineMode.Starting: return ("In avvio", [$"Prima sessione {around ?? "a breve"}."], $"Prima sessione {around ?? "a breve"}"); case EngineMode.OutsideWindow: return ("Fuori fascia", ["Fuori dalla fascia oraria Febe non apre nulla da solo.", $"Riprende {around ?? "nei giorni attivi"}."], $"Riprende {around ?? "nei giorni attivi"}"); case EngineMode.Paused: return ("In pausa", ["Messo in pausa da te.", "Premi «Riprendi» per ripartire."], "In pausa"); case EngineMode.Throttled: { var until = breaker.Until is { } u ? ItalianText.Around(u, now, zone) : "più tardi"; return ("Fermo per rallentamento", [$"Instagram ha chiesto di rallentare: riprende {until}.", "Poi i tetti restano dimezzati per 48 ore."], $"Riprende {until}"); } case EngineMode.StoppedForVerification: { var since = breaker.LastSignal is { } s ? $"Fermo {ItalianText.Since(s.At, zone)}. " : string.Empty; return ("Fermo", ["In attesa che tu completi la verifica", since + "Nessun nuovo tentativo finché non premi «Riprendi»."], "Serve il tuo intervento"); } case EngineMode.Disconnected: return ("Scollegato", ["La sessione di Instagram non c'è più.", "Apri il browser, accedi di nuovo, poi premi «Riprendi». Febe non prova a rientrare da solo."], "Accedi di nuovo"); case EngineMode.NotConnected when copyMissing: return ("Serve «Ho finito»", ["Il browser è collegato, ma manca la copia della sessione per le richieste.", "Dalla pagina Collegamento apri il browser e premi «Ho finito» sulla tua pagina iniziale."], "Serve «Ho finito»"); case EngineMode.NotConnected: return ("Non collegato", ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento."], "Non collegato"); case EngineMode.UserDriving: return ("Stai usando il browser", ["Il motore resta fermo finché non hai finito."], "Stai usando il browser"); default: return ("Motore spento", ["Il motore non è in funzione."], "Motore spento"); } } private static StopBanner? Banner(BreakerState breaker, DateTimeOffset now, TimeZoneInfo zone) { var at = breaker.LastSignal is { } s ? ItalianText.At(s.At, zone) : null; return breaker.Status switch { BreakerStatus.Challenge => new StopBanner( BannerLevel.Error, "Instagram chiede una verifica", $"Ho fermato tutto{(at is null ? string.Empty : " " + at)} e non riparto da solo. Apri il browser, completa la verifica a mano, poi premi «Riprendi».", true), BreakerStatus.Disconnected => new StopBanner( BannerLevel.Error, "Instagram ha chiuso la sessione", $"Ho fermato tutto{(at is null ? string.Empty : " " + at)} e non provo a rientrare. Apri il browser, accedi a mano, poi premi «Riprendi».", true), BreakerStatus.Throttled when breaker.Until is { } until => new StopBanner( BannerLevel.Warning, "Instagram ha chiesto di rallentare", $"Ho chiuso la sessione e riparto da solo {ItalianText.Around(until, now, zone)}, con i tetti dimezzati per 48 ore.", false), _ => null, }; } private static string? ReductionNote(EffectiveBudgets budgets, DateTimeOffset now, TimeZoneInfo zone) => budgets.Reduction switch { BudgetReduction.GradualStart => $"Avvio graduale: tetti al {ItalianText.Number((long)Math.Round(budgets.Factor * 100))}%" + (budgets.Until is { } u ? $", pieni {ItalianText.Around(u, now, zone)}" : string.Empty) + ".", BudgetReduction.HalvedAfterThrottle => "Tetti dimezzati dopo un rallentamento" + (budgets.Until is { } h ? $", di nuovo pieni {ItalianText.Around(h, now, zone)}" : string.Empty) + ".", _ => null, }; internal static BudgetView View(BudgetStatus status, BreakerState breaker, DateTimeOffset now, TimeZoneInfo zone) { var data = status.Kind == ActionKind.DataDownload; var usedText = data ? ItalianText.Bytes(status.UsedToday) : ItalianText.Number(status.UsedToday); var limitText = "di " + (data ? ItalianText.Bytes(status.LimitToday) : ItalianText.Number(status.LimitToday)); string note; if (!breaker.AllowsSiteActions && !data) { note = breaker.LastSignal is { } s ? "Fermo " + ItalianText.Since(s.At, zone) : "Fermo"; } else if (status.DailyReached) { note = "Tetto di oggi raggiunto: riprende domani"; } else if (status.HourlyReached) { note = "Tetto orario raggiunto: riprende entro un'ora"; } else if (status.DailyRatio >= BudgetStatus.AmberThreshold) { note = "Quasi al limite per oggi"; } else if (status.HourlyRatio >= BudgetStatus.AmberThreshold) { note = "Quasi al limite di quest'ora"; } else if (data) { note = "Restano " + ItalianText.Bytes(Math.Max(0, status.LimitToday - status.UsedToday)); } else { note = $"In questa ora {ItalianText.Number(status.UsedLastHour ?? 0)} di {ItalianText.Number(status.LimitPerHour ?? 0)}"; } return new BudgetView( status.Kind, ItalianText.CategoryLabel(status.Kind), status.UsedToday, status.LimitToday, status.UsedLastHour, status.LimitPerHour, status.IsAmber, Math.Clamp(status.DailyRatio, 0, 1), usedText, limitText, note); } private async Task StripAsync( DateTimeOffset now, TimeZoneInfo zone, SessionContext? current, EngineRuntime runtime, CautionProfile profile, Dictionary accounts, CancellationToken ct) { var day = LocalCalendar.Today(now, zone); var (dayStart, dayEnd) = LocalCalendar.DayBounds(day, zone); var spans = new List(); // Night and inactive hours: everything of the day outside the windows of yesterday and today. var windows = new List(); foreach (var d in new[] { day.AddDays(-1), day }) { if (await _s.Planner.GetWindowAsync(d, ct).ConfigureAwait(false) is { } w && w.End > dayStart && w.Start < dayEnd) { windows.Add(w); } } var cursor = dayStart; foreach (var w in windows.OrderBy(w => w.Start)) { var start = w.Start < dayStart ? dayStart : w.Start; if (start > cursor) { spans.Add(new StripSpan(StripSpanKind.OutsideWindow, cursor, start, false, "Fuori fascia")); } cursor = w.End > cursor ? w.End : cursor; } if (cursor < dayEnd) { spans.Add(new StripSpan(StripSpanKind.OutsideWindow, cursor, dayEnd, false, "Fuori fascia")); } // Sessions of the day and the rests between them. var sessions = await _s.Storage.Sessions.ListAsync(dayStart, dayEnd, ct).ConfigureAwait(false); DateTimeOffset? previousEnd = null; var activeMinutes = 0.0; foreach (var session in sessions) { var end = session.EndedAt ?? now; var inProgress = session.EndedAt is null && current?.SessionId == session.Id; if (previousEnd is { } rest && session.StartedAt > rest) { spans.Add(new StripSpan(StripSpanKind.Rest, rest, session.StartedAt, false, "Pausa")); } spans.Add(new StripSpan( inProgress ? StripSpanKind.CurrentSession : StripSpanKind.Session, session.StartedAt, end, false, (inProgress ? "Sessione in corso dalle " : "Sessione dalle ") + ItalianText.Clock(session.StartedAt, zone) + (inProgress ? string.Empty : " alle " + ItalianText.Clock(end, zone)))); activeMinutes += ((end < dayEnd ? end : dayEnd) - (session.StartedAt > dayStart ? session.StartedAt : dayStart)).TotalMinutes; previousEnd = end; } if (current is null && previousEnd is { } lastEnd && lastEnd < now && windows.Any(w => w.Contains(now))) { spans.Add(new StripSpan(StripSpanKind.Rest, lastEnd, now, false, "Pausa")); } // Stops. var throttles = 0; foreach (var incident in await _s.Storage.Incidents.ListAsync(dayStart - TimeSpan.FromDays(2), dayEnd, ct).ConfigureAwait(false)) { var end = incident.ResolvedAt ?? (incident.Level == SignalLevel.Throttle ? incident.StoppedUntil ?? now : now); if (end <= dayStart || incident.At >= dayEnd) { continue; } if (incident.Level == SignalLevel.Throttle) { if (incident.At >= dayStart) { throttles++; } spans.Add(new StripSpan(StripSpanKind.Throttle, incident.At, end, incident.ResolvedAt is null, "Fermo per rallentamento")); } else { spans.Add(new StripSpan( StripSpanKind.Stop, incident.At, incident.ResolvedAt ?? now, false, incident.Level == SignalLevel.Challenge ? "Fermo per una verifica" : "Fermo per disconnessione")); } } // Planned sessions, indicative: median length and median pause from the next planned start. if (current is null && runtime.NextSessionAt is { } next && _s.Breaker.State.AllowsSiteActions && !runtime.IsPaused) { var sessionLength = TimeSpan.FromTicks((long)Math.Sqrt((double)profile.SessionMin.Ticks * profile.SessionMax.Ticks)); var pause = TimeSpan.FromTicks((long)Math.Sqrt((double)profile.PauseMin.Ticks * profile.PauseMax.Ticks)); var start = next < now ? now : next; for (var i = 0; i < 40 && start < dayEnd; i++) { var window = windows.FirstOrDefault(w => w.Contains(start)); if (window is null) { break; } var end = start + sessionLength; spans.Add(new StripSpan(StripSpanKind.PlannedSession, start, end < window.End ? end : window.End, true, "Prossima sessione " + ItalianText.Around(start, now, zone))); start = end + pause; } } var newEntries = 0L; foreach (var account in accounts.Values) { foreach (var kind in new[] { EntryKind.Post, EntryKind.Story, EntryKind.Highlight, EntryKind.Tagged }) { newEntries += await _s.Storage.Entries.CountDiscoveredAsync(account.Id, kind, dayStart, dayEnd, ct).ConfigureAwait(false); } } var summary = string.Join(", ", new[] { ItalianText.Count(sessions.Count, "sessione", "sessioni"), ItalianText.Count((long)Math.Round(activeMinutes), "minuto di attività", "minuti di attività"), ItalianText.Count(newEntries, "contenuto nuovo", "contenuti nuovi"), throttles == 0 ? "nessun rallentamento" : ItalianText.Count(throttles, "rallentamento", "rallentamenti"), }); return new DayStrip(day, dayStart, dayEnd, now, summary, [.. spans.OrderBy(s => s.Start).ThenBy(s => s.Kind)]); } private async Task> QueueAsync( DateTimeOffset now, TimeZoneInfo zone, EngineMode mode, SessionContext? session, EngineRuntime runtime, Dictionary accounts, CancellationToken ct) { var suspended = mode is EngineMode.Paused or EngineMode.Throttled or EngineMode.StoppedForVerification or EngineMode.Disconnected or EngineMode.NotConnected or EngineMode.Off; var tasks = await _s.Storage.Tasks.ListPendingAsync(200, ct).ConfigureAwait(false); var items = new List(); foreach (var task in tasks .OrderByDescending(t => t.IsManual) .ThenBy(t => t.DueAt) .ThenByDescending(t => t.Priority) .Take(20)) { Account? account = null; if (task.AccountId is { } id) { accounts.TryGetValue(id, out account); } var (title, detail) = Describe(task, account); DateTimeOffset? around = null; string when; if (suspended) { when = "Sospeso"; } else if (session is not null && task.DueAt <= now) { around = now; when = "In questa sessione"; } else { var t = task.DueAt; var next = runtime.NextSessionAt ?? now; if (t < next) { t = next; } if (t < now) { t = now; } if (await _s.Planner.GetWindowAtAsync(t, ct).ConfigureAwait(false) is null && await _s.Planner.GetNextWindowAsync(t, ct).ConfigureAwait(false) is { } w) { t = w.Start; } around = t; when = ItalianText.Around(t, now, zone); } items.Add(new QueueItem(task.Id, task.Kind, task.AccountId, title, detail, around, when, task.IsManual, suspended)); } return items; } private static (string Title, string Detail) Describe(EngineTask task, Account? account) { var who = ItalianText.Handle(account?.Username); return task.Kind switch { EngineTaskKind.FollowingSweep => ("Giro dei profili che segui", "Home e barra delle storie"), EngineTaskKind.FollowingList => ("Elenco dei profili che segui", "Lettura chiesta da te"), EngineTaskKind.ProfileCheck when task.IsManual => (who, "Controllo chiesto da te"), EngineTaskKind.ProfileCheck when account is { IsFollowed: true } => (who, "Riconciliazione del profilo"), EngineTaskKind.ProfileCheck when account is not null && CheckPolicy.WantsStories(account) => (who, "Nuovi post e storie"), EngineTaskKind.ProfileCheck => (who, "Nuovi post"), EngineTaskKind.AccountStories when task.IsManual => (who, "Storie, chieste da te"), EngineTaskKind.AccountStories when task.Priority > 0 => (who, "Storie segnalate dalla barra"), EngineTaskKind.AccountStories => (who, "Storie"), EngineTaskKind.Backfill when account?.PostCount is { } count => (who, "Storico, " + ItalianText.Count(count, "post sul profilo", "post sul profilo")), EngineTaskKind.Backfill => (who, "Storico"), EngineTaskKind.HighlightCheck => (who, "Storie in evidenza"), EngineTaskKind.TaggedCheck => (who, "Post in cui è taggato"), EngineTaskKind.ReelsCheck => (who, "Reel"), EngineTaskKind.SinglePost => (who, "Post singolo"), _ => (who, task.Kind.ToString()), }; } private async Task> RecentAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct) { var views = new List(); if (_s.Runtime.CurrentSession is not null && _s.Runtime.Activity is { } activity) { views.Add(new RecentActionView(now, ItalianText.Clock(now, zone), activity.StartsWith("Sto ", StringComparison.Ordinal) ? ItalianText.Capitalize(activity[4..]) : activity, string.Empty, "In corso", true)); } var recent = _host.RecentActions(10); if (recent.Count > 0) { views.AddRange(recent.Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false))); return views; } // Just started: the latest lines of the timeline. var events = await _s.Storage.Events.ListAsync(new EventQuery { Limit = 200 }, ct).ConfigureAwait(false); foreach (var e in events.Where(e => e.Code.StartsWith(EngineEventCodes.RecipePrefix, StringComparison.Ordinal)).Take(10)) { var split = e.Message.IndexOf(": ", StringComparison.Ordinal); var title = split > 0 ? e.Message[..split] : e.Message; var detail = split > 0 ? e.Message[(split + 2)..] : string.Empty; views.Add(new RecentActionView(e.At, ItalianText.Clock(e.At, zone), title, detail, null, false)); } return views; } }