diff --git a/docs/decisioni.md b/docs/decisioni.md
index 973812b..f5d5559 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -542,3 +542,5 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-25 | Le sei prove di `PipelineTests.Pulizia` con il limite di 5 minuti girano una per volta, dopo le altre (`[DoNotParallelize]`), senza alzare il limite | In un giro completo in locale, accanto alle suite di conformità H.264/H.265, superavano i 5 minuti; da sole ne prendono circa uno |
| 2026-11-25 | Carattere: il token `--carattere` è esattamente la pila dell'appendice B (`system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`), che `InHouseAssetsTests` confronta con la specifica; sostituisce la pila del 18 novembre con Cantarell, "Noto Sans" e "Liberation Sans" | La specifica fissa la pila; Liberation è fuori anche dall'immagine. Resta per i documenti: l'appendice B non elenca il token `--carattere` |
| 2026-11-25 | Il commit di unione 537517b ha nel messaggio, dopo `Co-Authored-By`, le righe `# Conflicts:` lasciate da git: si accetta così, sapendolo | Rifarlo vorrebbe dire riscrivere la storia di cinque rami locali costruiti sopra; `git interpret-trailers` legge lo stesso il `Co-Authored-By` |
+| 2026-11-25 | D1, prima parte: «Cosa scaricare prima» generale nella chiave `scaricamento.ordine` di `setting` (vuota per l'ordine predefinito storie, evidenza, post, reel, taggati), salvata con i limiti (`downloadOrder` in `/api/settings/limits`). Nel motore, dopo il giro, le storie non segnalate e il resto del lavoro dovuto (non in una sessione leggera) si estraggono da un solo insieme con peso dell'account × peso del tipo (16, 8, 4, 2, 1); le storie segnalate restano davanti, il giro resta primo, Storico dopo. La coda dei file ordina per posizione del tipo dell'elemento, poi per scadenza e scoperta. Ordine per account, colonna del reel e migrazione non ancora fatti | Una sola chiave di `setting` non tocca lo schema, che per la `0002` va concordato con E1 (§8.3). Unire le fasi 3 e 4 è l'unico modo perché l'ordine pesi davvero la visita successiva (§7.2: «il primo tipo viene di norma prima ma non sempre»); le prove del motore, simulazione compresa, restano verdi |
+| 2026-11-25 | Dashboard al posto di Attività (`/dashboard`, `/` e `/attivita` vi portano, prima voce della barra, ritorno dopo l'accesso): anteprima del browser sempre in alto, chiesta ogni secondo mentre il motore lavora e solo con la scheda visibile, e `LiveBrowserPreview` che cattura al più un fotogramma al secondo per tutti. Le miniature della cronologia vengono da `/api/activity/arrived` (account, inizio e fine della ricetta, entrate scoperte in quell'intervallo), chieste solo quando la riga entra in vista e tenute finché la riga resta | La riga della cronologia sa già account e fine; l'inizio della ricetta (`RecentAction.StartedAt`) basta a ritrovare ciò che ha salvato senza una tabella nuova, con l'indice `ix_entry_account_kind`. Un fotogramma al secondo è il massimo di §7.9; la memoria di 1 s nel servizio evita catture doppie con più schede aperte |
diff --git a/docs/guida/Attivita-e-arresti.md b/docs/guida/Attivita-e-arresti.md
index becd8f9..c388b9f 100644
--- a/docs/guida/Attivita-e-arresti.md
+++ b/docs/guida/Attivita-e-arresti.md
@@ -1,18 +1,25 @@
# Attività e arresti
-## La pagina Attività
+## La Dashboard
-**Attività** è il cruscotto del motore. Si aggiorna da sola.
+La **Dashboard** (prima si chiamava Attività) è il cruscotto del motore e la pagina con cui Febe si apre: è la prima
+voce della barra laterale, e il vecchio indirizzo `/attivita` porta lì. Quando il motore lavora puoi restare qui a
+guardare come va lo scaricamento. Si aggiorna da sola.
-- **Adesso:** che cosa sta facendo Febe («In sessione», «In ascolto», «Fuori fascia», «In pausa», «Fermo»), quando
- riprende, e un'**anteprima del browser** di Febe (un fotogramma ogni pochi secondi, non un video; la pagina vuota fra
- una sessione e l'altra).
+- **In alto, l'anteprima del browser**, sempre visibile: la pagina che il browser di Febe sta guardando, che scorre
+ mentre la ricetta la scorre (un fotogramma nuovo al più ogni secondo, non un video; la pagina vuota fra una sessione
+ e l'altra). Accanto, che cosa sta facendo Febe («In sessione», «In ascolto», «Fuori fascia», «In pausa», «Fermo») e
+ quando riprende, e i **limiti di oggi**: profili aperti, storie viste, pagine di storico, dati scaricati, con i
+ numeri; «Tutti i tetti» apre l'elenco completo (orari e giornalieri). Ambra sopra l'80%.
- **Oggi:** la striscia della giornata, 24 ore con le sessioni come tratti, il riposo, i rallentamenti e gli arresti,
e le prossime sessioni con orario indicativo. Gli orari futuri si scrivono sempre «verso le», perché sono estratti a
caso.
-- **Limiti di oggi:** profili aperti, storie viste, pagine di storico, dati scaricati, con i numeri; «Tutti i tetti»
- apre l'elenco completo (orari e giornalieri). Ambra sopra l'80%.
-- **In coda** (con orari indicativi) e **Appena fatto** (le ultime ricette con l'esito).
+- **Cronologia dell'attività:** le ultime ricette con l'esito. Le righe che hanno salvato qualcosa mostrano le
+ miniature di ciò che è arrivato (al più otto, con «+12» per il resto). Un clic su una miniatura apre l'anteprima
+ ingrandita sopra la pagina: la foto o il video (senza audio), l'account, il tipo, la data, le frecce fra i file di
+ quella riga; Esc la chiude. «Apri nella Libreria» apre il visualizzatore su quell'elemento, «Apri l'account» la sua
+ scheda.
+- **In coda**, con orari indicativi: le prime righe, e «Mostra tutta» per le altre.
- **Arresti e rallentamenti** degli ultimi 14 giorni, con segnale, pagina, durata e quando si sono risolti.
- **Avvisi** degli ultimi 14 giorni: verifiche, disconnessioni, fermi e riprese, storici completati, dischi quasi
pieni, formati non riconosciuti, e gli avvisi che non sono arrivati (vedi [Avvisi e Telegram](Avvisi-e-Telegram)).
diff --git a/docs/guida/Limiti-e-comportamento.md b/docs/guida/Limiti-e-comportamento.md
index 430f101..aff704c 100644
--- a/docs/guida/Limiti-e-comportamento.md
+++ b/docs/guida/Limiti-e-comportamento.md
@@ -85,6 +85,15 @@ ritmo «naturale»), limiti dell'account. Risponde con un permesso o con un rifi
l'interruttore, la pausa e la fascia oraria; fra due passi della ricerca, e fra la ricerca e il motore, passa almeno
poco più di un secondo. Vedi [Account e impostazioni](Account-e-impostazioni).
+## Cosa scaricare prima
+
+In fondo alla pagina c'è l'ordine dei tipi: **storie, in evidenza, post, reel, taggati** se non lo cambi. Trascina le
+righe, oppure usa «Su» e «Giù», poi «Salva». Dopo il giro dei profili che segui, che resta sempre il primo, Febe sceglie
+più spesso il tipo che sta più in alto, e nella coda degli scaricamenti passano prima i suoi file. L'ordine pesa le
+scelte, non le rende fisse: non aggiunge controlli, non anticipa nulla e non scavalca tetti, pause e frequenze; un tipo
+in cima senza nulla da controllare non si visita. Le storie scadono dopo 24 ore: più in basso stanno, più è facile che
+scadano prima di essere scaricate. Per ora l'ordine è uno solo per tutti gli account, e un reel conta come post.
+
## Avvio graduale
Se attivo (lo è di partenza), nei primi giorni dopo il primo collegamento e **dopo ogni «Riprendi» che segue una
diff --git a/src/Febe.App/LiveBrowserPreview.cs b/src/Febe.App/LiveBrowserPreview.cs
index 862f57f..624a9ba 100644
--- a/src/Febe.App/LiveBrowserPreview.cs
+++ b/src/Febe.App/LiveBrowserPreview.cs
@@ -6,13 +6,13 @@ using Febe.Web.Engine;
namespace Febe.App;
///
-/// Preview of the browser for the Attività page (mockup 06): one still frame taken with Page.captureScreenshot when the
-/// page asks, at most every few seconds. Reading what the browser shows is not an action toward the site. On the empty
-/// rest page there is nothing to show. The same in both shells.
+/// Preview of the browser for the Dashboard (spec §7.9, mockup 06): one still frame taken with Page.captureScreenshot
+/// when the page asks, at most one a second however many pages ask. Reading what the browser shows is not an action
+/// toward the site. On the empty rest page there is nothing to show. The same in both shells.
///
public sealed class LiveBrowserPreview(IFebeBrowser browser, IClock clock) : IBrowserPreview
{
- private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(4);
+ private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(1);
private readonly SemaphoreSlim _gate = new(1, 1);
private BrowserFrame? _last;
diff --git a/src/Febe.Core/Collection/Downloads/DownloadQueue.cs b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs
index 3467753..4ebd97b 100644
--- a/src/Febe.Core/Collection/Downloads/DownloadQueue.cs
+++ b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs
@@ -242,7 +242,9 @@ public sealed class DownloadQueue
var now = _clock.Now;
var waiting = _retryAt.Count(r => r.Value > now);
var window = (int)Math.Min(10_000L, (long)_options.BatchSize + attempted.Count + waiting);
- var batch = (await _storage.Media.ListPendingDownloadsAsync(window, ct).ConfigureAwait(false))
+ // «Cosa scaricare prima» (spec §6.5, §7.2), read at every batch so that a change counts from the next one.
+ var order = await Febe.Core.Engine.DownloadOrder.LoadAsync(_storage.Settings, ct).ConfigureAwait(false);
+ var batch = (await _storage.Media.ListPendingDownloadsAsync(window, order.EntryKinds(), ct).ConfigureAwait(false))
.Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now))
.Take(_options.BatchSize)
.ToList();
diff --git a/src/Febe.Core/Engine/DownloadOrder.cs b/src/Febe.Core/Engine/DownloadOrder.cs
new file mode 100644
index 0000000..f80e167
--- /dev/null
+++ b/src/Febe.Core/Engine/DownloadOrder.cs
@@ -0,0 +1,160 @@
+using Febe.Core.Domain;
+using Febe.Core.Storage;
+
+namespace Febe.Core.Engine;
+
+/// A type of «Cosa scaricare prima» (spec §7.2): the kinds of recipes of §6.3, grouped as Alberto names them.
+public enum DownloadKind
+{
+ /// «Storie»: Storie di un account.
+ Stories,
+
+ /// «Evidenza»: Raccolta in evidenza.
+ Highlights,
+
+ /// «Post»: Controllo del profilo and Storico, profile pictures included.
+ Posts,
+
+ /// «Reel»: Reel.
+ Reels,
+
+ /// «Taggati»: Taggati.
+ Tagged,
+}
+
+///
+/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in as their
+/// Italian names separated by commas. It weighs the next visit after the Giro dei seguiti (the weight of a kind is
+/// , multiplied by the weight of the account) and the order of the queue of the files (spec §6.5). It
+/// never adds a visit, never brings one forward and never makes the order fixed: it only weighs the choices the engine
+/// already makes among the work that is due and allowed.
+///
+public sealed class DownloadOrder
+{
+ /// The general order (Impostazioni → Limiti e comportamento).
+ public const string SettingKey = "scaricamento.ordine";
+
+ /// The weights of the positions, first to last (spec §7.4 table, «Peso di un tipo nella scelta»).
+ public static readonly IReadOnlyList Weights = [16, 8, 4, 2, 1];
+
+ private static readonly (DownloadKind Kind, string Name)[] Names =
+ [
+ (DownloadKind.Stories, "storie"),
+ (DownloadKind.Highlights, "evidenza"),
+ (DownloadKind.Posts, "post"),
+ (DownloadKind.Reels, "reel"),
+ (DownloadKind.Tagged, "taggati"),
+ ];
+
+ private DownloadOrder(IReadOnlyList kinds) => Kinds = kinds;
+
+ /// Storie, evidenza, post, reel, taggati (spec §7.2, §16 question 19).
+ public static DownloadOrder Default { get; } = new([DownloadKind.Stories, DownloadKind.Highlights, DownloadKind.Posts, DownloadKind.Reels, DownloadKind.Tagged]);
+
+ /// The five kinds, first to last.
+ public IReadOnlyList Kinds { get; }
+
+ /// True when this is the order of .
+ public bool IsDefault => Kinds.SequenceEqual(Default.Kinds);
+
+ /// The Italian name of a kind, as stored and as the interface sends it.
+ public static string NameOf(DownloadKind kind) => Names.First(n => n.Kind == kind).Name;
+
+ ///
+ /// Reads a stored order. Unknown names are left out, a kind named twice counts once and the kinds missing are added
+ /// at the end in the default order, so any text gives the five kinds; null or empty gives .
+ ///
+ public static DownloadOrder Parse(string? text)
+ {
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ return Default;
+ }
+
+ var kinds = new List();
+ foreach (var part in text.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
+ {
+ foreach (var (kind, name) in Names)
+ {
+ if (string.Equals(name, part, StringComparison.OrdinalIgnoreCase) && !kinds.Contains(kind))
+ {
+ kinds.Add(kind);
+ }
+ }
+ }
+
+ kinds.AddRange(Default.Kinds.Where(k => !kinds.Contains(k)));
+ return new DownloadOrder(kinds);
+ }
+
+ /// Builds an order from the names the interface sends; the same rules as .
+ public static DownloadOrder From(IEnumerable names) => Parse(string.Join(',', names));
+
+ /// The stored text: the five names, comma separated.
+ public override string ToString() => string.Join(',', Kinds.Select(NameOf));
+
+ /// 0 for the first kind, 4 for the last.
+ public int Position(DownloadKind kind)
+ {
+ for (var i = 0; i < Kinds.Count; i++)
+ {
+ if (Kinds[i] == kind)
+ {
+ return i;
+ }
+ }
+
+ return Kinds.Count - 1;
+ }
+
+ /// 16, 8, 4, 2 or 1 by the position of the kind.
+ public double Weight(DownloadKind kind) => Weights[Position(kind)];
+
+ ///
+ /// The kind of a task of the engine (spec §7.2); null for the work that no kind weighs: the Giro dei seguiti, which
+ /// stays first, and the reading of the following list.
+ ///
+ public static DownloadKind? KindOf(EngineTaskKind task) => task switch
+ {
+ EngineTaskKind.AccountStories => DownloadKind.Stories,
+ EngineTaskKind.HighlightCheck => DownloadKind.Highlights,
+ EngineTaskKind.ProfileCheck or EngineTaskKind.Backfill or EngineTaskKind.SinglePost => DownloadKind.Posts,
+ EngineTaskKind.ReelsCheck => DownloadKind.Reels,
+ EngineTaskKind.TaggedCheck => DownloadKind.Tagged,
+ _ => null,
+ };
+
+ ///
+ /// The kind of a file in the queue (spec §6.5): profile pictures go with the posts; a reel counts as a post until Febe
+ /// keeps whether a post is a reel (spec §8.3, the flag of entry of D1).
+ ///
+ public static DownloadKind KindOf(EntryKind entry) => entry switch
+ {
+ EntryKind.Story => DownloadKind.Stories,
+ EntryKind.Highlight => DownloadKind.Highlights,
+ EntryKind.Tagged => DownloadKind.Tagged,
+ _ => DownloadKind.Posts,
+ };
+
+ /// The entry kinds in the order of the queue: the position of each , first to last.
+ public IReadOnlyList EntryKinds()
+ {
+ var all = Enum.GetValues();
+ return [.. all.OrderBy(e => Position(KindOf(e))).ThenBy(e => Array.IndexOf(all, e))];
+ }
+
+ /// The general order stored in the settings.
+ public static async Task LoadAsync(ISettingsStore settings, CancellationToken ct = default)
+ {
+ ArgumentNullException.ThrowIfNull(settings);
+ return Parse(await settings.GetAsync(SettingKey, ct).ConfigureAwait(false));
+ }
+
+ /// Stores the general order; the default is stored as no value («come le impostazioni predefinite»).
+ public static Task SaveAsync(ISettingsStore settings, DownloadOrder order, CancellationToken ct = default)
+ {
+ ArgumentNullException.ThrowIfNull(settings);
+ ArgumentNullException.ThrowIfNull(order);
+ return settings.SetAsync(SettingKey, order.IsDefault ? null : order.ToString(), ct);
+ }
+}
diff --git a/src/Febe.Core/Engine/Monitor.cs b/src/Febe.Core/Engine/Monitor.cs
index b50be18..3d10653 100644
--- a/src/Febe.Core/Engine/Monitor.cs
+++ b/src/Febe.Core/Engine/Monitor.cs
@@ -524,7 +524,16 @@ public sealed class EngineMonitor : IEngineMonitor
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)));
+ views.AddRange(recent.Select(r => new RecentActionView(
+ r.At,
+ ItalianText.Clock(r.At, zone),
+ r.Title,
+ r.Detail,
+ r.Badge,
+ false,
+ r.NewEntries > 0 ? r.AccountId : null,
+ r.NewEntries > 0 ? r.StartedAt : null,
+ r.NewEntries)));
return views;
}
diff --git a/src/Febe.Core/Engine/MonitorModels.cs b/src/Febe.Core/Engine/MonitorModels.cs
index 972286a..c2ed3d0 100644
--- a/src/Febe.Core/Engine/MonitorModels.cs
+++ b/src/Febe.Core/Engine/MonitorModels.cs
@@ -136,8 +136,21 @@ public sealed record BudgetView(
/// The engine is stopped or paused.
public sealed record QueueItem(long TaskId, EngineTaskKind Kind, long? AccountId, string Title, string Detail, DateTimeOffset? Around, string When, bool IsManual, bool Suspended);
-/// A line of «Appena fatto».
-public sealed record RecentActionView(DateTimeOffset At, string Time, string Title, string Detail, string? Badge, bool InProgress);
+/// A line of the history of the Dashboard («Appena fatto»).
+/// Account of the recipe, when it has one and saved something: with and
+/// it tells the page which entries arrived, for their thumbnails (spec §7.9, tappa D1).
+/// When the recipe started.
+/// Entries saved by the recipe.
+public sealed record RecentActionView(
+ DateTimeOffset At,
+ string Time,
+ string Title,
+ string Detail,
+ string? Badge,
+ bool InProgress,
+ long? AccountId = null,
+ DateTimeOffset? From = null,
+ int NewEntries = 0);
/// A recipe suspended after repeated unrecognized formats.
public sealed record SuspendedRecipeView(RecipeKind Recipe, string Name, DateTimeOffset Since);
diff --git a/src/Febe.Core/Engine/RecentActions.cs b/src/Febe.Core/Engine/RecentActions.cs
index 53d6d7c..d70c92a 100644
--- a/src/Febe.Core/Engine/RecentActions.cs
+++ b/src/Febe.Core/Engine/RecentActions.cs
@@ -8,6 +8,8 @@ namespace Febe.Core.Engine;
/// «2 storie nuove», «Nessuna novità».
/// How it ended.
/// New entries found.
+/// When it started: the entries of the account discovered from then to are
+/// the ones it saved (thumbnails of the Dashboard, spec §7.9).
public sealed record RecentAction(
DateTimeOffset At,
RecipeKind Recipe,
@@ -15,7 +17,8 @@ public sealed record RecentAction(
string Title,
string Detail,
RecipeStatus Status,
- int NewEntries)
+ int NewEntries,
+ DateTimeOffset? StartedAt = null)
{
/// Short label of the outcome for a badge («Scaricato», «Rimandato»...); null when nothing to say.
public string? Badge => Status switch
diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs
index 92136d9..6e05b38 100644
--- a/src/Febe.Core/Engine/SessionComposer.cs
+++ b/src/Febe.Core/Engine/SessionComposer.cs
@@ -84,23 +84,39 @@ internal sealed class SessionComposer
await RunSweepAsync(sweepTask, accounts, state, ct).ConfigureAwait(false);
}
- // 3. Stories: flagged by the stories bar first, then the due ones (visits of profiles not followed included).
+ // 3. The work that is due: stories flagged by the stories bar first, then, drawn one after the other with the
+ // weight of the account times the weight of its kind in «Cosa scaricare prima» (spec §7.2, tappa D1), the other
+ // stories (visits of profiles not followed included) and, except in a light session, the expired profile checks,
+ // highlight collections and other planned work. The order weighs the choices, it does not add any.
if (!Over(state, ct))
{
var now = Clock.Now;
var window = await WindowLengthAsync(now, ct).ConfigureAwait(false);
+ var order = await DownloadOrder.LoadAsync(Store.Settings, ct).ConfigureAwait(false);
due = await Store.Tasks.PeekDueAsync(now, 1000, ct).ConfigureAwait(false);
await RunManualTasksAsync(due, accounts, state, ct).ConfigureAwait(false);
var storyWork = due.Where(t => !t.IsManual && IsStoryWork(t, accounts, now)).ToList();
var flagged = storyWork.Where(t => t.Priority >= Options.FlaggedStoriesPriority);
- var rest = storyWork.Where(t => t.Priority < Options.FlaggedStoriesPriority);
- foreach (var task in Weighted(flagged, accounts, now, window).Concat(Weighted(rest, accounts, now, window)))
+ var rest = storyWork.Where(t => t.Priority < Options.FlaggedStoriesPriority).ToList();
+ var other = light
+ ? []
+ : due.Where(t => !t.IsManual
+ && t.Kind is not (EngineTaskKind.FollowingSweep or EngineTaskKind.Backfill or EngineTaskKind.AccountStories)
+ && !storyWork.Contains(t)).ToList();
+ var storyIds = rest.Select(t => t.Id).ToHashSet();
+ foreach (var task in Weighted(flagged, accounts, now, window, order).Concat(Weighted(rest.Concat(other), accounts, now, window, order)))
{
if (Over(state, ct))
{
break;
}
+ // A profile already opened in this session is not opened again for the other work: it waits for the next one.
+ if (!storyIds.Contains(task.Id) && task.Priority < Options.FlaggedStoriesPriority && task.AccountId is { } visited && state.Visited.Contains(visited))
+ {
+ continue;
+ }
+
await RunScheduledAsync(task, accounts, state, ct).ConfigureAwait(false);
}
@@ -133,28 +149,7 @@ internal sealed class SessionComposer
}
}
- // 4. Expired profile checks, highlight collections and other planned work.
- if (!light && !Over(state, ct))
- {
- var now = Clock.Now;
- var window = await WindowLengthAsync(now, ct).ConfigureAwait(false);
- due = await Store.Tasks.PeekDueAsync(now, 1000, ct).ConfigureAwait(false);
- await RunManualTasksAsync(due, accounts, state, ct).ConfigureAwait(false);
- var other = due.Where(t => !t.IsManual
- && t.Kind is not (EngineTaskKind.FollowingSweep or EngineTaskKind.Backfill or EngineTaskKind.AccountStories)
- && !(t.AccountId is { } id && state.Visited.Contains(id)));
- foreach (var task in Weighted(other, accounts, now, window))
- {
- if (Over(state, ct))
- {
- break;
- }
-
- await RunScheduledAsync(task, accounts, state, ct).ConfigureAwait(false);
- }
- }
-
- // 5. A few pages of history on one account.
+ // 4. A few pages of history on one account.
if (!light && !Over(state, ct))
{
await RunBackfillAsync(state, ct).ConfigureAwait(false);
@@ -470,21 +465,26 @@ internal sealed class SessionComposer
&& (account.NextStoriesCheckAt is null || account.NextStoriesCheckAt <= now);
}
- private IEnumerable Weighted(IEnumerable tasks, Dictionary accounts, DateTimeOffset now, TimeSpan window)
+ private IEnumerable Weighted(IEnumerable tasks, Dictionary accounts, DateTimeOffset now, TimeSpan window, DownloadOrder order)
{
var items = new List<(EngineTask, double)>();
foreach (var task in tasks)
{
+ // The visit of a profile not followed whose stories are due is story work (spec §7.2): it weighs as stories.
+ var kind = task.Kind == EngineTaskKind.ProfileCheck && IsStoryWork(task, accounts, now)
+ ? DownloadKind.Stories
+ : DownloadOrder.KindOf(task.Kind);
+ var kindWeight = kind is { } k ? order.Weight(k) : 1;
if (task.AccountId is { } id && accounts.TryGetValue(id, out var account))
{
var interval = task.Kind == EngineTaskKind.AccountStories
? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay)
: VisitInterval(account, window);
- items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval)));
+ items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval) * kindWeight));
}
else
{
- items.Add((task, 2));
+ items.Add((task, 2 * kindWeight));
}
}
@@ -907,6 +907,7 @@ internal sealed class SessionComposer
}
state.Recipes++;
+ var startedAt = Clock.Now;
_s.Runtime.Activity = ActivityText(request.Kind, account);
_s.Events.Publish(EngineNotificationKind.ActivityChanged);
RecipeOutcome outcome;
@@ -946,7 +947,7 @@ internal sealed class SessionComposer
await _queueGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
- await ApplyOutcomeAsync(task, request, account, outcome, state).ConfigureAwait(false);
+ await ApplyOutcomeAsync(task, request, account, outcome, state, startedAt).ConfigureAwait(false);
}
finally
{
@@ -978,7 +979,7 @@ internal sealed class SessionComposer
}
}
- private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state)
+ private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state, DateTimeOffset startedAt)
{
// Bookkeeping always completes, even when the session has just been cancelled. Independent writes are queued
// together (the single writer keeps their order and commits them in one transaction).
@@ -1132,7 +1133,7 @@ internal sealed class SessionComposer
}
var (title, detail) = Describe(kind, account, outcome);
- _recent.Add(new RecentAction(now, kind, account?.Id, title, detail, outcome.Status, outcome.NewEntries));
+ _recent.Add(new RecentAction(now, kind, account?.Id, title, detail, outcome.Status, outcome.NewEntries, startedAt));
var severity = outcome.Status switch
{
RecipeStatus.Completed => outcome.NewEntries > 0 ? EventSeverity.Success : EventSeverity.Info,
diff --git a/src/Febe.Core/Storage/IEntryStore.cs b/src/Febe.Core/Storage/IEntryStore.cs
index 82900ff..f7824c0 100644
--- a/src/Febe.Core/Storage/IEntryStore.cs
+++ b/src/Febe.Core/Storage/IEntryStore.cs
@@ -60,6 +60,12 @@ public interface IEntryStore
/// Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).
Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
+ ///
+ /// What a recipe saved (spec §7.9, thumbnails of the history of the Dashboard): the entries of the account discovered
+ /// in [from, to], newest first, at most , with how many there are in all.
+ ///
+ Task ListDiscoveredAsync(long accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default);
+
/// Entries of (account, kind) discovered in [from, to): per-account daily backfill limit.
Task CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default);
@@ -74,3 +80,6 @@ public interface IEntryStore
/// Tiles for given entries, in the given order (e.g. the items of a highlight collection).
Task> GetTilesAsync(IReadOnlyList entryIds, CancellationToken ct = default);
}
+
+/// Entries saved by a recipe: the first ones, newest first, and how many in all.
+public sealed record ArrivedEntries(IReadOnlyList EntryIds, int Total);
diff --git a/src/Febe.Core/Storage/IMediaStore.cs b/src/Febe.Core/Storage/IMediaStore.cs
index 7ff7546..a54aab0 100644
--- a/src/Febe.Core/Storage/IMediaStore.cs
+++ b/src/Febe.Core/Storage/IMediaStore.cs
@@ -30,6 +30,13 @@ public interface IMediaStore
///
Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default);
+ ///
+ /// Files waiting to be downloaded in the order of «Cosa scaricare prima» (spec §6.5, §7.2): the files of the entry kind
+ /// that comes first in , then the other kinds in that order, and within a kind the ones
+ /// that expire first, then the oldest waiting. A kind left out of the list goes last.
+ ///
+ Task> ListPendingDownloadsAsync(int limit, IReadOnlyList kindOrder, CancellationToken ct = default);
+
/// Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»).
Task CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default);
diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs
index 0e831c6..b26129e 100644
--- a/src/Febe.Data/Stores/EntryStore.cs
+++ b/src/Febe.Data/Stores/EntryStore.cs
@@ -197,6 +197,29 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
ct);
}
+ public Task ListDiscoveredAsync(long accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default) =>
+ db.ReadAsync(
+ c =>
+ {
+ var ids = new List();
+ using (var r = c.Command("""
+ SELECT id FROM entry WHERE account_id = @a AND discovered_at >= @f AND discovered_at <= @t AND state <> 'Deleted'
+ ORDER BY discovered_at DESC, id DESC LIMIT @l
+ """).With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@l", (long)Math.Clamp(limit, 1, 100)).ExecuteReader())
+ {
+ while (r.Read())
+ {
+ ids.Add(r.GetInt64(0));
+ }
+ }
+
+ var total = (int)c.Command("""
+ SELECT COUNT(*) FROM entry WHERE account_id = @a AND discovered_at >= @f AND discovered_at <= @t AND state <> 'Deleted'
+ """).With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ScalarInt64();
+ return new ArrivedEntries(ids, total);
+ },
+ ct);
+
public Task CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync(
c => (int)c.Command("""
diff --git a/src/Febe.Data/Stores/MediaStore.cs b/src/Febe.Data/Stores/MediaStore.cs
index 8ad209b..f71c5cd 100644
--- a/src/Febe.Data/Stores/MediaStore.cs
+++ b/src/Febe.Data/Stores/MediaStore.cs
@@ -81,6 +81,24 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore
ct);
public Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) =>
+ ListPendingAsync(limit, "(e.kind = 'Story') DESC", ct);
+
+ public Task> ListPendingDownloadsAsync(int limit, IReadOnlyList kindOrder, CancellationToken ct = default)
+ {
+ ArgumentNullException.ThrowIfNull(kindOrder);
+
+ // The names are those of the enum, never text from outside: the rank is written into the query.
+ var rank = new System.Text.StringBuilder("CASE e.kind");
+ for (var i = 0; i < kindOrder.Count; i++)
+ {
+ rank.Append(" WHEN '").Append(kindOrder[i].ToString()).Append("' THEN ").Append(i.ToString(System.Globalization.CultureInfo.InvariantCulture));
+ }
+
+ rank.Append(" ELSE ").Append(kindOrder.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)).Append(" END");
+ return ListPendingAsync(limit, rank.ToString(), ct);
+ }
+
+ private Task> ListPendingAsync(int limit, string first, CancellationToken ct) =>
db.ReadAsync>(
c =>
{
@@ -88,7 +106,7 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore
SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted'
- ORDER BY (e.kind = 'Story') DESC, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position
+ ORDER BY {first}, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position
LIMIT @limit
""").With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader();
var list = new List();
diff --git a/src/Febe.Server/DemoCommand.cs b/src/Febe.Server/DemoCommand.cs
index adf4a25..7beff49 100644
--- a/src/Febe.Server/DemoCommand.cs
+++ b/src/Febe.Server/DemoCommand.cs
@@ -54,7 +54,7 @@ internal static class DemoCommand
}
await using var running = demo;
- var address = new Uri(demo.Address, "/libreria");
+ var address = new Uri(demo.Address, "/dashboard");
await output.WriteLineAsync($"Pronto: {demo.World.Accounts} account e {Febe.Core.Engine.ItalianText.Number(demo.World.Entries)} elementi dimostrativi.").ConfigureAwait(false);
await output.WriteLineAsync($"Apri {address}").ConfigureAwait(false);
await output.WriteLineAsync("Scene: ?scena=normale, sessione, fermo, scollegato, alvolante; tema: ?tema=chiaro o scuro; veste: ?veste=desktop o docker.").ConfigureAwait(false);
diff --git a/src/Febe.Web/Api/ActivityApi.cs b/src/Febe.Web/Api/ActivityApi.cs
index 7873d4f..d868ea7 100644
--- a/src/Febe.Web/Api/ActivityApi.cs
+++ b/src/Febe.Web/Api/ActivityApi.cs
@@ -23,6 +23,15 @@ public static class ActivityApi
/// Days of stops shown by the page.
public const int HistoryDays = 14;
+ /// Thumbnails of a line of the history (spec §7.9: at most eight, «+12» for the rest).
+ public const int ArrivedShown = 8;
+
+ /// The most the arrows of the enlarged preview walk through in one line.
+ public const int ArrivedLimit = 60;
+
+ private static bool TryTime(string text, out DateTimeOffset at) =>
+ DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out at);
+
///
/// «Esporta il rapporto di diagnostica» (issue #39, spec §7.9): the traces of the engine sessions of the last two
/// weeks as a JSON file to send, with no data value in it. Also answered with a configuration problem, where the
@@ -38,6 +47,24 @@ public static class ActivityApi
endpoints.MapGet("/api/alerts", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await AlertsAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AlertListDto));
+ // The thumbnails of a line of the history (spec §7.9): asked by the page only when the line is in view.
+ endpoints.MapGet("/api/activity/arrived", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
+ {
+ var query = context.Request.Query;
+ if (!long.TryParse(query["account"].ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out var account)
+ || !TryTime(query["from"].ToString(), out var from)
+ || !TryTime(query["to"].ToString(), out var to)
+ || to < from)
+ {
+ throw new BadRequestException("Indica account, inizio e fine.");
+ }
+
+ var limit = int.TryParse(query["limit"].ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? Math.Clamp(n, 1, ArrivedLimit) : ArrivedShown;
+ var arrived = await storage.Entries.ListDiscoveredAsync(account, from, to, limit, ct).ConfigureAwait(false);
+ var tiles = await storage.Entries.GetTilesAsync(arrived.EntryIds, ct).ConfigureAwait(false);
+ return ApiHttp.Json(new ArrivedDto([.. tiles.Select(t => LibraryApi.Tile(t, clock.LocalZone))], arrived.Total), FebeJsonContext.Default.ArrivedDto);
+ });
+
endpoints.MapGet("/api/browser/preview", async (IBrowserPreview preview, CancellationToken ct) =>
{
var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs
index 71faf7d..d0757a6 100644
--- a/src/Febe.Web/Api/Dtos.cs
+++ b/src/Febe.Web/Api/Dtos.cs
@@ -58,6 +58,9 @@ public sealed record TileDto(
/// A window of tiles; cursors continue it (null: nothing more that way).
public sealed record LibraryPageDto(IReadOnlyList Tiles, string? Older, string? Newer);
+/// What a line of the history of the Dashboard saved (spec §7.9): the first tiles and how many in all.
+public sealed record ArrivedDto(IReadOnlyList Tiles, int Total);
+
/// A day of the mosaic: its count and the cursor that starts at its end.
public sealed record DayDto(string Day, int Count, string Cursor);
diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs
index 1edd824..636764e 100644
--- a/src/Febe.Web/Api/FebeJsonContext.cs
+++ b/src/Febe.Web/Api/FebeJsonContext.cs
@@ -55,6 +55,7 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(IncidentListDto))]
[JsonSerializable(typeof(AlertListDto))]
[JsonSerializable(typeof(BrowserPreviewDto))]
+[JsonSerializable(typeof(ArrivedDto))]
[JsonSerializable(typeof(DuplicateCountsDto))]
[JsonSerializable(typeof(GeneralSettingsDto))]
[JsonSerializable(typeof(GeneralSettingsRequest))]
diff --git a/src/Febe.Web/Api/Part2Dtos.cs b/src/Febe.Web/Api/Part2Dtos.cs
index b9e03aa..8fb8548 100644
--- a/src/Febe.Web/Api/Part2Dtos.cs
+++ b/src/Febe.Web/Api/Part2Dtos.cs
@@ -164,10 +164,14 @@ public sealed record LimitsDto(
bool GradualStart,
IReadOnlyList ActiveDays,
LimitRulesDto Rules,
- IReadOnlyList Stops);
+ IReadOnlyList Stops,
+ IReadOnlyList? DownloadOrder = null);
-/// Saves the limits; is read when is custom.
-public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList ActiveDays);
+///
+/// Saves the limits; is read when is custom. is
+/// «Cosa scaricare prima» (spec §7.2), the names of the five kinds first to last; null keeps the stored order.
+///
+public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList ActiveDays, IReadOnlyList? DownloadOrder = null);
// ---------------------------------------------------------------- settings: notifications (spec §13.3)
diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs
index 453999e..baee7ae 100644
--- a/src/Febe.Web/Api/SettingsApi.cs
+++ b/src/Febe.Web/Api/SettingsApi.cs
@@ -128,7 +128,7 @@ public static class SettingsApi
// ------------------------------------------------------------------------------------------ Limiti e comportamento
endpoints.MapGet("/api/settings/limits", async (IFebeStorage storage, CancellationToken ct) =>
- ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto));
+ ApiHttp.Json(await LimitsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.LimitsDto));
endpoints.MapPut("/api/settings/limits", async (HttpContext context, IFebeStorage storage, IEngineSettingsControl engine, CancellationToken ct) =>
{
@@ -142,7 +142,13 @@ public static class SettingsApi
}
await engine.ApplyAsync(settings, ct).ConfigureAwait(false);
- return ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto);
+ if (body.DownloadOrder is { } names)
+ {
+ // The engine reads the order at every session and the queue at every batch: nothing else to tell them.
+ await DownloadOrder.SaveAsync(storage.Settings, DownloadOrder.From(names), ct).ConfigureAwait(false);
+ }
+
+ return ApiHttp.Json(await LimitsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.LimitsDto);
});
// ------------------------------------------------------------------------------------------ Notifiche
@@ -364,6 +370,14 @@ public static class SettingsApi
// ---------------------------------------------------------------------------------------------- Limiti
+ /// The limits with «Cosa scaricare prima» (spec §7.2), as stored.
+ private static async Task LimitsAsync(IFebeStorage storage, CancellationToken ct)
+ {
+ var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
+ var order = await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
+ return Limits(settings) with { DownloadOrder = [.. order.Kinds.Select(DownloadOrder.NameOf)] };
+ }
+
public static LimitsDto Limits(EngineSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs
index cc9b876..2d9ed64 100644
--- a/src/Febe.Web/Demo/DemoEngine.cs
+++ b/src/Febe.Web/Demo/DemoEngine.cs
@@ -351,7 +351,7 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
}
list.AddRange(world.Recent.Where(r => r.At <= (scene == DemoScene.Stopped ? stopAt : now))
- .Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false)));
+ .Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false, r.AccountId, r.From, r.NewEntries)));
return list.Take(10).ToList();
}
}
diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs
index f0c0b11..cecf818 100644
--- a/src/Febe.Web/Demo/DemoSeeder.cs
+++ b/src/Febe.Web/Demo/DemoSeeder.cs
@@ -11,7 +11,9 @@ namespace Febe.Web.Demo;
public sealed record DemoSession(DateTimeOffset Start, DateTimeOffset End, int ProfilesOpened, int StoriesViewed, int HistoryPages, long Bytes, int NewEntries);
/// A line of «Appena fatto».
-public sealed record DemoAction(DateTimeOffset At, string Title, string Detail, string? Badge);
+/// A line of the history of the demo; and when it saved something
+/// (its thumbnails on the Dashboard, spec §7.9).
+public sealed record DemoAction(DateTimeOffset At, string Title, string Detail, string? Badge, long? AccountId = null, DateTimeOffset? From = null, int NewEntries = 0);
/// Everything the demo engine needs to tell a coherent day (spec §10.6: «i conteggi tornano, gli orari sono plausibili»).
public sealed class DemoWorld
@@ -563,7 +565,16 @@ public static class DemoSeeder
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;
- return new DemoAction(e.At, title, Capitalize(detail), e.Severity == EventSeverity.Success ? "Scaricato" : null);
+ if (e.Severity != EventSeverity.Success || e.AccountId is not { } accountId)
+ {
+ return new DemoAction(e.At, title, Capitalize(detail), e.Severity == EventSeverity.Success ? "Scaricato" : null);
+ }
+
+ // What this visit found: the entries of the account discovered after its previous visit (at most an hour back).
+ var previous = events.Where(x => x.AccountId == accountId && x.At < e.At).Select(x => x.At).Append(e.At - TimeSpan.FromHours(1)).Max();
+ var from = previous.AddMilliseconds(1);
+ var found = created.Count(c => c.AccountId == accountId && c.Discovered >= from && c.Discovered <= e.At);
+ return new DemoAction(e.At, title, Capitalize(detail), "Scaricato", found > 0 ? accountId : null, found > 0 ? from : null, found);
})
.ToList();
diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md
index 0ca8951..7bad2b7 100644
--- a/src/Febe.Web/LEGGIMI.md
+++ b/src/Febe.Web/LEGGIMI.md
@@ -170,7 +170,7 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da
### Una pagina nuova
-1. Una riga in `js/routes.js`: `{ pattern: /^\/attivita\/?$/, nav: 'attivita', page: () => import('./pages/activity.js') }`
+1. Una riga in `js/routes.js`: `{ pattern: /^\/dashboard\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') }`
(i gruppi con nome del `pattern` arrivano in `route.params`; `data` aggiunge valori fissi).
2. Il modulo esporta `export default { async mount(page, route) { … } }`. `route` ha `path`, `params`, `query`
(`URLSearchParams`). Se `mount` restituisce una funzione, viene chiamata quando si lascia la pagina.
@@ -184,7 +184,7 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da
`onEngine`/`onLibrary` non si iscrivono e `onLeave` esegue subito la funzione. Dopo un `await` controlla
`page.signal.aborted` prima di prendere risorse che durano (il browser, una vista remota, un timer).
La striscia rossa di arresto (mockup 11) la mette la cornice su ogni pagina, da sola.
-4. Pagine della seconda parte: `pages/activity.js` (`/attivita`, con `day-strip.js` per la striscia del giorno),
+4. Pagine della seconda parte: `pages/dashboard.js` (`/dashboard`, prima `/attivita`, con `day-strip.js` per la striscia del giorno),
`pages/settings.js` (`/impostazioni/{generali|limiti|collegamento|notifiche|dati|informazioni}`, un modulo
`settings-*.js` per sezione; `connection.js` per il collegamento), `pages/browser.js` (`/browser`, vista remota della
veste Docker, `remote-view.js` parla con `/api/vista` secondo `Connection/PROTOCOLLO.md`), `pages/import.js`
diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css
index 29b12cf..59bdc93 100644
--- a/src/Febe.Web/wwwroot/css/febe.css
+++ b/src/Febe.Web/wwwroot/css/febe.css
@@ -654,7 +654,53 @@ a.stato:hover{border-color:var(--bordo-forte)}
/* ---------- attività ---------- */
.attivita{display:flex;flex-direction:column;gap:24px;padding-bottom:8px}
.attivita > div:empty{display:none}
-[data-pagina=attivita] .arresto .riprendi-arresto{display:none}
+[data-pagina=dashboard] .arresto .riprendi-arresto{display:none}
+/* Dashboard (spec §7.9, tappa D1): compact, preview always visible at the top with what is happening and the budgets */
+.dashboard{gap:18px}
+.cruscotto{display:flex;align-items:stretch;gap:20px;padding:14px 16px}
+.cruscotto .anteprima{width:420px}
+.cruscotto .anteprima .quadro{height:236px}
+.cruscotto-lato{flex:1;min-width:0;display:flex;flex-direction:column;justify-content:space-between;gap:14px}
+.cruscotto-lato .ora-testo .cosa{margin-top:8px}
+.blocco-tetti .testa-blocco{margin-bottom:6px}
+.blocco-tetti h2{margin:0;font-size:14px;font-weight:650}
+.blocco-tetti .tetti{border:1px solid var(--bordo);border-radius:8px}
+.blocco-tetti .tetto{padding:9px 12px 10px;gap:5px}
+.blocco-tetti .tetto .valore b{font-size:17px}
+.oggi-basso .striscia{height:22px}
+.storia-coda{grid-template-columns:minmax(0,1.6fr) minmax(0,1fr)}
+.elenco-attivita.stretto li{min-height:46px;padding:8px 14px}
+.storia-righe li{align-items:flex-start}
+.piede-elenco{display:block;width:100%;padding:9px 14px;text-align:left;border-top:1px solid var(--bordo)}
+.miniature{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px;min-height:44px}
+.miniatura{position:relative;width:44px;height:44px;padding:0;border:0;border-radius:3px;overflow:hidden;background:var(--rialzo);cursor:zoom-in;flex:none}
+.miniatura img{display:block;width:100%;height:100%;object-fit:cover}
+.miniatura .vuota{display:flex;width:100%;height:100%;align-items:center;justify-content:center;color:var(--testo-3)}
+.miniatura .segni{position:absolute;top:2px;right:2px;display:flex;gap:2px;color:#fff;font-size:9.5px;text-shadow:0 0 3px rgba(0,0,0,.7)}
+.miniatura .anello svg.ic{width:11px;height:11px}
+.miniatura:focus-visible{outline:2px solid var(--accento);outline-offset:1px}
+.miniature-altre{display:inline-flex;align-items:center;justify-content:center;width:44px;height:44px;border-radius:3px;background:var(--rialzo);color:var(--testo-2);font-size:12px}
+.anteprima-cronologia{width:min(860px,calc(100vw - 32px));border-radius:14px}
+.anteprima-scena{display:flex;align-items:center;gap:10px}
+.anteprima-palco{flex:1;min-width:0;height:min(62vh,560px);display:flex;align-items:center;justify-content:center;background:#161616;border-radius:8px;overflow:hidden}
+.anteprima-palco img,.anteprima-palco video{max-width:100%;max-height:100%;object-fit:contain}
+.anteprima-neutra{display:flex;flex-direction:column;align-items:center;gap:8px;color:rgba(255,255,255,.7);font-size:13px}
+.anteprima-dida{display:flex;flex-wrap:wrap;gap:6px 12px;margin-top:10px;font-size:13px}
+.btn.tondo{width:36px;height:36px;padding:0;border-radius:50%;justify-content:center;flex:none}
+/* «Cosa scaricare prima» (spec §7.2) */
+.ordine-tipi{list-style:none;margin:0;padding:0}
+.riga-ordine{display:flex;align-items:center;gap:12px;padding:8px 12px;border-bottom:1px solid var(--bordo);background:var(--superficie)}
+.riga-ordine:last-child{border-bottom:0}
+.riga-ordine.trascinata{opacity:.55}
+.riga-ordine .maniglia{cursor:grab;color:var(--testo-3);display:inline-flex}
+.riga-ordine .posizione{width:16px;color:var(--testo-2)}
+.riga-ordine .destra{margin-left:auto;display:flex;gap:4px}
+.riga-sotto{display:flex;align-items:center;gap:12px;margin-top:8px}
+@media (max-width:1000px){
+ .cruscotto{flex-direction:column}
+ .cruscotto .anteprima{width:100%}
+ .storia-coda{grid-template-columns:minmax(0,1fr)}
+}
.ora-pannello{display:flex;align-items:center;gap:24px;padding:18px 18px 18px 24px;min-height:142px}
.ora-testo{flex:1;min-width:0}
.ora-testo .riga{display:flex;align-items:center;gap:10px}
diff --git a/src/Febe.Web/wwwroot/icone/chevron-up.svg b/src/Febe.Web/wwwroot/icone/chevron-up.svg
new file mode 100644
index 0000000..c6973da
--- /dev/null
+++ b/src/Febe.Web/wwwroot/icone/chevron-up.svg
@@ -0,0 +1,3 @@
+
diff --git a/src/Febe.Web/wwwroot/icone/grip-vertical.svg b/src/Febe.Web/wwwroot/icone/grip-vertical.svg
new file mode 100644
index 0000000..047c3f0
--- /dev/null
+++ b/src/Febe.Web/wwwroot/icone/grip-vertical.svg
@@ -0,0 +1,8 @@
+
diff --git a/src/Febe.Web/wwwroot/js/core/return-path.js b/src/Febe.Web/wwwroot/js/core/return-path.js
index 775a9c6..3253ccb 100644
--- a/src/Febe.Web/wwwroot/js/core/return-path.js
+++ b/src/Febe.Web/wwwroot/js/core/return-path.js
@@ -6,9 +6,9 @@
const SAFE = /^\/(?![\/\\])[^\\\s\u0000-\u001f\u007f-\u009f]*$/;
-export const DEFAULT_PAGE = '/libreria';
+export const DEFAULT_PAGE = '/dashboard';
-/** The absolute address to open after the login, on only; the library when is missing or unsafe. */
+/** The absolute address to open after the login, on only; the Dashboard when is missing or unsafe. */
export function returnAddress(value, origin) {
const fallback = new URL(DEFAULT_PAGE, origin).href;
if (typeof value !== 'string' || value.length > 2048 || !SAFE.test(value)) {
diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js
index 354f002..4396e82 100644
--- a/src/Febe.Web/wwwroot/js/core/shell.js
+++ b/src/Febe.Web/wwwroot/js/core/shell.js
@@ -1,5 +1,5 @@
-// The frame of every page (spec §10.2): fixed 228 px sidebar with brand, Libreria, Account, Attività, Importa,
-// separator, Impostazioni, and the status box always visible at the bottom; on the right the page: title row,
+// The frame of every page (spec §10.2): fixed 228 px sidebar with brand, Dashboard (the start page, tappa D1), Libreria,
+// Account, Importa, separator, Impostazioni, and the status box always visible at the bottom; on the right the page: title row,
// optional tools row, scrolling content, fixed bar for the actions that save. The red strip (mockup 11) appears under
// the title of every page while the engine is stopped and needs Alberto. Also the router of the addresses.
@@ -12,9 +12,9 @@ import { avatar, showError, toast, closeMenu } from './ui.js';
import { routes } from '../routes.js';
const NAV = [
+ { key: 'dashboard', href: '/dashboard', icon: 'activity' },
{ key: 'libreria', href: '/libreria', icon: 'layout-grid' },
{ key: 'account', href: '/account', icon: 'users' },
- { key: 'attivita', href: '/attivita', icon: 'activity' },
{ key: 'importa', href: '/importa', icon: 'folder-input' },
'stacco',
{ key: 'impostazioni', href: '/impostazioni', icon: 'settings' },
@@ -37,13 +37,13 @@ export function buildShell(root) {
navLinks[item.key] = a;
return a;
});
- statusBox = h('a.stato', { href: withCarried('/attivita'), 'aria-label': t('stato.riquadro') });
+ statusBox = h('a.stato', { href: withCarried('/dashboard'), 'aria-label': t('stato.riquadro') });
main = h('main.pagina', { id: 'contenuto', tabindex: '-1' });
fill(root,
h('a.salta', { href: '#contenuto' }, t('app.salta')),
h('div.app',
h('aside.barra',
- h('a.marchio', { href: withCarried('/libreria') }, brand(), h('b', t('app.nome'))),
+ h('a.marchio', { href: withCarried('/dashboard') }, brand(), h('b', t('app.nome'))),
h('nav.nav', { 'aria-label': t('nav.principale') }, links),
h('div.molla'),
statusBox),
@@ -82,7 +82,7 @@ function renderStatus(state) {
h('div.conto', h('span', t('stato.profiliOggi')), h('span', `${meter.usedText} ${meter.limitText}`)),
who);
statusBox.title = s.details && s.details.length ? s.details.join(' ') : s.headline;
- const attention = navLinks.attivita;
+ const attention = navLinks.dashboard;
if (attention) {
const dot = attention.querySelector('.punto');
if (s.banner && !dot) attention.append(h('span.punto', { role: 'img', 'aria-label': t('nav.fermo') }));
diff --git a/src/Febe.Web/wwwroot/js/pages/activity.js b/src/Febe.Web/wwwroot/js/pages/activity.js
deleted file mode 100644
index c7b351a..0000000
--- a/src/Febe.Web/wwwroot/js/pages/activity.js
+++ /dev/null
@@ -1,395 +0,0 @@
-// Attività (mockups 06 and 11, spec §7.9): what the engine is doing now with a still frame of the browser every few
-// seconds, the strip of the day, «Limiti di oggi» with the four main budgets and «Tutti i tetti», the queue with
-// «verso le» times, «Appena fatto» with the outcomes, the stops of the last days and the alerts (spec §13.3: also the
-// ones that are not stops, like a backfill completed or a disk almost full). It updates by itself from the event
-// stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
-
-import { api, download, withCarried } from '../core/api.js';
-import { h, icon, fill } from '../core/dom.js';
-import { dotOf, refreshEngine } from '../core/engine.js';
-import { openBrowser } from '../core/shell.js';
-import { t, at, capitalize } from '../core/text.js';
-import { dialog, label, showError, toast } from '../core/ui.js';
-import { dayStrip } from './day-strip.js';
-
-const STOPPED = ['StoppedForVerification', 'Disconnected'];
-
-export default {
- async mount(page) {
- page.title(t('attivita.titolo'));
- const notice = h('div');
- const now = h('section.ora-pannello.pannello');
- const preview = previewBox(page);
- const today = h('section.blocco');
- const budgets = h('section.blocco');
- const lists = h('div.due-colonne');
- const suspended = h('div');
- const incidents = h('section.blocco');
- const alerts = h('section.blocco', { hidden: true });
- // On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11).
- page.root.dataset.pagina = 'attivita';
- fill(page.body, h('div.attivita', now, suspended, today, budgets, lists, notice, incidents, alerts));
-
- let latest = null;
- page.onEngine((state) => {
- latest = state;
- drawActions(page, state);
- drawNow(now, preview, state);
- drawToday(today, state);
- drawBudgets(budgets, state);
- drawLists(lists, state);
- drawSuspended(suspended, state);
- preview.update(state);
- });
-
- async function loadSide() {
- try {
- const [counts, history, recent] = await Promise.all([
- api('/api/duplicates/count', { signal: page.signal }),
- api('/api/engine/incidents', { signal: page.signal }),
- api('/api/alerts', { signal: page.signal }),
- ]);
- drawNotice(notice, counts);
- drawIncidents(incidents, history);
- drawAlerts(alerts, recent);
- } catch (error) {
- if (error.name !== 'AbortError') showError(error);
- }
- }
- await loadSide();
- if (page.signal.aborted) return;
- page.onLibrary(() => loadSide());
- const timer = setInterval(() => {
- if (latest && document.visibilityState === 'visible') loadSide();
- }, 60000);
- page.onLeave(() => clearInterval(timer));
- },
-};
-
-// ------------------------------------------------------------------------------------------------- title actions
-
-function drawActions(page, state) {
- const s = state.snapshot;
- const resume = async () => {
- try {
- const result = await api('/api/engine/resume', { method: 'POST' });
- toast(result.message, result.resumed ? '' : 'errore');
- refreshEngine();
- } catch (error) {
- showError(error);
- }
- };
- const pause = async () => {
- try {
- const result = await api('/api/engine/pause', { method: 'POST' });
- toast(result.message);
- refreshEngine();
- } catch (error) {
- showError(error);
- }
- };
- const needsResume = s.mode === 'Paused' || (s.banner && s.banner.needsResume);
- const first = needsResume
- ? h('button.btn', {
- type: 'button', onclick: resume, disabled: s.mode !== 'Paused' && !state.canResume,
- title: s.mode !== 'Paused' && !state.canResume ? t('arresto.riprendiSpento') : null, 'aria-label': t('attivita.riprendi'),
- }, icon('rotate-cw'), h('span.testo-btn', t('attivita.riprendi')))
- : h('button.btn', {
- type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'),
- }, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
- page.actions(
- first,
- h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
- diagnosticsButton(),
- );
-}
-
-// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click
-// may be gone by the end: the flag, not the button, says whether an export is running.
-let exporting = false;
-
-/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */
-function diagnosticsButton() {
- const button = h('button.btn', {
- type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting,
- }, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica')));
- button.onclick = async () => {
- if (exporting) return;
- exporting = true;
- button.disabled = true;
- try {
- await download('/api/engine/diagnostica', null, 'febe-diagnostica.json');
- toast(t('attivita.diagnosticaEsportata'));
- } catch (error) {
- showError(error);
- } finally {
- exporting = false;
- // The button on the page now, which may not be this one.
- for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false;
- }
- };
- button.dataset.diagnostica = '';
- return button;
-}
-
-// ------------------------------------------------------------------------------------------------- now
-
-function drawNow(box, preview, state) {
- const s = state.snapshot;
- const dot = dotOf(s.mode);
- const [first, ...rest] = s.details || [];
- fill(box,
- h('div.ora-testo',
- h('div.riga', h(`span.spia${dot ? '.' + dot : ''}`, { 'aria-hidden': 'true' }), h('b', s.headline)),
- first ? h('p.cosa', first) : null,
- rest.length ? h('p.dettaglio', rest.join(' ')) : null,
- s.reductionNote ? h('p.dettaglio', s.reductionNote) : null),
- preview.element);
-}
-
-/** The still frame of the browser: one image every few seconds, never a video (mockup 06). */
-function previewBox(page) {
- const address = h('span.indirizzo.dati');
- const image = h('img', { alt: t('attivita.anteprima'), hidden: true });
- const placeholder = h('div.segnaposto-anteprima');
- const element = h('figure.anteprima', h('figcaption', icon('lock', 'xs'), address), h('div.quadro', image, placeholder));
- let mode = null;
- let frameUrl = null;
- let timer = 0;
- let stopped = false;
-
- function placeholderFor(m) {
- if (m === 'StoppedForVerification') return ['shield-alert', t('attivita.anteprimaVerifica'), 'https://www.instagram.com/challenge/'];
- if (m === 'Disconnected' || m === 'NotConnected') return ['user', t('attivita.anteprimaAccesso'), null];
- if (m === 'Off') return ['square', t('attivita.anteprimaSpenta'), null];
- if (m === 'InSession' || m === 'UserDriving') return ['hourglass', t('attivita.anteprimaAttesa'), null];
- return ['moon', t('attivita.anteprimaVuota'), 'about:blank'];
- }
-
- async function load() {
- clearTimeout(timer);
- if (stopped) return;
- try {
- const result = await api('/api/browser/preview', { signal: page.signal });
- if (result.hasFrame && result.frame) {
- if (result.frame !== frameUrl) {
- frameUrl = result.frame;
- image.src = withCarried(result.frame);
- }
- image.hidden = false;
- placeholder.hidden = true;
- address.textContent = shortUrl(result.url);
- } else {
- showPlaceholder();
- }
- } catch (error) {
- if (error.name === 'AbortError') return;
- showPlaceholder();
- }
- const busy = ['InSession', 'UserDriving', ...STOPPED].includes(mode);
- timer = setTimeout(load, busy ? 5000 : 30000);
- }
-
- function showPlaceholder() {
- frameUrl = null;
- image.hidden = true;
- image.removeAttribute('src');
- const [name, text, url] = placeholderFor(mode);
- fill(placeholder, icon(name, 'l'), h('span', text));
- placeholder.hidden = false;
- address.textContent = url ? shortUrl(url) : '';
- }
-
- page.onLeave(() => {
- stopped = true;
- clearTimeout(timer);
- });
-
- return {
- element,
- update(state) {
- const changed = state.snapshot.mode !== mode;
- mode = state.snapshot.mode;
- if (changed) load();
- },
- };
-}
-
-function shortUrl(url) {
- if (!url) return '';
- return url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '');
-}
-
-// ------------------------------------------------------------------------------------------------- strip
-
-function drawToday(box, state) {
- const s = state.snapshot;
- const { strip, hours, legend } = dayStrip(s.today, { stopOpen: STOPPED.includes(s.mode) });
- fill(box,
- h('div.testa-blocco', h('h2', t('attivita.oggi')), h('span.muto', s.today.summary), legend),
- strip, hours);
-}
-
-// ------------------------------------------------------------------------------------------------- budgets
-
-function drawBudgets(box, state) {
- const s = state.snapshot;
- const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
- const profile = frozen ? t('attivita.congelati', { profilo: s.profileLine }) : s.profileLine;
- fill(box,
- h('div.testa-blocco',
- h('h2', t('attivita.limiti')),
- h('span.muto', profile),
- s.reductionNote ? label(s.reductionNote, 'ambra') : null,
- h('button.btn.collegamento.destra', { type: 'button', onclick: () => allBudgets(state) }, t('attivita.tuttiTetti'))),
- h('div.tetti.pannello', s.mainBudgets.map((b) => budgetCard(b, frozen))));
-}
-
-function budgetCard(b, frozen) {
- const meterClass = frozen && b.kind !== 'DataDownload' ? '.grigio' : b.amber ? '.ambra' : '';
- return h('div.tetto',
- h('span.nome', b.label),
- h('div.valore', h('b.dati', b.usedText), h('span', b.limitText)),
- h(`div.misura${meterClass}`, {
- role: 'meter', 'aria-label': b.label, 'aria-valuemin': '0', 'aria-valuemax': String(b.limitToday), 'aria-valuenow': String(b.usedToday),
- }, h('i', { style: { width: `${Math.max(0, Math.min(1, b.ratio)) * 100}%` } })),
- h('span.nota', b.amber ? h('span', icon('triangle-alert', 'xs'), ' ', b.note) : b.note));
-}
-
-function allBudgets(state) {
- const s = state.snapshot;
- const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
- const cell = (used, limit, text, ratio, amber) => h('td',
- h('div.cella-tetto',
- h('span.dati', text),
- limit != null ? h(`div.misura.fine${frozen ? '.grigio' : amber ? '.ambra' : ''}`, h('i', { style: { width: `${Math.max(0, Math.min(1, ratio)) * 100}%` } })) : null));
- dialog({
- title: t('attivita.tetti.titolo'),
- className: 'tutti-tetti',
- build: (close) => ({
- body: h('div.contenuto',
- h('p.aiuto', t('attivita.tetti.aiuto')),
- h('table.tab',
- h('thead', h('tr', h('th', t('attivita.tetti.categoria')), h('th', t('attivita.tetti.ora')), h('th', t('attivita.tetti.giorno')))),
- h('tbody', s.allBudgets.map((b) => h('tr',
- h('td', h('b', b.label), b.amber ? h('div', label(b.note, 'ambra')) : b.note.startsWith(t('attivita.tetti.ora')) ? null : h('div.muto.piccolo', b.note)),
- b.limitPerHour == null
- ? h('td.muto', '—')
- : cell(b.usedLastHour, b.limitPerHour, t('attivita.tetti.di', { usati: b.usedLastHour, limite: b.limitPerHour }), b.limitPerHour ? b.usedLastHour / b.limitPerHour : 0, b.limitPerHour && b.usedLastHour / b.limitPerHour >= 0.8),
- cell(b.usedToday, b.limitToday, `${b.usedText} ${b.limitText}`, b.ratio, b.ratio >= 0.8)))))),
- footer: h('footer',
- h('a.btn.nudo', { href: withCarried('/impostazioni/limiti'), onclick: () => close() }, icon('sliders-horizontal'), t('attivita.tetti.cambia')),
- h('div.destra', h('button.btn.primo', { type: 'button', onclick: () => close() }, t('comune.chiudi')))),
- }),
- });
-}
-
-// ------------------------------------------------------------------------------------------------- queue and latest actions
-
-function badgeKind(text) {
- const v = String(text || '').toLowerCase();
- if (v.includes('in corso')) return 'accento';
- if (v.includes('scaricat') || v.includes('nuov')) return 'verde';
- if (v.includes('tutto fermo') || v.includes('verifica') || v.includes('non riuscit')) return 'rosso';
- if (v.includes('fermo') || v.includes('rallent') || v.includes('tetto')) return 'ambra';
- return '';
-}
-
-function drawLists(box, state) {
- const s = state.snapshot;
- const queue = s.queue.length
- ? h('ul.elenco-attivita', s.queue.map((q) => h('li',
- h('span.quando.dati', q.when),
- h('div.chi-cosa', h('b', q.title), h('span', q.detail)),
- q.suspended ? label(t('account.sospeso')) : q.isManual ? label(t('attivita.chiesto'), 'accento') : null)))
- : h('p.vuoto-elenco', t('attivita.codaVuota'));
- const recent = s.recentActions.length
- ? h('ul.elenco-attivita', s.recentActions.map((r) => h('li',
- h('span.quando.dati', r.time),
- h('div.chi-cosa', h('b', r.title), h('span', r.detail)),
- r.badge ? label(r.badge, badgeKind(r.badge)) : null)))
- : h('p.vuoto-elenco', t('attivita.fattoVuoto'));
- fill(box,
- h('section', h('h2', t('attivita.coda')), h('div.pannello', queue)),
- h('section', h('h2', t('attivita.fatto')), h('div.pannello', recent)));
-}
-
-// ------------------------------------------------------------------------------------------------- side information
-
-function drawNotice(box, counts) {
- if (!counts || !counts.download) {
- box.replaceChildren();
- return;
- }
- fill(box, h('div.avviso.ambra.avviso-azione', icon('layers', 's'),
- h('span', t('attivita.doppioni', { n: counts.download })),
- h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi'))));
-}
-
-/** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */
-function drawSuspended(box, state) {
- const items = state.snapshot.suspendedRecipes || [];
- if (!items.length) {
- box.replaceChildren();
- return;
- }
- fill(box, items.map((r) => h('div.avviso.rosso.avviso-azione', { style: { marginBottom: '10px' } },
- icon('octagon-alert', 's'),
- h('span', t('attivita.sospesa', { nome: r.name })),
- h('button.btn.piccolo', {
- type: 'button',
- onclick: async () => {
- try {
- const result = await api(`/api/engine/recipes/${encodeURIComponent(r.recipe)}/resume`, { method: 'POST' });
- toast(result.message, result.resumed ? '' : 'errore');
- refreshEngine();
- } catch (error) {
- showError(error);
- }
- },
- }, t('attivita.riattiva')))));
-}
-
-const ALERT_LOOK = {
- error: { icon: 'octagon-alert', label: 'rosso' },
- warning: { icon: 'triangle-alert', label: 'ambra' },
- success: { icon: 'circle-check', label: 'verde' },
- info: { icon: 'bell', label: '' },
-};
-
-/** «Avvisi»: every alert of the last days, the same ones Telegram and Windows get. Hidden while there are none. */
-function drawAlerts(box, recent) {
- const items = (recent && recent.items) || [];
- box.hidden = !items.length;
- if (!items.length) {
- box.replaceChildren();
- return;
- }
- fill(box,
- h('div.testa-blocco', h('h2', t('attivita.avvisi')), h('span.muto', t('attivita.avvisiAiuto', { giorni: recent.days }))),
- h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => {
- const look = ALERT_LOOK[i.level] || ALERT_LOOK.info;
- return h('li',
- h('span.quando.dati', capitalize(at(i.at))),
- h('div.chi-cosa', h('b', i.title), h('span', i.message)),
- label(t(`attivita.livelliAvviso.${i.level}`), look.label, look.icon));
- }))));
-}
-
-function drawIncidents(box, history) {
- const items = history.items || [];
- fill(box,
- h('div.testa-blocco', h('h2', t('attivita.arresti')), h('span.muto', t('attivita.arrestiAiuto'))),
- history.advice ? h('div.avviso.ambra', { style: { marginBottom: '10px' } }, icon('triangle-alert', 's'), h('span', history.advice)) : null,
- items.length
- ? h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => h('li',
- h('span.quando.dati', capitalize(at(i.at))),
- h('div.chi-cosa',
- h('b', i.title, ' ', h('span.codice.dati', i.signal)),
- h('span', [i.note, i.url ? i.url.replace(/^https?:\/\/(www\.)?/, '') : null].filter(Boolean).join(' · '))),
- i.open
- ? label(t('attivita.aperto'), i.level === 'throttle' ? 'ambra' : 'rosso')
- : h('span.muto.piccolo', i.resolvedAt ? t('attivita.risolto', { quando: at(i.resolvedAt) }) : i.stoppedUntil ? t('attivita.fermoFino', { quando: at(i.stoppedUntil) }) : '')))))
- : h('p.vuoto-elenco.pannello', t('attivita.arrestiVuoti')));
-}
-
diff --git a/src/Febe.Web/wwwroot/js/pages/browser.js b/src/Febe.Web/wwwroot/js/pages/browser.js
index ad0b7d8..581aea0 100644
--- a/src/Febe.Web/wwwroot/js/pages/browser.js
+++ b/src/Febe.Web/wwwroot/js/pages/browser.js
@@ -37,7 +37,7 @@ export default {
// «Ho finito» gives the browser back on the server whatever the answer.
lease.settled();
toast(result.message, result.connected ? '' : 'errore');
- if (result.connected) navigate('/attivita');
+ if (result.connected) navigate('/dashboard');
else fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message)));
};
page.saveBar(h('div', { style: { display: 'contents' } },
diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard.js b/src/Febe.Web/wwwroot/js/pages/dashboard.js
new file mode 100644
index 0000000..b3cea1b
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/dashboard.js
@@ -0,0 +1,672 @@
+// Dashboard (spec §7.9, §10.2, tappa D1; before it was Attività, mockups 06 and 11): the start page, where Alberto stays
+// while the engine works. Compact, to fit the top of a 1440 × 900 window without scrolling: at the top the preview of
+// the browser, always visible and refreshed at every new frame (at most one a second), with beside it what the engine
+// is doing now and the four main budgets in one row («Tutti i tetti» for the others); then the strip of the day, lower;
+// then in two columns the history with the thumbnails of what arrived (loaded only when the line is in view, at most
+// eight with «+N»; a click opens a light enlarged preview) and the queue with «verso le» times, cut to the first rows
+// with «Mostra tutta». Below: the stops of the last days and the alerts (spec §13.3). It updates by itself from the
+// event stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
+
+import { api, download, withCarried } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { dotOf, refreshEngine } from '../core/engine.js';
+import { openBrowser } from '../core/shell.js';
+import { t, at, capitalize, dayName, duration } from '../core/text.js';
+import { dialog, label, showError, toast } from '../core/ui.js';
+import { dayStrip } from './day-strip.js';
+import { openViewer } from './viewer.js';
+
+const STOPPED = ['StoppedForVerification', 'Disconnected'];
+// Rows of the queue shown before «Mostra tutta»; thumbnails of a line of the history before «+N» (spec §7.9).
+const QUEUE_ROWS = 5;
+const THUMBS = 8;
+
+export default {
+ async mount(page) {
+ page.title(t('attivita.titolo'));
+ const notice = h('div');
+ const now = h('div.ora-testo');
+ const preview = previewBox(page);
+ const today = h('section.blocco.oggi-basso');
+ const budgets = h('section.blocco-tetti');
+ const history = historyBox(page);
+ const queue = queueBox();
+ const suspended = h('div');
+ const incidents = h('section.blocco');
+ const alerts = h('section.blocco', { hidden: true });
+ // On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11).
+ page.root.dataset.pagina = 'dashboard';
+ fill(page.body, h('div.attivita.dashboard',
+ h('section.cruscotto.pannello', preview.element, h('div.cruscotto-lato', now, budgets)),
+ suspended, today,
+ h('div.due-colonne.storia-coda', history.element, queue.element),
+ notice, incidents, alerts));
+
+ let latest = null;
+ page.onEngine((state) => {
+ latest = state;
+ drawActions(page, state);
+ drawNow(now, state);
+ drawToday(today, state);
+ drawBudgets(budgets, state);
+ history.draw(state);
+ queue.draw(state);
+ drawSuspended(suspended, state);
+ preview.update(state);
+ });
+
+ async function loadSide() {
+ try {
+ const [counts, history, recent] = await Promise.all([
+ api('/api/duplicates/count', { signal: page.signal }),
+ api('/api/engine/incidents', { signal: page.signal }),
+ api('/api/alerts', { signal: page.signal }),
+ ]);
+ drawNotice(notice, counts);
+ drawIncidents(incidents, history);
+ drawAlerts(alerts, recent);
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ }
+ }
+ await loadSide();
+ if (page.signal.aborted) return;
+ page.onLibrary(() => loadSide());
+ const timer = setInterval(() => {
+ if (latest && document.visibilityState === 'visible') loadSide();
+ }, 60000);
+ page.onLeave(() => clearInterval(timer));
+ },
+};
+
+// ------------------------------------------------------------------------------------------------- title actions
+
+function drawActions(page, state) {
+ const s = state.snapshot;
+ const resume = async () => {
+ try {
+ const result = await api('/api/engine/resume', { method: 'POST' });
+ toast(result.message, result.resumed ? '' : 'errore');
+ refreshEngine();
+ } catch (error) {
+ showError(error);
+ }
+ };
+ const pause = async () => {
+ try {
+ const result = await api('/api/engine/pause', { method: 'POST' });
+ toast(result.message);
+ refreshEngine();
+ } catch (error) {
+ showError(error);
+ }
+ };
+ const needsResume = s.mode === 'Paused' || (s.banner && s.banner.needsResume);
+ const first = needsResume
+ ? h('button.btn', {
+ type: 'button', onclick: resume, disabled: s.mode !== 'Paused' && !state.canResume,
+ title: s.mode !== 'Paused' && !state.canResume ? t('arresto.riprendiSpento') : null, 'aria-label': t('attivita.riprendi'),
+ }, icon('rotate-cw'), h('span.testo-btn', t('attivita.riprendi')))
+ : h('button.btn', {
+ type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'),
+ }, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
+ page.actions(
+ first,
+ h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
+ diagnosticsButton(),
+ );
+}
+
+// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click
+// may be gone by the end: the flag, not the button, says whether an export is running.
+let exporting = false;
+
+/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */
+function diagnosticsButton() {
+ const button = h('button.btn', {
+ type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting,
+ }, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica')));
+ button.onclick = async () => {
+ if (exporting) return;
+ exporting = true;
+ button.disabled = true;
+ try {
+ await download('/api/engine/diagnostica', null, 'febe-diagnostica.json');
+ toast(t('attivita.diagnosticaEsportata'));
+ } catch (error) {
+ showError(error);
+ } finally {
+ exporting = false;
+ // The button on the page now, which may not be this one.
+ for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false;
+ }
+ };
+ button.dataset.diagnostica = '';
+ return button;
+}
+
+// ------------------------------------------------------------------------------------------------- now
+
+function drawNow(box, state) {
+ const s = state.snapshot;
+ const dot = dotOf(s.mode);
+ const [first, ...rest] = s.details || [];
+ fill(box,
+ h('div.riga', h(`span.spia${dot ? '.' + dot : ''}`, { 'aria-hidden': 'true' }), h('b', s.headline)),
+ first ? h('p.cosa', first) : null,
+ rest.length ? h('p.dettaglio', rest.join(' ')) : null,
+ s.reductionNote ? h('p.dettaglio', s.reductionNote) : null);
+}
+
+/**
+ * The preview of the browser, always visible (spec §7.9): the page the browser of Febe is looking at, frames and never
+ * a video. While the engine works it asks every second and swaps the picture only when the frame is new (the server
+ * takes at most one a second, however many pages ask); otherwise every 30 seconds. Out of a session it says why it
+ * is still. A hidden tab asks nothing.
+ */
+function previewBox(page) {
+ const address = h('span.indirizzo.dati');
+ const image = h('img', { alt: t('attivita.anteprima'), hidden: true });
+ const placeholder = h('div.segnaposto-anteprima');
+ const element = h('figure.anteprima', h('figcaption', icon('lock', 'xs'), address), h('div.quadro', image, placeholder));
+ let mode = null;
+ let frameUrl = null;
+ let timer = 0;
+ let stopped = false;
+
+ function placeholderFor(m) {
+ if (m === 'StoppedForVerification') return ['shield-alert', t('attivita.anteprimaVerifica'), 'https://www.instagram.com/challenge/'];
+ if (m === 'Disconnected' || m === 'NotConnected') return ['user', t('attivita.anteprimaAccesso'), null];
+ if (m === 'Off') return ['square', t('attivita.anteprimaSpenta'), null];
+ if (m === 'InSession' || m === 'UserDriving') return ['hourglass', t('attivita.anteprimaAttesa'), null];
+ return ['moon', t('attivita.anteprimaVuota'), 'about:blank'];
+ }
+
+ async function load() {
+ clearTimeout(timer);
+ if (stopped) return;
+ try {
+ const result = await api('/api/browser/preview', { signal: page.signal });
+ if (result.hasFrame && result.frame) {
+ if (result.frame !== frameUrl) {
+ frameUrl = result.frame;
+ image.src = withCarried(result.frame);
+ }
+ image.hidden = false;
+ placeholder.hidden = true;
+ address.textContent = shortUrl(result.url);
+ } else {
+ showPlaceholder();
+ }
+ } catch (error) {
+ if (error.name === 'AbortError') return;
+ showPlaceholder();
+ }
+ const busy = ['InSession', 'UserDriving', ...STOPPED].includes(mode);
+ timer = setTimeout(() => {
+ if (document.visibilityState === 'visible') load();
+ else waiting = true;
+ }, busy ? 1000 : 30000);
+ }
+
+ // Back to a visible tab: at once, instead of after the next interval.
+ let waiting = false;
+ const onVisible = () => {
+ if (document.visibilityState === 'visible' && waiting) {
+ waiting = false;
+ load();
+ }
+ };
+ document.addEventListener('visibilitychange', onVisible);
+
+ function showPlaceholder() {
+ frameUrl = null;
+ image.hidden = true;
+ image.removeAttribute('src');
+ const [name, text, url] = placeholderFor(mode);
+ fill(placeholder, icon(name, 'l'), h('span', text));
+ placeholder.hidden = false;
+ address.textContent = url ? shortUrl(url) : '';
+ }
+
+ page.onLeave(() => {
+ stopped = true;
+ clearTimeout(timer);
+ document.removeEventListener('visibilitychange', onVisible);
+ });
+
+ return {
+ element,
+ update(state) {
+ const changed = state.snapshot.mode !== mode;
+ mode = state.snapshot.mode;
+ if (changed) load();
+ },
+ };
+}
+
+function shortUrl(url) {
+ if (!url) return '';
+ return url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '');
+}
+
+// ------------------------------------------------------------------------------------------------- strip
+
+function drawToday(box, state) {
+ const s = state.snapshot;
+ const { strip, hours, legend } = dayStrip(s.today, { stopOpen: STOPPED.includes(s.mode) });
+ fill(box,
+ h('div.testa-blocco', h('h2', t('attivita.oggi')), h('span.muto', s.today.summary), legend),
+ strip, hours);
+}
+
+// ------------------------------------------------------------------------------------------------- budgets
+
+function drawBudgets(box, state) {
+ const s = state.snapshot;
+ const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
+ const profile = frozen ? t('attivita.congelati', { profilo: s.profileLine }) : s.profileLine;
+ fill(box,
+ h('div.testa-blocco',
+ h('h2', t('attivita.limiti')),
+ h('span.muto', profile),
+ h('button.btn.collegamento.destra', { type: 'button', onclick: () => allBudgets(state) }, t('attivita.tuttiTetti'))),
+ h('div.tetti', s.mainBudgets.map((b) => budgetCard(b, frozen))));
+}
+
+function budgetCard(b, frozen) {
+ const meterClass = frozen && b.kind !== 'DataDownload' ? '.grigio' : b.amber ? '.ambra' : '';
+ return h('div.tetto',
+ h('span.nome', b.label),
+ h('div.valore', h('b.dati', b.usedText), h('span', b.limitText)),
+ h(`div.misura${meterClass}`, {
+ role: 'meter', 'aria-label': b.label, 'aria-valuemin': '0', 'aria-valuemax': String(b.limitToday), 'aria-valuenow': String(b.usedToday),
+ }, h('i', { style: { width: `${Math.max(0, Math.min(1, b.ratio)) * 100}%` } })),
+ h('span.nota', b.amber ? h('span', icon('triangle-alert', 'xs'), ' ', b.note) : b.note));
+}
+
+function allBudgets(state) {
+ const s = state.snapshot;
+ const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
+ const cell = (used, limit, text, ratio, amber) => h('td',
+ h('div.cella-tetto',
+ h('span.dati', text),
+ limit != null ? h(`div.misura.fine${frozen ? '.grigio' : amber ? '.ambra' : ''}`, h('i', { style: { width: `${Math.max(0, Math.min(1, ratio)) * 100}%` } })) : null));
+ dialog({
+ title: t('attivita.tetti.titolo'),
+ className: 'tutti-tetti',
+ build: (close) => ({
+ body: h('div.contenuto',
+ h('p.aiuto', t('attivita.tetti.aiuto')),
+ h('table.tab',
+ h('thead', h('tr', h('th', t('attivita.tetti.categoria')), h('th', t('attivita.tetti.ora')), h('th', t('attivita.tetti.giorno')))),
+ h('tbody', s.allBudgets.map((b) => h('tr',
+ h('td', h('b', b.label), b.amber ? h('div', label(b.note, 'ambra')) : b.note.startsWith(t('attivita.tetti.ora')) ? null : h('div.muto.piccolo', b.note)),
+ b.limitPerHour == null
+ ? h('td.muto', '—')
+ : cell(b.usedLastHour, b.limitPerHour, t('attivita.tetti.di', { usati: b.usedLastHour, limite: b.limitPerHour }), b.limitPerHour ? b.usedLastHour / b.limitPerHour : 0, b.limitPerHour && b.usedLastHour / b.limitPerHour >= 0.8),
+ cell(b.usedToday, b.limitToday, `${b.usedText} ${b.limitText}`, b.ratio, b.ratio >= 0.8)))))),
+ footer: h('footer',
+ h('a.btn.nudo', { href: withCarried('/impostazioni/limiti'), onclick: () => close() }, icon('sliders-horizontal'), t('attivita.tetti.cambia')),
+ h('div.destra', h('button.btn.primo', { type: 'button', onclick: () => close() }, t('comune.chiudi')))),
+ }),
+ });
+}
+
+// ------------------------------------------------------------------------------------------------- queue and latest actions
+
+function badgeKind(text) {
+ const v = String(text || '').toLowerCase();
+ if (v.includes('in corso')) return 'accento';
+ if (v.includes('scaricat') || v.includes('nuov')) return 'verde';
+ if (v.includes('tutto fermo') || v.includes('verifica') || v.includes('non riuscit')) return 'rosso';
+ if (v.includes('fermo') || v.includes('rallent') || v.includes('tetto')) return 'ambra';
+ return '';
+}
+
+/** The queue with «verso le» times, cut to the first rows; «Mostra tutta» opens it whole until the page is left. */
+function queueBox() {
+ const element = h('section.coda');
+ let whole = false;
+ let last = null;
+ function draw(state) {
+ last = state;
+ const items = state.snapshot.queue;
+ const shown = whole ? items : items.slice(0, QUEUE_ROWS);
+ const list = items.length
+ ? h('ul.elenco-attivita.stretto', shown.map((q) => h('li',
+ h('span.quando.dati', q.when),
+ h('div.chi-cosa', h('b', q.title), h('span', q.detail)),
+ q.suspended ? label(t('account.sospeso')) : q.isManual ? label(t('attivita.chiesto'), 'accento') : null)))
+ : h('p.vuoto-elenco', t('attivita.codaVuota'));
+ const more = items.length > QUEUE_ROWS
+ ? h('button.btn.collegamento.piede-elenco', {
+ type: 'button',
+ 'aria-expanded': String(whole),
+ onclick: () => {
+ whole = !whole;
+ draw(last);
+ },
+ }, whole ? t('attivita.mostraMeno') : t('attivita.mostraTutta', { n: items.length }))
+ : null;
+ fill(element, h('h2', t('attivita.coda')), h('div.pannello', list, more));
+ }
+ return { element, draw };
+}
+
+/**
+ * The history of the activity (spec §7.9): the last recipe runs with their outcome; a line that saved something shows
+ * the thumbnails of what arrived, asked to the server only when the line comes into view and kept while the page is
+ * open, so that the engine updates never ask again for the same line.
+ */
+function historyBox(page) {
+ const element = h('section.storia');
+ const arrived = new Map();
+ const watcher = 'IntersectionObserver' in window
+ ? new IntersectionObserver((entries) => {
+ for (const e of entries) {
+ if (!e.isIntersecting) continue;
+ watcher.unobserve(e.target);
+ loadThumbs(e.target);
+ }
+ }, { rootMargin: '200px 0px' })
+ : null;
+ page.onLeave(() => watcher && watcher.disconnect());
+
+ function keyOf(r) {
+ return `${r.accountId}|${r.from}|${r.at}`;
+ }
+
+ async function loadThumbs(holder) {
+ const key = holder.dataset.chiave;
+ const known = arrived.get(key);
+ if (known && known.result) {
+ paint(holder, known);
+ return;
+ }
+ if (known && known.loading) return;
+ const item = { loading: true, result: null, line: holder.line };
+ arrived.set(key, item);
+ try {
+ const query = new URLSearchParams({ account: String(holder.line.accountId), from: holder.line.from, to: holder.line.at, limit: String(THUMBS) });
+ item.result = await api(`/api/activity/arrived?${query}`, { signal: page.signal });
+ } catch (error) {
+ if (error.name === 'AbortError') return;
+ item.result = { tiles: [], total: 0 };
+ } finally {
+ item.loading = false;
+ }
+ // The line may have been drawn again meanwhile: paint the holder that is on the page now.
+ const shown = element.querySelector(`[data-chiave="${CSS.escape(key)}"]`);
+ if (shown) paint(shown, item);
+ }
+
+ function paint(holder, item) {
+ const { tiles, total } = item.result;
+ // The holder keeps the room of a row of thumbnails while it waits (an element with no size is never in view).
+ if (!tiles.length) {
+ holder.replaceChildren();
+ holder.hidden = true;
+ return;
+ }
+ const rest = Math.max(0, total - tiles.length);
+ fill(holder,
+ tiles.map((tile, i) => thumb(tile, () => openPreview(page, item.line, tiles, total, i))),
+ rest > 0 ? h('span.miniature-altre.dati', { title: t('attivita.altreArrivate', { n: rest }) }, `+${rest}`) : null);
+ }
+
+ function draw(state) {
+ const items = state.snapshot.recentActions;
+ if (!items.length) {
+ fill(element, h('h2', t('attivita.fatto')), h('div.pannello', h('p.vuoto-elenco', t('attivita.fattoVuoto'))));
+ return;
+ }
+ const list = h('ul.elenco-attivita.storia-righe', items.map((r) => {
+ let holder = null;
+ if (r.accountId && r.from && r.newEntries > 0) {
+ holder = h('div.miniature', { dataset: { chiave: keyOf(r) }, 'aria-label': t('attivita.arrivate', { n: r.newEntries }), role: 'group' });
+ holder.line = r;
+ const known = arrived.get(keyOf(r));
+ if (known && known.result) paint(holder, known);
+ else if (watcher) watcher.observe(holder);
+ else loadThumbs(holder);
+ }
+ return h('li',
+ h('span.quando.dati', r.time),
+ h('div.chi-cosa', h('b', r.title), r.detail ? h('span', r.detail) : null, holder),
+ r.badge ? label(r.badge, badgeKind(r.badge)) : null);
+ }));
+ fill(element, h('h2', t('attivita.fatto')), h('div.pannello', list));
+ // Lines no longer shown are forgotten, so that a long day does not keep every answer.
+ const keys = new Set(items.filter((r) => r.accountId && r.from).map(keyOf));
+ for (const key of arrived.keys()) if (!keys.has(key)) arrived.delete(key);
+ }
+
+ return { element, draw };
+}
+
+/** A small tile of the history: the thumbnail of §8.4 with the marks of the mosaic (video length, ring of stories). */
+function thumb(tile, onOpen) {
+ const cover = tile.cover;
+ const marks = [];
+ if (tile.kind === 'story') marks.push(h('span.anello', icon('circle-dashed', 'xs')));
+ if (cover && cover.kind === 'video') marks.push(h('span.durata', duration(cover.duration || 0)));
+ const what = t(`libreria.tipiTessera.${tile.kind}`);
+ return h('button.miniatura', {
+ type: 'button',
+ onclick: onOpen,
+ 'aria-label': t('attivita.apriAnteprima', { tipo: what, account: tile.username }),
+ title: `${what}, @${tile.username}`,
+ },
+ cover && cover.thumb
+ ? h('img', { src: `/api/thumbnails/${cover.thumb}`, alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' })
+ : h('span.vuota', icon('image', 'xs')),
+ marks.length ? h('span.segni', marks) : null);
+}
+
+/**
+ * The enlarged preview of a line of the history (spec §7.9): a light dialog over the page, without leaving it. The
+ * photo or the video (without sound), account, kind, date, arrows between the files of that line, Esc that closes;
+ * «Apri nella Libreria» opens the viewer of §4.6 on that entry, «Apri l'account» its tab. A damaged or incomplete file
+ * shows the neutral tile. The files of an entry are asked only when the arrows reach it.
+ */
+async function openPreview(page, line, firstTiles, total, startIndex) {
+ let tiles = firstTiles;
+ // More entries than the thumbnails: the arrows walk all of them (up to the server's limit).
+ if (total > firstTiles.length) {
+ try {
+ const query = new URLSearchParams({ account: String(line.accountId), from: line.from, to: line.at, limit: '60' });
+ const all = await api(`/api/activity/arrived?${query}`, { signal: page.signal });
+ if (all.tiles.length) tiles = all.tiles;
+ } catch (error) {
+ if (error.name === 'AbortError') return;
+ }
+ }
+ const entries = new Map();
+ let entryIndex = Math.max(0, tiles.findIndex((x) => x.id === firstTiles[startIndex].id));
+ let fileIndex = 0;
+ let token = 0;
+ const stage = h('div.anteprima-palco');
+ const caption = h('div.anteprima-dida');
+ const position = h('span.dati.muto');
+ const prev = h('button.btn.nudo.tondo', { type: 'button', 'aria-label': t('vis.precedente'), onclick: () => step(-1) }, icon('chevron-left'));
+ const next = h('button.btn.nudo.tondo', { type: 'button', 'aria-label': t('vis.successivo'), onclick: () => step(1) }, icon('chevron-right'));
+ let closeDialog = null;
+
+ async function entryOf(i) {
+ const id = tiles[i].id;
+ if (!entries.has(id)) entries.set(id, api(`/api/entries/${id}`, { signal: page.signal }).catch(() => null));
+ return entries.get(id);
+ }
+
+ async function show() {
+ const mine = ++token;
+ const tile = tiles[entryIndex];
+ const entry = await entryOf(entryIndex);
+ if (mine !== token) return;
+ const media = entry && entry.media.length ? entry.media[Math.min(fileIndex, entry.media.length - 1)] : null;
+ const thumbUrl = media && media.thumb ? `/api/thumbnails/${media.thumb}` : tile.cover && tile.cover.thumb ? `/api/thumbnails/${tile.cover.thumb}` : null;
+ if (!media || media.damaged || !media.available) {
+ fill(stage, h('div.anteprima-neutra', icon('image', 'l'),
+ media && media.damaged ? h('p', t('vis.danneggiato')) : media && !media.available ? h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante')) : null));
+ } else if (media.kind === 'video') {
+ const video = h('video', { src: `/api/media/${media.id}/file`, poster: thumbUrl, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata' });
+ video.muted = true; // spec §10.3: videos start without sound
+ fill(stage, video);
+ } else {
+ fill(stage, h('img', { src: `/api/media/${media.id}/file`, alt: `@${tile.username}` }));
+ }
+ const files = entry ? entry.media.length : 1;
+ fill(caption,
+ h('b', `@${tile.username}`),
+ h('span', t(`libreria.tipiTessera.${tile.kind}`)),
+ h('span.muto', `${capitalize(dayName(tile.day, ''))}, ${tile.time}`),
+ files > 1 ? h('span.muto', t('attivita.fileDi', { n: fileIndex + 1, di: files })) : null);
+ position.textContent = t('attivita.elementoDi', { n: entryIndex + 1, di: tiles.length });
+ prev.disabled = entryIndex === 0 && fileIndex === 0;
+ next.disabled = entryIndex === tiles.length - 1 && fileIndex >= files - 1;
+ }
+
+ async function step(delta) {
+ const entry = await entryOf(entryIndex);
+ const files = entry ? entry.media.length : 1;
+ if (delta > 0) {
+ if (fileIndex < files - 1) fileIndex += 1;
+ else if (entryIndex < tiles.length - 1) {
+ entryIndex += 1;
+ fileIndex = 0;
+ } else return;
+ } else if (fileIndex > 0) fileIndex -= 1;
+ else if (entryIndex > 0) {
+ entryIndex -= 1;
+ const before = await entryOf(entryIndex);
+ fileIndex = before ? Math.max(0, before.media.length - 1) : 0;
+ } else return;
+ show();
+ }
+
+ function onKey(event) {
+ if (event.key === 'ArrowLeft') {
+ event.preventDefault();
+ step(-1);
+ } else if (event.key === 'ArrowRight') {
+ event.preventDefault();
+ step(1);
+ }
+ }
+
+ const list = {
+ position: (id) => {
+ const i = tiles.findIndex((x) => x.id === id);
+ return i < 0 ? null : { index: i, total: tiles.length };
+ },
+ neighbor: async (id, delta) => {
+ const i = tiles.findIndex((x) => x.id === id);
+ return i < 0 ? null : tiles[i + delta] || null;
+ },
+ };
+
+ dialog({
+ title: t('attivita.anteprimaTitolo'),
+ className: 'anteprima-cronologia',
+ build: (close) => {
+ closeDialog = close;
+ return {
+ body: h('div.contenuto', { onkeydown: onKey }, h('div.anteprima-scena', prev, stage, next), caption),
+ footer: h('footer',
+ position,
+ h('div.destra',
+ h('a.btn', { href: withCarried(`/account/${tiles[entryIndex].accountId}/contenuti`), onclick: () => closeDialog() }, icon('user'), t('attivita.apriAccount')),
+ h('button.btn.primo', {
+ type: 'button',
+ onclick: () => {
+ const tile = tiles[entryIndex];
+ closeDialog();
+ openViewer({ tile, source: list, origin: t('nav.libreria') });
+ },
+ }, icon('layout-grid'), t('attivita.apriLibreria')))),
+ };
+ },
+ });
+ show();
+}
+
+// ------------------------------------------------------------------------------------------------- side information
+
+function drawNotice(box, counts) {
+ if (!counts || !counts.download) {
+ box.replaceChildren();
+ return;
+ }
+ fill(box, h('div.avviso.ambra.avviso-azione', icon('layers', 's'),
+ h('span', t('attivita.doppioni', { n: counts.download })),
+ h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi'))));
+}
+
+/** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */
+function drawSuspended(box, state) {
+ const items = state.snapshot.suspendedRecipes || [];
+ if (!items.length) {
+ box.replaceChildren();
+ return;
+ }
+ fill(box, items.map((r) => h('div.avviso.rosso.avviso-azione', { style: { marginBottom: '10px' } },
+ icon('octagon-alert', 's'),
+ h('span', t('attivita.sospesa', { nome: r.name })),
+ h('button.btn.piccolo', {
+ type: 'button',
+ onclick: async () => {
+ try {
+ const result = await api(`/api/engine/recipes/${encodeURIComponent(r.recipe)}/resume`, { method: 'POST' });
+ toast(result.message, result.resumed ? '' : 'errore');
+ refreshEngine();
+ } catch (error) {
+ showError(error);
+ }
+ },
+ }, t('attivita.riattiva')))));
+}
+
+const ALERT_LOOK = {
+ error: { icon: 'octagon-alert', label: 'rosso' },
+ warning: { icon: 'triangle-alert', label: 'ambra' },
+ success: { icon: 'circle-check', label: 'verde' },
+ info: { icon: 'bell', label: '' },
+};
+
+/** «Avvisi»: every alert of the last days, the same ones Telegram and Windows get. Hidden while there are none. */
+function drawAlerts(box, recent) {
+ const items = (recent && recent.items) || [];
+ box.hidden = !items.length;
+ if (!items.length) {
+ box.replaceChildren();
+ return;
+ }
+ fill(box,
+ h('div.testa-blocco', h('h2', t('attivita.avvisi')), h('span.muto', t('attivita.avvisiAiuto', { giorni: recent.days }))),
+ h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => {
+ const look = ALERT_LOOK[i.level] || ALERT_LOOK.info;
+ return h('li',
+ h('span.quando.dati', capitalize(at(i.at))),
+ h('div.chi-cosa', h('b', i.title), h('span', i.message)),
+ label(t(`attivita.livelliAvviso.${i.level}`), look.label, look.icon));
+ }))));
+}
+
+function drawIncidents(box, history) {
+ const items = history.items || [];
+ fill(box,
+ h('div.testa-blocco', h('h2', t('attivita.arresti')), h('span.muto', t('attivita.arrestiAiuto'))),
+ history.advice ? h('div.avviso.ambra', { style: { marginBottom: '10px' } }, icon('triangle-alert', 's'), h('span', history.advice)) : null,
+ items.length
+ ? h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => h('li',
+ h('span.quando.dati', capitalize(at(i.at))),
+ h('div.chi-cosa',
+ h('b', i.title, ' ', h('span.codice.dati', i.signal)),
+ h('span', [i.note, i.url ? i.url.replace(/^https?:\/\/(www\.)?/, '') : null].filter(Boolean).join(' · '))),
+ i.open
+ ? label(t('attivita.aperto'), i.level === 'throttle' ? 'ambra' : 'rosso')
+ : h('span.muto.piccolo', i.resolvedAt ? t('attivita.risolto', { quando: at(i.resolvedAt) }) : i.stoppedUntil ? t('attivita.fermoFino', { quando: at(i.stoppedUntil) }) : '')))))
+ : h('p.vuoto-elenco.pannello', t('attivita.arrestiVuoti')));
+}
+
diff --git a/src/Febe.Web/wwwroot/js/pages/settings-limits.js b/src/Febe.Web/wwwroot/js/pages/settings-limits.js
index c1a52fe..ecf464a 100644
--- a/src/Febe.Web/wwwroot/js/pages/settings-limits.js
+++ b/src/Febe.Web/wwwroot/js/pages/settings-limits.js
@@ -12,11 +12,13 @@ import { checkbox, confirmDialog, label, showError, toast, toggle } from '../cor
import { guardChanges, heading } from './settings.js';
const PACES = ['slow', 'natural', 'brisk'];
+// «Cosa scaricare prima» (spec §7.2): the default order of the kinds, the one the server also uses.
+const DEFAULT_ORDER = ['storie', 'evidenza', 'post', 'reel', 'taggati'];
const DAY_ORDER = [1, 2, 3, 4, 5, 6, 0]; // Monday first; the API counts from Sunday = 0
export default async function limits(page, box) {
let data = await api('/api/settings/limits', { signal: page.signal });
- const snapshot = () => JSON.stringify({ profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays].sort() });
+ const snapshot = () => JSON.stringify({ profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays].sort(), order: form.order });
let form = fromData(data);
let original = snapshot();
const dirty = () => snapshot() !== original;
@@ -32,9 +34,83 @@ export default async function limits(page, box) {
gradualStart: d.gradualStart,
activeDays: new Set(d.activeDays),
jitterOn: d.current.jitterMinutes > 0,
+ order: Array.isArray(d.downloadOrder) && d.downloadOrder.length ? [...d.downloadOrder] : [...DEFAULT_ORDER],
};
}
+ // ------------------------------------------------------------------------------------------- download order
+ // The rows move by dragging (mouse) or with «Su» and «Giù» (keyboard); the order is saved with the save bar.
+ const orderList = h('ol.ordine-tipi', { 'aria-label': t('impostazioni.limiti.ordine') });
+ const orderStatus = h('span.vh', { 'aria-live': 'polite' });
+ let dragged = null;
+
+ function move(from, to, focus) {
+ if (to < 0 || to >= form.order.length || from === to) return;
+ const [kind] = form.order.splice(from, 1);
+ form.order.splice(to, 0, kind);
+ drawOrder();
+ drawSaveBar();
+ orderStatus.textContent = t('impostazioni.limiti.ordineSpostato', { tipo: t(`impostazioni.limiti.tipi.${kind}`), n: to + 1 });
+ if (focus) {
+ const again = orderList.querySelector(`[data-tipo="${kind}"] [data-verso="${focus}"]`);
+ if (again && !again.disabled) again.focus();
+ else orderList.querySelector(`[data-tipo="${kind}"] button:not([disabled])`)?.focus();
+ }
+ }
+
+ function drawOrder() {
+ fill(orderList, form.order.map((kind, i) => {
+ const name = t(`impostazioni.limiti.tipi.${kind}`);
+ const row = h('li.riga-ordine', { draggable: 'true', dataset: { tipo: kind } },
+ h('span.maniglia', { title: t('impostazioni.limiti.ordineManiglia'), 'aria-hidden': 'true' }, icon('grip-vertical', 's')),
+ h('span.posizione.dati', String(i + 1)),
+ h('b', name),
+ kind === 'storie' && i > 0 ? h('span.muto.piccolo', icon('clock', 'xs'), ' ', t('impostazioni.limiti.ordineStorie')) : null,
+ h('div.destra',
+ h('button.btn.piccolo.nudo', {
+ type: 'button', disabled: i === 0, dataset: { verso: 'su' }, 'aria-label': t('impostazioni.limiti.ordineSuDi', { tipo: name }), onclick: () => move(i, i - 1, 'su'),
+ }, icon('chevron-up', 's'), h('span.testo-btn', t('impostazioni.limiti.ordineSu'))),
+ h('button.btn.piccolo.nudo', {
+ type: 'button', disabled: i === form.order.length - 1, dataset: { verso: 'giu' }, 'aria-label': t('impostazioni.limiti.ordineGiuDi', { tipo: name }), onclick: () => move(i, i + 1, 'giu'),
+ }, icon('chevron-down', 's'), h('span.testo-btn', t('impostazioni.limiti.ordineGiu')))));
+ row.addEventListener('dragstart', (event) => {
+ dragged = i;
+ row.classList.add('trascinata');
+ try {
+ event.dataTransfer.effectAllowed = 'move';
+ event.dataTransfer.setData('text/plain', kind);
+ } catch {
+ // Some browsers refuse data on a drag: the index above is enough.
+ }
+ });
+ row.addEventListener('dragend', () => {
+ dragged = null;
+ row.classList.remove('trascinata');
+ });
+ row.addEventListener('dragover', (event) => {
+ if (dragged === null) return;
+ event.preventDefault();
+ });
+ row.addEventListener('drop', (event) => {
+ if (dragged === null) return;
+ event.preventDefault();
+ const from = dragged;
+ dragged = null;
+ move(from, i, null);
+ });
+ return row;
+ }));
+ }
+
+ const orderReset = h('button.btn.collegamento', {
+ type: 'button',
+ onclick: () => {
+ form.order = [...DEFAULT_ORDER];
+ drawOrder();
+ drawSaveBar();
+ },
+ }, t('impostazioni.limiti.ordineMetti'));
+
/** Any edit turns the profile into «Su misura» (spec §7.5). */
function edited() {
form.profile = 'custom';
@@ -363,7 +439,7 @@ export default async function limits(page, box) {
try {
data = await api('/api/settings/limits', {
method: 'PUT',
- body: { profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays] },
+ body: { profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays], downloadOrder: form.order },
});
form = fromData(data);
original = snapshot();
@@ -381,6 +457,7 @@ export default async function limits(page, box) {
drawWindow();
drawPace();
drawTable();
+ drawOrder();
drawSaveBar();
}
@@ -411,7 +488,11 @@ export default async function limits(page, box) {
heading(t('impostazioni.limiti.tetti'), t('impostazioni.limiti.tettiAiuto')),
h('div.pannello.tabella-tetti', h('table.tab',
h('thead', h('tr', h('th', t('impostazioni.limiti.colonne.attivita')), h('th', t('impostazioni.limiti.colonne.ora')), h('th', t('impostazioni.limiti.colonne.giorno')))),
- table))));
+ table))),
+ h('div.sezione',
+ heading(t('impostazioni.limiti.ordine'), t('impostazioni.limiti.ordineAiuto')),
+ h('div.pannello', orderList),
+ h('div.riga-sotto', orderReset, orderStatus)));
}
function toInt(text) {
diff --git a/src/Febe.Web/wwwroot/js/routes.js b/src/Febe.Web/wwwroot/js/routes.js
index cff56ac..4628b28 100644
--- a/src/Febe.Web/wwwroot/js/routes.js
+++ b/src/Febe.Web/wwwroot/js/routes.js
@@ -3,18 +3,20 @@
// so a new page needs only a line here and its module in js/pages/ (see src/Febe.Web/LEGGIMI.md).
export const routes = [
- { pattern: /^\/$/, redirect: '/libreria' },
+ // The Dashboard is the start page (spec §7.9, §10.2, tappa D1); the old address of Attività leads there too.
+ { pattern: /^\/$/, redirect: '/dashboard' },
+ { pattern: /^\/dashboard\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') },
+ { pattern: /^\/attivita\/?$/, redirect: '/dashboard' },
{ pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') },
{ pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.js') },
{ pattern: /^\/account\/(?\d+)(?:\/(?contenuti|impostazioni|cronologia))?\/?$/, nav: 'account', page: () => import('./pages/account.js') },
- { pattern: /^\/attivita\/?$/, nav: 'attivita', page: () => import('./pages/activity.js') },
{ pattern: /^\/importa\/?$/, nav: 'importa', page: () => import('./pages/import.js') },
- { pattern: /^\/doppioni\/?$/, nav: 'attivita', page: () => import('./pages/duplicates.js') },
+ { pattern: /^\/doppioni\/?$/, nav: 'dashboard', page: () => import('./pages/duplicates.js') },
{ pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' },
{
pattern: /^\/impostazioni\/(?generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/,
nav: 'impostazioni',
page: () => import('./pages/settings.js'),
},
- { pattern: /^\/browser\/?$/, nav: 'attivita', page: () => import('./pages/browser.js') },
+ { pattern: /^\/browser\/?$/, nav: 'dashboard', page: () => import('./pages/browser.js') },
];
diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json
index c6c9a69..fc7d854 100644
--- a/src/Febe.Web/wwwroot/testi/it.json
+++ b/src/Febe.Web/wwwroot/testi/it.json
@@ -8,9 +8,9 @@
},
"nav": {
"principale": "Navigazione principale",
+ "dashboard": "Dashboard",
"libreria": "Libreria",
"account": "Account",
- "attivita": "Attività",
"importa": "Importa",
"impostazioni": "Impostazioni",
"fermo": "Serve il tuo intervento"
@@ -520,7 +520,7 @@
"uscita": "Esci"
},
"attivita": {
- "titolo": "Attività",
+ "titolo": "Dashboard",
"pausa": "Metti in pausa",
"riprendi": "Riprendi",
"apriBrowser": "Apri il browser",
@@ -558,8 +558,18 @@
},
"coda": "In coda",
"codaVuota": "La coda è vuota.",
- "fatto": "Appena fatto",
+ "mostraTutta": "Mostra tutta ({n})",
+ "mostraMeno": "Mostra meno",
+ "fatto": "Cronologia dell'attività",
"fattoVuoto": "Nessuna azione nelle ultime ore.",
+ "arrivate": "1 elemento arrivato|{n} elementi arrivati",
+ "altreArrivate": "e 1 altro|e altri {n}",
+ "apriAnteprima": "Ingrandisci: {tipo} di @{account}",
+ "anteprimaTitolo": "Anteprima",
+ "fileDi": "file {n} di {di}",
+ "elementoDi": "{n} di {di}",
+ "apriAccount": "Apri l'account",
+ "apriLibreria": "Apri nella Libreria",
"arresti": "Arresti e rallentamenti",
"arrestiAiuto": "Gli ultimi 14 giorni. Le durate dei fermi sono fisse: 1 ora, 6 ore, 24 ore.",
"arrestiVuoti": "Nessun arresto negli ultimi 14 giorni.",
@@ -673,6 +683,17 @@
"arrestiTesto": "1 ora la prima volta, 6 ore la seconda nelle 24 ore, 24 ore la terza; poi tetti dimezzati per 48 ore.",
"arrestiFissi": "Non si modificano",
"salvati": "Limiti salvati: valgono da subito.",
+ "ordine": "Cosa scaricare prima",
+ "ordineAiuto": "Dopo il giro dei profili che segui, Febe sceglie più spesso il tipo che sta più in alto, e scarica prima i suoi file. Non aggiunge controlli e non scavalca tetti, pause e frequenze. Trascina le righe o usa «Su» e «Giù».",
+ "ordineStorie": "Le storie scadono dopo 24 ore: più in basso stanno, più è facile che scadano prima di essere scaricate.",
+ "ordineMetti": "Ripristina l'ordine predefinito",
+ "ordineManiglia": "Trascina per spostare",
+ "ordineSu": "Su",
+ "ordineGiu": "Giù",
+ "ordineSuDi": "Sposta su: {tipo}",
+ "ordineGiuDi": "Sposta giù: {tipo}",
+ "ordineSpostato": "{tipo}: posizione {n} di 5",
+ "tipi": { "storie": "Storie", "evidenza": "In evidenza", "post": "Post", "reel": "Reel", "taggati": "Taggati" },
"errori": {
"pausa": "La pausa minima non può scendere sotto i {n} minuti.",
"sessione": "Una sessione non può durare più di {n} minuti.",
diff --git a/tests/Febe.Tests/Engine/DownloadOrderTests.cs b/tests/Febe.Tests/Engine/DownloadOrderTests.cs
new file mode 100644
index 0000000..8b5f361
--- /dev/null
+++ b/tests/Febe.Tests/Engine/DownloadOrderTests.cs
@@ -0,0 +1,142 @@
+using Febe.Core.Domain;
+using Febe.Core.Engine;
+using Febe.Tests.Engine.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Engine;
+
+///
+/// «Cosa scaricare prima» (spec §7.2, §6.5, tappa D1): the order of the kinds, its weight on the visits after the Giro dei
+/// seguiti (on the virtual clock, with a fixed seed) and on the queue of the files.
+///
+[TestClass]
+public sealed class DownloadOrderTests
+{
+ private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
+
+ [TestMethod]
+ public void TheDefaultOrderIsStoriesHighlightsPostsReelsTagged()
+ {
+ Assert.AreEqual("storie,evidenza,post,reel,taggati", DownloadOrder.Default.ToString());
+ Assert.IsTrue(DownloadOrder.Parse(null).IsDefault);
+ Assert.IsTrue(DownloadOrder.Parse(" ").IsDefault);
+ Assert.AreEqual(16, DownloadOrder.Default.Weight(DownloadKind.Stories));
+ Assert.AreEqual(8, DownloadOrder.Default.Weight(DownloadKind.Highlights));
+ Assert.AreEqual(4, DownloadOrder.Default.Weight(DownloadKind.Posts));
+ Assert.AreEqual(2, DownloadOrder.Default.Weight(DownloadKind.Reels));
+ Assert.AreEqual(1, DownloadOrder.Default.Weight(DownloadKind.Tagged));
+ }
+
+ [TestMethod]
+ [DataRow("taggati,post", "taggati,post,storie,evidenza,reel")]
+ [DataRow("POST, post ,qualcosa,reel", "post,reel,storie,evidenza,taggati")]
+ [DataRow("reel,taggati,post,evidenza,storie", "reel,taggati,post,evidenza,storie")]
+ public void AnyStoredTextGivesTheFiveKindsOnce(string stored, string expected)
+ {
+ var order = DownloadOrder.Parse(stored);
+ Assert.AreEqual(expected, order.ToString());
+ Assert.HasCount(5, order.Kinds);
+ Assert.AreEqual(order.ToString(), DownloadOrder.Parse(order.ToString()).ToString());
+ }
+
+ [TestMethod]
+ public void EveryTaskAndEntryKindHasItsPlace()
+ {
+ Assert.IsNull(DownloadOrder.KindOf(EngineTaskKind.FollowingSweep), "il giro resta primo, nessun tipo lo pesa");
+ Assert.IsNull(DownloadOrder.KindOf(EngineTaskKind.FollowingList));
+ Assert.AreEqual(DownloadKind.Stories, DownloadOrder.KindOf(EngineTaskKind.AccountStories));
+ Assert.AreEqual(DownloadKind.Highlights, DownloadOrder.KindOf(EngineTaskKind.HighlightCheck));
+ Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EngineTaskKind.ProfileCheck));
+ Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EngineTaskKind.Backfill));
+ Assert.AreEqual(DownloadKind.Reels, DownloadOrder.KindOf(EngineTaskKind.ReelsCheck));
+ Assert.AreEqual(DownloadKind.Tagged, DownloadOrder.KindOf(EngineTaskKind.TaggedCheck));
+ Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EntryKind.ProfilePicture), "le foto del profilo vanno con i post");
+
+ var queue = DownloadOrder.Parse("taggati,post").EntryKinds();
+ CollectionAssert.AreEqual(new[] { EntryKind.Tagged, EntryKind.Post, EntryKind.ProfilePicture, EntryKind.Story, EntryKind.Highlight }, queue.ToArray());
+ }
+
+ [TestMethod]
+ public async Task TheQueueOfTheFilesFollowsTheOrder()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var a = await db.Accounts.AddAsync(Make.Account("marta.demo"));
+ await db.Entries.AddAsync(Make.Entry(a.Id, "post", Make.T0), [Make.Photo(1), Make.Photo(2)]);
+ await db.Entries.AddAsync(Make.Entry(a.Id, "storia", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(2) }, [Make.Video()]);
+ await db.Entries.AddAsync(Make.Entry(a.Id, "taggato", Make.T0, EntryKind.Tagged), [Make.Photo()]);
+
+ var standard = await db.Media.ListPendingDownloadsAsync(10, DownloadOrder.Default.EntryKinds());
+ CollectionAssert.AreEqual(new[] { EntryKind.Story, EntryKind.Post, EntryKind.Post, EntryKind.Tagged }, standard.Select(p => p.Kind).ToArray());
+
+ var tagged = await db.Media.ListPendingDownloadsAsync(10, DownloadOrder.Parse("taggati,post,storie").EntryKinds());
+ CollectionAssert.AreEqual(new[] { EntryKind.Tagged, EntryKind.Post, EntryKind.Post, EntryKind.Story }, tagged.Select(p => p.Kind).ToArray());
+ Assert.AreEqual(1, tagged[1].Media.Position, "dentro un tipo l'ordine di sempre");
+ }
+
+ [TestMethod]
+ public async Task TheOrderWeighsTheVisitsAfterTheSweepWithoutMakingThemFixed()
+ {
+ var standard = await FirstVisitsAsync(null);
+ var postsFirst = await FirstVisitsAsync("post,storie");
+
+ Assert.IsGreaterThan(10, postsFirst.Sessions, "abbastanza sessioni con le due cose da fare");
+ Assert.IsGreaterThan(standard.PostsFirst + 0.2, postsFirst.PostsFirst, $"post per primi: {postsFirst.PostsFirst:P0} contro {standard.PostsFirst:P0}");
+ Assert.IsLessThan(1.0, postsFirst.PostsFirst, "l'ordine pesa ma non diventa fisso");
+ Assert.IsGreaterThan(0.0, standard.PostsFirst, "anche con le storie in cima i post vengono talvolta prima");
+ Assert.IsGreaterThan(0.75, postsFirst.SweepFirst, "il giro resta di norma il primo");
+ Assert.AreEqual(standard.SweepFirst, postsFirst.SweepFirst, 0.15, "la composizione delle sessioni non cambia");
+ }
+
+ [TestMethod]
+ public async Task AKindWithNothingDueIsNotVisited()
+ {
+ await using var bed = await EngineTestBed.CreateAsync(Morning);
+ await bed.Db.Settings.SetAsync(DownloadOrder.SettingKey, "evidenza,taggati,reel,post,storie");
+ await bed.AddAccountAsync("seguito.demo", followed: true);
+ for (var i = 0; i < 4; i++)
+ {
+ await bed.AddAccountAsync($"post{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos);
+ }
+
+ var runner = new ScriptedRunner(bed.Governor, bed.Clock);
+ bed.Start(runner);
+ await bed.RunUntilAsync(Morning.AddDays(2));
+
+ Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Highlight), "nessuna raccolta in evidenza da controllare");
+ Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck), "il resto del lavoro va avanti");
+ }
+
+ ///
+ /// Three days of the engine with accounts that want only their stories and accounts that want only their posts: in
+ /// how many sessions with both, the first of them after the sweep was a profile check.
+ ///
+ private static async Task<(double PostsFirst, double SweepFirst, int Sessions)> FirstVisitsAsync(string? order)
+ {
+ await using var bed = await EngineTestBed.CreateAsync(Morning, seed: 11);
+ if (order is not null)
+ {
+ await bed.Db.Settings.SetAsync(DownloadOrder.SettingKey, order);
+ }
+
+ await bed.AddAccountAsync("seguito.demo", followed: true);
+ for (var i = 0; i < 6; i++)
+ {
+ await bed.AddAccountAsync($"storie{i}.demo", followed: false, Frequency.High, types: ContentTypes.Stories);
+ await bed.AddAccountAsync($"post{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos);
+ }
+
+ var runner = new ScriptedRunner(bed.Governor, bed.Clock);
+ bed.Start(runner);
+ await bed.RunUntilAsync(Morning.AddDays(3));
+
+ var sessions = runner.Runs.GroupBy(r => r.SessionId).ToList();
+ var sweepFirst = sessions.Count(g => g.First().Request.Kind == RecipeKind.FollowingSweep) / (double)sessions.Count;
+ var both = sessions
+ .Select(g => g.Where(r => r.Request.Kind is RecipeKind.AccountStories or RecipeKind.ProfileCheck).ToList())
+ .Where(v => v.Any(r => r.Request.Kind == RecipeKind.AccountStories) && v.Any(r => r.Request.Kind == RecipeKind.ProfileCheck))
+ .ToList();
+ var postsFirst = both.Count == 0 ? 0 : both.Count(v => v[0].Request.Kind == RecipeKind.ProfileCheck) / (double)both.Count;
+ return (postsFirst, sweepFirst, both.Count);
+ }
+}
diff --git a/tests/Febe.Tests/Web/DashboardApiTests.cs b/tests/Febe.Tests/Web/DashboardApiTests.cs
new file mode 100644
index 0000000..b008c88
--- /dev/null
+++ b/tests/Febe.Tests/Web/DashboardApiTests.cs
@@ -0,0 +1,68 @@
+using System.Net;
+using Febe.Core.Domain;
+using Febe.Core.Engine;
+using Febe.Tests.Support;
+using Febe.Tests.Web.Part2Support;
+using Febe.Tests.Web.Support;
+
+namespace Febe.Tests.Web;
+
+///
+/// What the Dashboard and «Cosa scaricare prima» ask the server (spec §7.2, §7.9, tappa D1): the thumbnails of a line of
+/// the history, and the order of the kinds saved with the limits.
+///
+[TestClass]
+public sealed class DashboardApiTests
+{
+ [TestMethod]
+ public async Task ALineOfTheHistoryGetsTheEntriesItSavedNewestFirst()
+ {
+ await using var server = await Part2.StartAsync();
+ var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.prova"));
+ var luca = await server.Db.Accounts.AddAsync(Make.Account("luca.prova"));
+ var start = Make.T0.AddHours(1);
+ await server.Db.Entries.AddAsync(Make.Entry(marta.Id, "prima", Make.T0) with { DiscoveredAt = start.AddMinutes(-5) }, [Make.Photo()]);
+ for (var i = 0; i < 3; i++)
+ {
+ await server.Db.Entries.AddAsync(Make.Entry(marta.Id, $"nuovo{i}", Make.T0) with { DiscoveredAt = start.AddSeconds(10 * (i + 1)) }, [Make.Photo()]);
+ }
+
+ await server.Db.Entries.AddAsync(Make.Entry(luca.Id, "altro", Make.T0) with { DiscoveredAt = start.AddSeconds(15) }, [Make.Photo()]);
+
+ var from = Uri.EscapeDataString(start.ToString("O"));
+ var to = Uri.EscapeDataString(start.AddMinutes(1).ToString("O"));
+ var arrived = await server.GetJsonAsync($"/api/activity/arrived?account={marta.Id}&from={from}&to={to}&limit=2");
+ Assert.AreEqual(3, arrived.Int("total"), "only what that recipe saved, of that account");
+ var tiles = arrived.Items("tiles").ToList();
+ Assert.HasCount(2, tiles, "at most what the line shows");
+ Assert.IsTrue(tiles.All(t => t.Int("accountId") == marta.Id));
+
+ var (status, _, _) = await server.GetAsync($"/api/activity/arrived?account={marta.Id}&from={to}&to={from}");
+ Assert.AreEqual(HttpStatusCode.BadRequest, status, "the end before the start");
+ (status, _, _) = await server.GetAsync("/api/activity/arrived?account=uno");
+ Assert.AreEqual(HttpStatusCode.BadRequest, status);
+ }
+
+ [TestMethod]
+ public async Task TheOrderOfTheKindsIsSavedWithTheLimitsAndKeptWhenNotSent()
+ {
+ await using var server = await Part2.StartAsync();
+ var limits = await server.GetJsonAsync("/api/settings/limits");
+ CollectionAssert.AreEqual(new[] { "storie", "evidenza", "post", "reel", "taggati" }, limits.Items("downloadOrder").Select(k => k.GetString()).ToArray());
+
+ var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits",
+ new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 }, downloadOrder = new[] { "taggati", "post" } });
+ Assert.AreEqual(HttpStatusCode.OK, status);
+ CollectionAssert.AreEqual(new[] { "taggati", "post", "storie", "evidenza", "reel" }, saved.Items("downloadOrder").Select(k => k.GetString()).ToArray());
+ Assert.AreEqual("taggati,post,storie,evidenza,reel", await server.Db.Settings.GetAsync(DownloadOrder.SettingKey));
+
+ (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits",
+ new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 } });
+ Assert.AreEqual(HttpStatusCode.OK, status);
+ Assert.AreEqual("taggati", saved.Items("downloadOrder").First().GetString(), "not sent: the stored order stays");
+
+ await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits",
+ new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 }, downloadOrder = DownloadOrder.Default.Kinds.Select(DownloadOrder.NameOf).ToArray() });
+ Assert.IsNull(await server.Db.Settings.GetAsync(DownloadOrder.SettingKey), "the default order is no stored value");
+ }
+}
diff --git a/tests/Febe.Tests/Web/InterfaceTests.cs b/tests/Febe.Tests/Web/InterfaceTests.cs
index 6f2453a..83eb933 100644
--- a/tests/Febe.Tests/Web/InterfaceTests.cs
+++ b/tests/Febe.Tests/Web/InterfaceTests.cs
@@ -114,6 +114,24 @@ public sealed class InterfaceTests
await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito chiudendo la scheda");
}
+ [TestMethod]
+ public async Task TheRootAndTheOldAttivitaOpenTheDashboardFirstInTheSidebar()
+ {
+ // Spec §7.9, §10.2 (tappa D1): the Dashboard is the start page and the first item of the sidebar.
+ var connection = new RecordingConnection { Status = Connected };
+ await using var server = await DockerAsync(connection, new FakeRemoteViewHost());
+ await using var ui = await UiBrowser.StartAsync();
+ await ui.OpenAsync(new Uri(server.Address, "/"));
+ await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .dashboard .cruscotto .anteprima') !== null", "Dashboard da /");
+ Assert.AreEqual("dashboard", (await ui.EvalAsync("document.querySelector('.nav a').dataset.nav")).GetString(), "prima voce della barra laterale");
+ Assert.AreEqual("/dashboard", (await ui.EvalAsync("new URL(document.querySelector('a.stato').href).pathname")).GetString(), "il riquadro di stato rimanda alla Dashboard");
+
+ await ui.NavigateAsync("/libreria");
+ await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
+ await ui.NavigateAsync("/attivita");
+ await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .dashboard') !== null", "Dashboard dal vecchio /attivita");
+ }
+
[TestMethod]
public async Task ABrowserPageLeftWhileLoadingNeverTakesTheBrowser()
{
@@ -153,7 +171,7 @@ public sealed class InterfaceTests
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso");
await ui.EvalAsync("document.querySelector('.salva .btn.primo').click()");
- await ui.WaitAsync("location.pathname === '/attivita'", "Attività dopo «Ho finito»");
+ await ui.WaitAsync("location.pathname === '/dashboard'", "Dashboard dopo «Ho finito»");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
@@ -632,7 +650,7 @@ public sealed class InterfaceTests
// Attività waits for its alerts and Alberto goes back to the Libreria before they come. Issue #8: going back
// after a fixed 200 ms, a slow machine had not even loaded the page yet, and the alerts were never asked.
await ui.EvalAsync("window.__hold('/api/alerts')");
- await ui.NavigateAsync("/attivita");
+ await ui.NavigateAsync("/dashboard");
await ui.WaitAsync("window.__started['/api/alerts'] >= 1", "Attività in attesa dei suoi avvisi");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .benvenuto') !== null", "Libreria (primo avvio)");
@@ -654,7 +672,7 @@ public sealed class InterfaceTests
CollectionAssert.AreEqual(new[] { "GET /api/alerts" }, await ui.AskedAsync("/api/alerts"), "Attività, left, no longer listens to the library");
// The page that stays open still works as usual: its minute timer runs, and a change of the library reloads it.
- await ui.NavigateAsync("/attivita");
+ await ui.NavigateAsync("/dashboard");
await ui.WaitAsync("window.__intervals(60000) === 1", "Attività aperta");
await ui.EvalAsync("window.__libraryChanged()");
await ui.WaitAsync("window.__asked.filter((r) => r.includes('/api/alerts')).length >= 3", "Attività aggiornata dopo la modifica");
diff --git a/tests/Febe.Tests/Web/LoginSecurityTests.cs b/tests/Febe.Tests/Web/LoginSecurityTests.cs
index adba142..1014f76 100644
--- a/tests/Febe.Tests/Web/LoginSecurityTests.cs
+++ b/tests/Febe.Tests/Web/LoginSecurityTests.cs
@@ -107,7 +107,7 @@ public sealed class LoginSecurityTests
const string origin = "http://tower:8480";
List<(string? Value, string Expected)> cases =
[
- .. Foreign.Select(v => ((string?)v, origin + "/libreria")),
+ .. Foreign.Select(v => ((string?)v, origin + "/dashboard")),
(null, origin + "/libreria"),
("/account/12", origin + "/account/12"),
("/libreria?tipo=foto#x", origin + "/libreria?tipo=foto#x"),