D1, prima parte: Dashboard al posto di Attività e «Cosa scaricare prima» generale

Richiesta di Alberto (#59): decidere cosa scaricare prima, una Dashboard compatta come
pagina iniziale da guardare mentre il motore lavora, e le miniature di ciò che è arrivato.

- Dashboard (§7.9, §10.2): /dashboard è la pagina iniziale e la prima voce della barra;
  /, /attivita, «Ho finito» del browser, il riquadro di stato e il ritorno dopo l'accesso
  portano lì. In alto l'anteprima del browser sempre visibile, chiesta ogni secondo mentre
  il motore lavora (LiveBrowserPreview cattura al più un fotogramma al secondo), accanto
  cosa sta facendo e i quattro tetti; poi la striscia più bassa, la cronologia con le
  miniature e la coda ridotta alle prime righe con «Mostra tutta». Sotto i 1000 px una
  colonna sola.
- Miniature della cronologia: /api/activity/arrived dà gli elementi che una ricetta ha
  salvato (account, inizio e fine della ricetta), chiesti solo quando la riga entra in
  vista, al più otto con «+N». Un clic apre un'anteprima leggera con foto o video senza
  audio, frecce fra i file della riga, Esc, «Apri nella Libreria» e «Apri l'account».
- «Cosa scaricare prima» (§7.2, §6.5): ordine generale dei tipi in Impostazioni → Limiti
  e comportamento (trascinare, «Su» e «Giù», nota sulle storie che scadono), predefinito
  storie, evidenza, post, reel, taggati. Dopo il giro, il lavoro dovuto si estrae con il
  peso dell'account per il peso del tipo (16, 8, 4, 2, 1): pesa, non rende fisso. La coda
  dei file segue lo stesso ordine.
- Prove: DownloadOrderTests (ordine, pesi, coda, motore con seme fisso: il primo tipo
  viene più spesso ma non sempre, il giro resta primo, un tipo senza lavoro non si
  visita), DashboardApiTests, una prova dell'interfaccia per / e /attivita.

Non ancora fatto: ordine per account e segno del reel (serve una migrazione da concordare
con E1), «Raggruppa i post» / «Tutte le foto», confronto con i mockup, revisione del
resto della guida che nomina ancora Attività.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 14:53:03 +01:00
1 parent 2068dd28f3
commit d6c0ef851d
38 files changed
+1468 -479

No files matched your search

+2
View File
@@ -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 |
+15 -8
View File
@@ -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)).
+9
View File
@@ -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
+4 -4
View File
@@ -6,13 +6,13 @@ using Febe.Web.Engine;
namespace Febe.App;
/// <summary>
/// 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.
/// </summary>
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;
@@ -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();
+160
View File
@@ -0,0 +1,160 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>A type of «Cosa scaricare prima» (spec §7.2): the kinds of recipes of §6.3, grouped as Alberto names them.</summary>
public enum DownloadKind
{
/// <summary>«Storie»: Storie di un account.</summary>
Stories,
/// <summary>«Evidenza»: Raccolta in evidenza.</summary>
Highlights,
/// <summary>«Post»: Controllo del profilo and Storico, profile pictures included.</summary>
Posts,
/// <summary>«Reel»: Reel.</summary>
Reels,
/// <summary>«Taggati»: Taggati.</summary>
Tagged,
}
/// <summary>
/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in <see cref="SettingKey"/> as their
/// Italian names separated by commas. It weighs the next visit after the Giro dei seguiti (the weight of a kind is
/// <see cref="Weight"/>, 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.
/// </summary>
public sealed class DownloadOrder
{
/// <summary>The general order (Impostazioni → Limiti e comportamento).</summary>
public const string SettingKey = "scaricamento.ordine";
/// <summary>The weights of the positions, first to last (spec §7.4 table, «Peso di un tipo nella scelta»).</summary>
public static readonly IReadOnlyList<double> 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<DownloadKind> kinds) => Kinds = kinds;
/// <summary>Storie, evidenza, post, reel, taggati (spec §7.2, §16 question 19).</summary>
public static DownloadOrder Default { get; } = new([DownloadKind.Stories, DownloadKind.Highlights, DownloadKind.Posts, DownloadKind.Reels, DownloadKind.Tagged]);
/// <summary>The five kinds, first to last.</summary>
public IReadOnlyList<DownloadKind> Kinds { get; }
/// <summary>True when this is the order of <see cref="Default"/>.</summary>
public bool IsDefault => Kinds.SequenceEqual(Default.Kinds);
/// <summary>The Italian name of a kind, as stored and as the interface sends it.</summary>
public static string NameOf(DownloadKind kind) => Names.First(n => n.Kind == kind).Name;
/// <summary>
/// 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 <see cref="Default"/>.
/// </summary>
public static DownloadOrder Parse(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return Default;
}
var kinds = new List<DownloadKind>();
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);
}
/// <summary>Builds an order from the names the interface sends; the same rules as <see cref="Parse"/>.</summary>
public static DownloadOrder From(IEnumerable<string> names) => Parse(string.Join(',', names));
/// <summary>The stored text: the five names, comma separated.</summary>
public override string ToString() => string.Join(',', Kinds.Select(NameOf));
/// <summary>0 for the first kind, 4 for the last.</summary>
public int Position(DownloadKind kind)
{
for (var i = 0; i < Kinds.Count; i++)
{
if (Kinds[i] == kind)
{
return i;
}
}
return Kinds.Count - 1;
}
/// <summary>16, 8, 4, 2 or 1 by the position of the kind.</summary>
public double Weight(DownloadKind kind) => Weights[Position(kind)];
/// <summary>
/// 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.
/// </summary>
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,
};
/// <summary>
/// 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 <c>entry</c> of D1).
/// </summary>
public static DownloadKind KindOf(EntryKind entry) => entry switch
{
EntryKind.Story => DownloadKind.Stories,
EntryKind.Highlight => DownloadKind.Highlights,
EntryKind.Tagged => DownloadKind.Tagged,
_ => DownloadKind.Posts,
};
/// <summary>The entry kinds in the order of the queue: the position of each <see cref="EntryKind"/>, first to last.</summary>
public IReadOnlyList<EntryKind> EntryKinds()
{
var all = Enum.GetValues<EntryKind>();
return [.. all.OrderBy(e => Position(KindOf(e))).ThenBy(e => Array.IndexOf(all, e))];
}
/// <summary>The general order stored in the settings.</summary>
public static async Task<DownloadOrder> LoadAsync(ISettingsStore settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
return Parse(await settings.GetAsync(SettingKey, ct).ConfigureAwait(false));
}
/// <summary>Stores the general order; the default is stored as no value («come le impostazioni predefinite»).</summary>
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);
}
}
+10 -1
View File
@@ -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;
}
+15 -2
View File
@@ -136,8 +136,21 @@ public sealed record BudgetView(
/// <param name="Suspended">The engine is stopped or paused.</param>
public sealed record QueueItem(long TaskId, EngineTaskKind Kind, long? AccountId, string Title, string Detail, DateTimeOffset? Around, string When, bool IsManual, bool Suspended);
/// <summary>A line of «Appena fatto».</summary>
public sealed record RecentActionView(DateTimeOffset At, string Time, string Title, string Detail, string? Badge, bool InProgress);
/// <summary>A line of the history of the Dashboard («Appena fatto»).</summary>
/// <param name="AccountId">Account of the recipe, when it has one and saved something: with <see cref="From"/> and
/// <see cref="At"/> it tells the page which entries arrived, for their thumbnails (spec §7.9, tappa D1).</param>
/// <param name="From">When the recipe started.</param>
/// <param name="NewEntries">Entries saved by the recipe.</param>
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);
/// <summary>A recipe suspended after repeated unrecognized formats.</summary>
public sealed record SuspendedRecipeView(RecipeKind Recipe, string Name, DateTimeOffset Since);
+4 -1
View File
@@ -8,6 +8,8 @@ namespace Febe.Core.Engine;
/// <param name="Detail">«2 storie nuove», «Nessuna novità».</param>
/// <param name="Status">How it ended.</param>
/// <param name="NewEntries">New entries found.</param>
/// <param name="StartedAt">When it started: the entries of the account discovered from then to <see cref="At"/> are
/// the ones it saved (thumbnails of the Dashboard, spec §7.9).</param>
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)
{
/// <summary>Short label of the outcome for a badge («Scaricato», «Rimandato»...); null when nothing to say.</summary>
public string? Badge => Status switch
+32 -31
View File
@@ -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<EngineTask> Weighted(IEnumerable<EngineTask> tasks, Dictionary<long, Account> accounts, DateTimeOffset now, TimeSpan window)
private IEnumerable<EngineTask> Weighted(IEnumerable<EngineTask> tasks, Dictionary<long, Account> 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,
+9
View File
@@ -60,6 +60,12 @@ public interface IEntryStore
/// <summary>Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).</summary>
Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
/// <summary>
/// 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 <paramref name="limit"/>, with how many there are in all.
/// </summary>
Task<ArrivedEntries> ListDiscoveredAsync(long accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default);
/// <summary>Entries of (account, kind) discovered in [from, to): per-account daily backfill limit.</summary>
Task<int> CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default);
@@ -74,3 +80,6 @@ public interface IEntryStore
/// <summary>Tiles for given entries, in the given order (e.g. the items of a highlight collection).</summary>
Task<IReadOnlyList<LibraryTile>> GetTilesAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
}
/// <summary>Entries saved by a recipe: the first ones, newest first, and how many in all.</summary>
public sealed record ArrivedEntries(IReadOnlyList<long> EntryIds, int Total);
+7
View File
@@ -30,6 +30,13 @@ public interface IMediaStore
/// </summary>
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default);
/// <summary>
/// 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 <paramref name="kindOrder"/>, 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.
/// </summary>
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, IReadOnlyList<EntryKind> kindOrder, CancellationToken ct = default);
/// <summary>Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»).</summary>
Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default);
+23
View File
@@ -197,6 +197,29 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
ct);
}
public Task<ArrivedEntries> ListDiscoveredAsync(long accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var ids = new List<long>();
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<int> CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync(
c => (int)c.Command("""
+19 -1
View File
@@ -81,6 +81,24 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore
ct);
public Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) =>
ListPendingAsync(limit, "(e.kind = 'Story') DESC", ct);
public Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, IReadOnlyList<EntryKind> 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<IReadOnlyList<PendingDownload>> ListPendingAsync(int limit, string first, CancellationToken ct) =>
db.ReadAsync<IReadOnlyList<PendingDownload>>(
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<PendingDownload>();
+1 -1
View File
@@ -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);
+27
View File
@@ -23,6 +23,15 @@ public static class ActivityApi
/// <summary>Days of stops shown by the page.</summary>
public const int HistoryDays = 14;
/// <summary>Thumbnails of a line of the history (spec §7.9: at most eight, «+12» for the rest).</summary>
public const int ArrivedShown = 8;
/// <summary>The most the arrows of the enlarged preview walk through in one line.</summary>
public const int ArrivedLimit = 60;
private static bool TryTime(string text, out DateTimeOffset at) =>
DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out at);
/// <summary>
/// «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);
+3
View File
@@ -58,6 +58,9 @@ public sealed record TileDto(
/// <summary>A window of tiles; cursors continue it (null: nothing more that way).</summary>
public sealed record LibraryPageDto(IReadOnlyList<TileDto> Tiles, string? Older, string? Newer);
/// <summary>What a line of the history of the Dashboard saved (spec §7.9): the first tiles and how many in all.</summary>
public sealed record ArrivedDto(IReadOnlyList<TileDto> Tiles, int Total);
/// <summary>A day of the mosaic: its count and the cursor that starts at its end.</summary>
public sealed record DayDto(string Day, int Count, string Cursor);
+1
View File
@@ -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))]
+7 -3
View File
@@ -164,10 +164,14 @@ public sealed record LimitsDto(
bool GradualStart,
IReadOnlyList<int> ActiveDays,
LimitRulesDto Rules,
IReadOnlyList<string> Stops);
IReadOnlyList<string> Stops,
IReadOnlyList<string>? DownloadOrder = null);
/// <summary>Saves the limits; <see cref="Values"/> is read when <see cref="Profile"/> is custom.</summary>
public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList<int> ActiveDays);
/// <summary>
/// Saves the limits; <see cref="Values"/> is read when <see cref="Profile"/> is custom. <see cref="DownloadOrder"/> is
/// «Cosa scaricare prima» (spec §7.2), the names of the five kinds first to last; null keeps the stored order.
/// </summary>
public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList<int> ActiveDays, IReadOnlyList<string>? DownloadOrder = null);
// ---------------------------------------------------------------- settings: notifications (spec §13.3)
+16 -2
View File
@@ -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
/// <summary>The limits with «Cosa scaricare prima» (spec §7.2), as stored.</summary>
private static async Task<LimitsDto> 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);
+1 -1
View File
@@ -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();
}
}
+13 -2
View File
@@ -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);
/// <summary>A line of «Appena fatto».</summary>
public sealed record DemoAction(DateTimeOffset At, string Title, string Detail, string? Badge);
/// <summary>A line of the history of the demo; <see cref="AccountId"/> and <see cref="From"/> when it saved something
/// (its thumbnails on the Dashboard, spec §7.9).</summary>
public sealed record DemoAction(DateTimeOffset At, string Title, string Detail, string? Badge, long? AccountId = null, DateTimeOffset? From = null, int NewEntries = 0);
/// <summary>Everything the demo engine needs to tell a coherent day (spec §10.6: «i conteggi tornano, gli orari sono plausibili»).</summary>
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();
+2 -2
View File
@@ -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`
+47 -1
View File
@@ -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}
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6.5 14.5 12 9 17.5 14.5"/>
</svg>

After

Width:  |  Height:  |  Size: 216 B

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<line x1="9" y1="6" x2="9" y2="6.01"/>
<line x1="15" y1="6" x2="15" y2="6.01"/>
<line x1="9" y1="12" x2="9" y2="12.01"/>
<line x1="15" y1="12" x2="15" y2="12.01"/>
<line x1="9" y1="18" x2="9" y2="18.01"/>
<line x1="15" y1="18" x2="15" y2="18.01"/>
</svg>

After

Width:  |  Height:  |  Size: 429 B

+2 -2
View File
@@ -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 <origin> only; the library when <value> is missing or unsafe. */
/** The absolute address to open after the login, on <origin> only; the Dashboard when <value> 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)) {
+6 -6
View File
@@ -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') }));
-395
View File
@@ -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')));
}
+1 -1
View File
@@ -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' } },
+672
View File
@@ -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')));
}
@@ -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) {
+6 -4
View File
@@ -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\/(?<id>\d+)(?:\/(?<tab>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\/(?<section>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') },
];
+24 -3
View File
@@ -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.",
@@ -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;
/// <summary>
/// «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.
/// </summary>
[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");
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
+68
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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");
}
}
+21 -3
View File
@@ -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");
+1 -1
View File
@@ -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"),