D1: Dashboard, «Cosa scaricare prima», «Raggruppa i post» / «Tutte le foto» (#59) #66

Merged
Alby96 merged 17 commits from funzione/dashboard into main 2026-11-26 16:02:00 +01:00
44 changed files with 261 additions and 118 deletions
Showing only changes of commit 58ff4e48b3 - Show all commits

No files matched your search

+6
View File
@@ -558,3 +558,9 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-25 | Selezione con «Tutte le foto»: si scelgono file (la chiave della tessera è il file); l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e barra e conferma lo dicono («3 file scelti, di 2 elementi», «3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»); anche «Elimina» del visualizzatore elimina l'elemento intero. «Copia in…» e «Fotogrammi…» non sono in questo ramo: quando arrivano (E2, E3) lavorano sui file scelti | §4.6: eliminare resta per elemento, per non lasciare post a metà; «Copia in…» di §4.10 lavora sui file |
| 2026-11-25 | La scelta «Raggruppa i post» / «Tutte le foto» sta nella memoria locale del browser (`febe.mosaico.libreria`, `febe.mosaico.account`, lette e scritte in un `try` da `local`); qualunque altro valore, o nessuna memoria, vale «Raggruppa i post». Nella scheda account l'interruttore manca in «In evidenza» (disegnata per raccolta) e le linguette contano elementi. Nella Libreria l'interruttore mostra solo le icone sotto i 1680 px di finestra, nella scheda account sotto i 1000 px | §4.6; la riga degli strumenti della Libreria a 1440 px non ha posto per due voci con il testo; nome e suggerimento restano sui pulsanti |
| 2026-11-25 | Dimostrazione: circa una serie di tre file o più su cinque ha un video in seconda posizione, deciso dall'identificativo dell'elemento (durata e peso compresi) e non dalla sequenza casuale, così il resto del mondo della dimostrazione resta com'era | «Tutte le foto» va provata anche con i video dentro un carosello; le prove della dimostrazione contano sugli stessi dati |
| 2026-11-25 | Il totale dei file di «Tutte le foto» in `/api/library/days` è la somma dei giorni (`CountLibraryByDayAsync` in modo file); `CountLibraryFilesAsync` è tolto | Ogni richiesta faceva due volte lo stesso passaggio su tutta la tabella `media` (0,2-0,3 s l'uno su 200.000 elementi), e il mosaico la ripete a ogni cambiamento della libreria, cioè di continuo mentre Febe scarica; i due numeri erano sempre uguali per costruzione |
| 2026-11-25 | Totali e conteggi per giorno di «Foto» e «Video» raggruppati, su tutta la libreria: `+e.kind = 'Post' AND +e.id IN (SELECT entry_id FROM media WHERE kind = …)` su un indice di copertura di `entry`, invece di un EXISTS per post; finestre, controlli del cursore e filtri sugli account restano con l'EXISTS. Nuove misure in `LibraryScaleTests` con limite 600 ms | Con l'EXISTS ogni post leggeva la sua riga: 1,3-1,6 s per i totali di «Video» e «Foto» a ogni caricamento (anche in «Tutte le foto», che chiede i totali). Con l'elenco: 86 ms (Video) e 141 ms (Foto); senza i `+` SQLite cercava ogni elemento per chiave e «Foto» costava ancora 0,85 s. Una finestra si ferma dopo poche centinaia di post, e con un account i post sono pochi: lì l'EXISTS costa meno |
| 2026-11-25 | Correzione della riga sulla quota di chi aspetta: il posto riservato (uno su otto) va al file più vecchio di **tutta** la coda, non a turno a ogni tipo. Non c'è un minimo di 1/8 per tipo: un tipo trovato dopo un arretrato più vecchio di un altro tipo (taggati scoperti dopo migliaia di post dello Storico) aspetta che quell'arretrato finisca. Vale solo che nessun file aspetta per sempre | È l'ordine che Alberto ha chiesto (storie, poi post, poi reel, poi taggati); una rotazione fra i tipi lo scavalcherebbe. Commento di `DownloadOptions.LongestWaitingShare` corretto, prova nuova con un arretrato più vecchio di un altro tipo |
| 2026-11-25 | Visualizzatore con «Tutte le foto»: le frecce saltano i file che il mosaico non mostra (le foto di un post con «Video», i video con «Foto», i file non in libreria) e passano alla tessera vicina; un file aperto dalla striscia della serie che non è una tessera non ha «file N di M» nell'intestazione. L'interruttore «Raggruppa i post» / «Tutte le foto» non fa nulla sulla voce già scelta | §4.6: «le frecce vanno di file in file» fra le tessere; prima l'intestazione diceva il numero di un altro file. Ricliccare la voce scelta ridisegnava il mosaico, tornava in cima e perdeva la selezione |
| 2026-11-25 | Tolta l'icona `activity` (`wwwroot/icone/activity.svg`): con la Dashboard (`layout-dashboard`) nessuna pagina la chiede. L'appendice C della specifica la nomina ancora fra le icone di navigazione: da aggiornare con `layout-dashboard` | Lo sprite `/icone/tutte.svg` mette insieme ogni file della cartella: un'icona che nessuno usa vi viaggia per niente |
| 2026-11-25 | Il commit 34fe5e9 del ramo `funzione/dashboard` ha all'inizio dell'oggetto un BOM (U+FEFF), entrato quando PowerShell ha passato il messaggio a git: si accetta così, sapendolo | Riscriverlo vorrebbe dire riscrivere la storia del ramo, che i passi del lavoro non possono fare; il testo è giusto, solo un carattere invisibile in testa |
+3 -2
View File
@@ -30,8 +30,9 @@ nome nel suggerimento):
post. Un file non ancora scaricato non ha tessera.
Filtri, ricerca e caricamento a finestre funzionano allo stesso modo nei due modi. Febe ricorda la scelta in questo
browser, una per la Libreria e una per le schede degli account (come il tema); in una finestra privata, o se il
browser non conserva nulla, si riparte da «Raggruppa i post».
browser, una per la Libreria e una per le schede degli account. A differenza del tema, che Febe salva e ritrova in
ogni browser, questa scelta resta solo nel browser in cui l'hai fatta: in un altro browser, in una finestra privata o
se il browser non conserva nulla, si riparte da «Raggruppa i post».
## Il visualizzatore
Binary file not shown.

After

Width:  |  Height:  |  Size: 686 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 203 KiB

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 170 KiB

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 KiB

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 82 KiB

+22 -14
View File
@@ -7,6 +7,7 @@ solo per l'interfaccia di Febe (§10.7).
| Schermata | Indirizzo | Mockup |
|---|---|---|
| `01-libreria.png` | `/libreria?tema=chiaro`, puntatore su una tessera | `docs/mockup/01-libreria.png` |
| `01-libreria-tutte-le-foto.png` | `/libreria?tema=chiaro`, «Tutte le foto» scelto (passo `tutte-le-foto.js`; presa il 25/11 da Windows) | `docs/mockup/01-libreria.png` (il mockup non ha l'interruttore, vedi sotto) |
| `02-visualizzatore.png` | `/libreria`, clic su un post con più file, seconda foto | `miniature/02-visualizzatore.png` |
| `03-account.png` | `/account?tema=chiaro` | `docs/mockup/03-account.png` |
| `03-account-telefono.png` | `/account`, 390 × 844 | (nessuno: tabella come elenco) |
@@ -17,8 +18,8 @@ solo per l'interfaccia di Febe (§10.7).
| `14-finestra-stretta.png` | `/libreria`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività, oggi Dashboard, al telefono) |
| `account-cronologia.png` | `/account/2/cronologia` | (nessuno) |
| `06-attivita.png` | `/attivita?scena=sessione&tema=chiaro` | `miniature/06-attivita.png` |
| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto (rifatta il 15/11 da Windows: c'è la riga «Ricerche di profili») | (nessuno: §7.4) |
| `06-attivita.png` | `/dashboard?scena=sessione&tema=chiaro` (Dashboard; rifatta il 25/11 da Windows) | `miniature/06-attivita.png` |
| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto (rifatta il 25/11 da Windows: c'è la riga «Ricerche di profili») | (nessuno: §7.4) |
| `07-limiti-e-comportamento.png` | `/impostazioni/limiti`, 1440 × 1470 (rifatta il 15/11 da Windows: riga «Ricerche di profili», 240 all'ora e 1.200 al giorno con «Prudente») | `miniature/07-limiti-e-comportamento.png` |
| `07-limiti-su-misura.png` | come sopra, un tetto cambiato: «Su misura» e barra di salvataggio attiva | (nessuno: §7.5) |
| `08-impostazioni-generali.png` | `/impostazioni/generali` | `docs/mockup/08-impostazioni-generali.png` |
@@ -29,11 +30,11 @@ solo per l'interfaccia di Febe (§10.7).
| `10-collegamento-windows.png` | come sopra con `veste=windows` | (nessuno: variante di §6.4) |
| `10-collegamento-collegato.png` | `/impostazioni/collegamento?veste=docker`, account collegato | (nessuno) |
| `10-browser.png` | `/browser?scena=fermo&veste=docker` | mockup 10 senza colonna dei passi |
| `11-attivita-fermo-tema-scuro.png` | `/attivita?scena=fermo&tema=scuro` | `miniature/11-attivita-fermo-tema-scuro.png` |
| `14-attivita-finestra-stretta.png` | `/attivita?scena=sessione`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
| `14-attivita-telefono.png` | `/attivita?scena=sessione`, 390 × 844 | parte destra di `miniature/14-finestra-stretta-e-telefono.png` |
| `14-attivita-finestra-stretta-normale.png` | `/attivita?scena=normale`, 860 × 900 | (come sopra, motore in ascolto) |
| `14-attivita-telefono-normale.png` | `/attivita?scena=normale`, 390 × 844 | (come sopra, motore in ascolto) |
| `11-attivita-fermo-tema-scuro.png` | `/dashboard?scena=fermo&tema=scuro` (rifatta il 25/11 da Windows) | `miniature/11-attivita-fermo-tema-scuro.png` |
| `14-attivita-finestra-stretta.png` | `/dashboard?scena=sessione`, 860 × 900 (rifatta il 25/11 da Windows) | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
| `14-attivita-telefono.png` | `/dashboard?scena=sessione`, 390 × 844 (rifatta il 25/11 da Windows) | parte destra di `miniature/14-finestra-stretta-e-telefono.png` |
| `14-attivita-finestra-stretta-normale.png` | `/dashboard?scena=normale`, 860 × 900 (rifatta il 25/11 da Windows) | (come sopra, motore in ascolto) |
| `14-attivita-telefono-normale.png` | `/dashboard?scena=normale`, 390 × 844 (rifatta il 25/11 da Windows) | (come sopra, motore in ascolto) |
| `impostazioni-notifiche.png` | `/impostazioni/notifiche` | (nessuno: §13.3) |
| `impostazioni-dati.png` | `/impostazioni/dati` | (nessuno: §8.2, §8.5) |
| `impostazioni-informazioni.png` | `/impostazioni/informazioni` | (nessuno) |
@@ -143,10 +144,10 @@ schermata del motore fermo si prende per prima, perché «Riprendi» resta spent
Attività è diventata la **Dashboard** (§7.9, §10.3 «Schermate della tappa D1»): `/dashboard`, prima voce della barra
laterale con un'icona sua (quattro riquadri), pagina iniziale (`/`, `/attivita` e la finestra di Windows portano lì).
Le schermate `06-attivita*`, `11-attivita-fermo-tema-scuro` e `14-attivita-*` della tabella sono della vecchia
pagina: **non sono state rifatte**; si rifanno con `/dashboard` al posto di `/attivita` (stesse scene e misure).
Confronto fatto il 25/11 a occhio sulla dimostrazione (1440 × 900, 860 × 900, 390 × 844, tema chiaro e scuro), non
con il programma delle schermate. Differenze dai mockup 06, 11 e 14 da cui la pagina è composta:
Le schermate `06-attivita*`, `11-attivita-fermo-tema-scuro` e `14-attivita-*` della tabella (i nomi restano quelli dei
mockup) sono state **rifatte il 25/11** con il programma delle schermate da Windows (Edge senza finestra), con
`/dashboard` e le stesse scene e misure, e messe accanto ai mockup 06, 11 e 14 da cui la pagina è composta.
Differenze:
- **In alto il cruscotto.** L'anteprima del browser è grande (420 × 236 px invece di 266 × 116) e sempre visibile, a
sinistra in un riquadro unico con accanto lo stato, che cosa sta facendo e i quattro tetti in una riga; nel mockup
@@ -164,6 +165,12 @@ con il programma delle schermate. Differenze dai mockup 06, 11 e 14 da cui la pa
- **Sotto i 1000 px** una colonna sola, con il cruscotto sopra (anteprima a tutta larghezza, poi stato e tetti in due
per due); al telefono l'anteprima è alta 196 px e i tre comandi del titolo restano icone.
- **Arresti e Avvisi** restano in fondo alla pagina come in Attività; «Diagnostica» resta nella riga del titolo.
- **Da sistemare, visto nelle schermate del 25/11** (non corretto in questa tornata):
- «Mostra tutta (N)» della coda sta sul bordo in basso a sinistra del riquadro, senza il margine interno delle righe.
- Nella striscia della giornata le sessioni sono segni corti di pochi pixel, non le barre a tutta altezza del mockup 06.
- A 860 × 900 l'anteprima prende tutta la larghezza (circa 900 × 300 px) e spinge la cronologia sotto il primo
schermo; la richiesta era una pagina compressa.
- Nella barra laterale le icone di Dashboard (`layout-dashboard`) e Libreria (`layout-grid`) si somigliano molto.
- **Dimostrazione.** Come per Attività l'anteprima compone tre immagini della libreria finta; righe, miniature e
numeri vengono dal mondo dimostrativo (alcune righe «Scaricato» della dimostrazione non hanno miniature perché nel
mondo finto i loro elementi non sono stati scoperti nel tempo di quella riga).
@@ -171,9 +178,10 @@ con il programma delle schermate. Differenze dai mockup 06, 11 e 14 da cui la pa
### «Raggruppa i post» / «Tutte le foto» (tappa D1, issue #59, dal 25 novembre 2026)
L'interruttore di §4.6 (§10.3 «Schermate della tappa D1») è composto dai mockup 01 e 12, che non lo hanno. Le
schermate `01-*` e `12-*` della tabella mostrano «Raggruppa i post», il predefinito, e non sono state rifatte; una
schermata con «Tutte le foto» non c'è ancora. **Non confrontato** con il programma delle schermate né nel browser di
prova: le prove dell'interfaccia (`LibraryModeInterfaceTests`) girano solo nella CI. Differenze:
schermate `01-libreria`, `01-*` e `12-*` mostrano «Raggruppa i post», il predefinito, e non sono state rifatte;
`01-libreria-tutte-le-foto.png` (presa il 25/11 con il programma delle schermate da Windows) mostra «Tutte le foto» ed
è stata messa accanto al mockup 01. Le prove dell'interfaccia (`LibraryModeInterfaceTests`) girano solo nella CI e qui
non sono state eseguite; la scheda account con «Tutte le foto» non ha una schermata. Differenze:
- **Controllo a due voci** (`.gruppo` dell'appendice B, come i controlli segmentati delle impostazioni) nella riga degli
strumenti, fra l'icona dell'elenco CSV e il cursore della grandezza nella Libreria, prima di «Seleziona» nella scheda
+2 -2
View File
@@ -94,7 +94,7 @@ public static class AlertEventCodes
/// </summary>
public static class AlertCatalog
{
/// <summary>Codes shown in the «Avvisi» list of Attività: the alerts and the failed deliveries.</summary>
/// <summary>Codes shown in the «Avvisi» list of the Dashboard: the alerts and the failed deliveries.</summary>
public static IReadOnlyList<string> Codes { get; } =
[
EngineEventCodes.ChallengeStop,
@@ -193,7 +193,7 @@ public static class AlertCatalog
/// <summary>
/// The engine's sentence without its first words when they repeat the title: «Instagram ha chiesto di rallentare
/// (segnale http-429). Ho chiuso…» becomes «Ho chiuso…» (the signal stays in the stops of Attività).
/// (segnale http-429). Ho chiuso…» becomes «Ho chiuso…» (the signal stays in the stops of the Dashboard).
/// </summary>
private static string WithoutTitle(string message, string title)
{
+1 -1
View File
@@ -43,7 +43,7 @@ public sealed record AlertServiceOptions
/// stops and resumes, backfills completed, unknown formats, suspended recipes) and checks the free space of the
/// library and the Data folder; each alert goes to the channels switched on in Impostazioni ▸ Notifiche (Windows
/// notification on the desktop, Telegram when token and chat are set). The red strip of the interface is not its
/// job: the engine snapshot always shows a stop, and every alert is a line of the «Avvisi» list in Attività.
/// job: the engine snapshot always shows a stop, and every alert is a line of the «Avvisi» list of the Dashboard.
/// <list type="bullet">
/// <item>Same kind and key within <see cref="AlertCatalog.MinimumInterval"/>: not sent again (the times are kept in the
/// settings, so a restart does not send it again either).</item>
@@ -75,11 +75,12 @@ public sealed record DownloadOptions
public int BatchSize { get; init; } = 200;
/// <summary>
/// «Cosa scaricare prima» never starves the later kinds (spec §6.5, §7.2): one file in this many is the one that has
/// waited longest, whatever its kind; the others follow the order. Every file in the queue becomes the longest
/// waiting sooner or later (new files are always younger), so every kind gets at least this share of the downloads
/// while it has files waiting, even when the daily data budget ends each day before the queue does. 0 or 1: the
/// order alone.
/// «Cosa scaricare prima» never makes a file wait for ever (spec §6.5, §7.2): one file in this many is the one that
/// has waited longest, whatever its kind; the others follow the order. Every file in the queue becomes the longest
/// waiting sooner or later (new files are always younger), so every file is downloaded in the end, even when the
/// daily data budget ends each day before the queue does. It is not a share per kind: the place goes to the oldest
/// file of the whole queue, so a kind found after an older backlog of another kind waits until that backlog is done
/// (taggati found after thousands of older posts come after them). 0 or 1: the order alone.
/// </summary>
public int LongestWaitingShare { get; init; } = 8;
@@ -437,7 +437,7 @@ public sealed partial class RecipeRunner
run.Finished = true;
if (walk.IsGrid)
{
// «Storico completato» in Attività, and the new state of the account, are the engine's: one line per
// «Storico completato» in the Dashboard, and the new state of the account, are the engine's: one line per
// history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished).
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false);
+1 -1
View File
@@ -66,7 +66,7 @@ public sealed class EngineHost : IAsyncDisposable
public EngineServices Services => _s;
/// <summary>What the interface shows of the engine (Attività, sidebar, account settings panel).</summary>
/// <summary>What the interface shows of the engine (Dashboard, sidebar, account settings panel).</summary>
public IEngineMonitor Monitor { get; }
/// <summary>Recipes suspended after repeated unrecognized formats, with when.</summary>
+2 -2
View File
@@ -1227,7 +1227,7 @@ internal sealed class SessionComposer
/// <summary>
/// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one
/// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their
/// «storico completato» line of the Dashboard, which is also the alert (spec §13.3). The recipes write no line of their
/// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account
/// as it is now.
/// </summary>
@@ -1292,7 +1292,7 @@ internal sealed class SessionComposer
await _s.Events.WriteAsync(
EventSeverity.Error,
EngineEventCodes.RecipeSuspended,
$"«{ItalianText.Capitalize(RecipeName(kind))}» è sospeso dopo {ItalianText.Number(threshold)} problemi di fila: Instagram potrebbe essere cambiato. Serve un campione nuovo con la modalità sonda; poi si riattiva da Attività.",
$"«{ItalianText.Capitalize(RecipeName(kind))}» è sospeso dopo {ItalianText.Number(threshold)} problemi di fila: Instagram potrebbe essere cambiato. Serve un campione nuovo con la modalità sonda; poi si riattiva dalla Dashboard («Riattiva»).",
account?.Id,
ct: ct).ConfigureAwait(false);
}
+1 -1
View File
@@ -17,7 +17,7 @@ public interface ITaskStore
/// <summary>Pending tasks due at <paramref name="now"/>: highest priority first, then earliest due, then oldest.</summary>
Task<IReadOnlyList<EngineTask>> PeekDueAsync(DateTimeOffset now, int limit, CancellationToken ct = default);
/// <summary>Pending tasks by due time (the queue shown in Attività, «verso le»).</summary>
/// <summary>Pending tasks by due time (the queue shown in the Dashboard, «verso le»).</summary>
Task<IReadOnlyList<EngineTask>> ListPendingAsync(int limit, CancellationToken ct = default);
/// <summary>Pending → Running, atomically. False if the task was not pending any more.</summary>
+3 -7
View File
@@ -81,15 +81,11 @@ public interface IEntryStore
Task<LibraryTotals> GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default);
/// <summary>
/// Files of the entries of the filter that are in the library (downloaded or imported): the tiles of
/// «Tutte le foto». With «Foto» and «Video» only the files of that kind.
/// </summary>
Task<int> CountLibraryFilesAsync(LibraryFilter filter, CancellationToken ct = default);
/// <summary>
/// Entries (or, with <see cref="MosaicMode.Files"/>, files) per local calendar day in Alberto's zone, newest day
/// first. A day without files is left out in that mode.
/// first. A day without files is left out in that mode. In that mode the files are those in the library
/// (downloaded or imported), the tiles of «Tutte le foto», with «Foto» and «Video» only the files of that kind; their
/// total is the sum of the days (one pass over the files, not a second count).
/// </summary>
Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default);
+19 -33
View File
@@ -323,7 +323,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
c =>
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var where = BuildWhere(c, command, filter, aggregate: true);
command.CommandText = $"SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entry e WHERE {where}";
using var r = command.ExecuteReader();
r.Read();
@@ -332,34 +332,6 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
ct);
}
public Task<int> CountLibraryFilesAsync(LibraryFilter filter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
return db.ReadAsync(
c =>
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, EntriesOfFiles(filter));
var counts = FileCounts(c, filter);
if (counts is null)
{
command.CommandText = $"SELECT COALESCE(SUM({FilesOfEntry(filter)}), 0) FROM entry e WHERE {where}";
return (int)command.ScalarInt64();
}
command.CommandText = $"SELECT e.id FROM entry e WHERE {where}";
var total = 0;
using var r = command.ExecuteReader();
while (r.Read())
{
total += counts.GetValueOrDefault(r.GetInt64(0));
}
return total;
},
ct);
}
public Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
@@ -371,7 +343,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var files = mode == MosaicMode.Files;
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter);
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true);
var counts = files ? FileCounts(c, filter) : null;
var perEntry = files && counts is null;
command.CommandText = !files
@@ -758,8 +730,22 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
}
/// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter)
/// <param name="aggregate">
/// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and
/// «Video» then test the key of each post, on a covering index, against one list of the entries that have such
/// files, read once from ix_media_entry_files (under two tenths of a second over 200,000 entries), instead of an
/// EXISTS per post (over a second: each post needs its table row). A window keeps the EXISTS: it stops after a few
/// hundred posts in index order.
/// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two.
/// </param>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false)
{
var byList = aggregate && filter.AccountIds is not { Count: > 0 };
// The unary + on kind and key keeps SQLite on a covering index of entry (kind, state and account in the index):
// looking up each entry of the list by key would read its table row, 0.85 s for «Foto» over 200,000 entries.
string FilesOfKind(string kind) => byList
? $"+e.kind = 'Post' AND +e.id IN (SELECT mk.entry_id FROM media mk WHERE mk.kind = '{kind}')"
: $"e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = '{kind}')";
var parts = new List<string>();
var states = filter.States is { Count: > 0 } s ? s : EntryStateRules.Visible;
// The unary + keeps SQLite from using the state and kind indexes for these broad terms: the keyset scan of the
@@ -772,8 +758,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// Like «Tutto», a broad term: on the kind index every post would need its table row for the state (most of
// the library); the publication index already holds kind and state.
LibraryKindFilter.Posts => "+e.kind = 'Post'",
LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')",
LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')",
LibraryKindFilter.Photos => FilesOfKind("Photo"),
LibraryKindFilter.Videos => FilesOfKind("Video"),
LibraryKindFilter.Stories => "e.kind = 'Story'",
LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))",
LibraryKindFilter.Tagged => "e.kind = 'Tagged'",
+1 -1
View File
@@ -15,7 +15,7 @@ using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// What the Attività page needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the
/// What the Dashboard (before: Attività) needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the
/// stops, the still frame of the browser, the probable duplicates waiting for Alberto, the diagnostic report.
/// </summary>
public static class ActivityApi
+1 -1
View File
@@ -285,7 +285,7 @@ public sealed record ProfileSearchHitDto(string InstagramId, string Username, st
/// <param name="State">"connected", "notConnected", "verification", "disconnected".</param>
public sealed record ConnectionDto(string State, string? Username, string? DisplayName, string? Avatar);
/// <summary>The engine for the sidebar, the stop strip and the Attività page.</summary>
/// <summary>The engine for the sidebar, the stop strip and the Dashboard.</summary>
public sealed record EngineDto(long Now, EngineSnapshot Snapshot, ConnectionDto Connection, bool CanResume);
public sealed record ResumeDto(bool Resumed, string Message);
+2 -1
View File
@@ -33,8 +33,9 @@ public static class LibraryApi
var filter = ApiMapping.Filter(context.Request.Query, zone);
var mode = ApiMapping.Mode(context.Request.Query["mode"]);
var totals = await storage.Entries.GetLibraryTotalsAsync(filter, ct).ConfigureAwait(false);
int? files = mode == MosaicMode.Files ? await storage.Entries.CountLibraryFilesAsync(filter, ct).ConfigureAwait(false) : null;
var days = await storage.Entries.CountLibraryByDayAsync(filter, zone, mode, ct).ConfigureAwait(false);
// The files of «Tutte le foto» are the sum of their days: one pass over the media table per request.
int? files = mode == MosaicMode.Files ? days.Sum(d => d.Count) : null;
var list = days.Select(d =>
{
var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone);
+2 -2
View File
@@ -1,6 +1,6 @@
namespace Febe.Web.Api;
// JSON shapes of the second part of the interface (Attività, Impostazioni, Importa, Collegamento, Browser, doppioni).
// JSON shapes of the second part of the interface (Dashboard, Impostazioni, Importa, Collegamento, Browser, doppioni).
// Same conventions as Dtos.cs: English camelCase names, Italian texts, times as Unix milliseconds or LocalTimeDto.
// ---------------------------------------------------------------- connection (PROTOCOLLO.md)
@@ -64,7 +64,7 @@ public sealed record IncidentDto(
public sealed record IncidentListDto(IReadOnlyList<IncidentDto> Items, int ThrottlesLastWeek, string? Advice);
/// <summary>
/// A line of the «Avvisi» list of Attività (spec §13.3): an alert or a failed delivery. <see cref="Kind"/>:
/// A line of the «Avvisi» list of the Dashboard (spec §13.3): an alert or a failed delivery. <see cref="Kind"/>:
/// verification, disconnection, throttleStop, throttleEnd, backfillDone, unknownFormat, recipeSuspended, diskLow,
/// deliveryFailed. <see cref="Level"/>: error, warning, success, info.
/// </summary>
+1 -1
View File
@@ -497,7 +497,7 @@ public static class DemoSeeder
withNews == 0 ? "Giro dei profili che segui: nessuna novità" : $"Giro dei profili che segui: {withNews} contenuti nuovi", null));
}
// The alerts of the last days (Attività, «Avvisi»): the throttle of three days ago (as DemoIncidentHistory) and
// The alerts of the last days (Dashboard, «Avvisi»): the throttle of three days ago (as DemoIncidentHistory) and
// its end, and the backfills completed in the last two weeks.
var throttle = LocalCalendar.StartOfDay(today.AddDays(-3), zone) + TimeSpan.FromHours(18.4);
var throttleEnd = throttle + TimeSpan.FromHours(1);
+2 -2
View File
@@ -1,13 +1,13 @@
namespace Febe.Web.Engine;
/// <summary>A still frame of Febe's browser for the Attività page (mockup 06: one frame every few seconds, not a video).</summary>
/// <summary>A still frame of Febe's browser for the Dashboard (mockup 06: one frame every few seconds, not a video).</summary>
/// <param name="Jpeg">The frame, JPEG encoded.</param>
/// <param name="Url">Address of the page, without query string.</param>
/// <param name="At">When the frame was taken.</param>
public sealed record BrowserFrame(byte[] Jpeg, string? Url, DateTimeOffset At);
/// <summary>
/// The latest frame of Febe's browser, for the preview of the Attività page. Implemented by the composition over the
/// The latest frame of Febe's browser, for the preview of the Dashboard. Implemented by the composition over the
/// browser host (Docker: the screencast of the remote view; Windows: the WebView2). Taking frames is never an action
/// toward the site: it reads what the browser already shows.
/// </summary>
+1 -1
View File
@@ -3,7 +3,7 @@ using Febe.Core.Collection.Diagnostics;
namespace Febe.Web.Engine;
/// <summary>
/// The traces of the diagnostic report (issue #39) for «Esporta il rapporto di diagnostica» in Attività: the finished
/// The traces of the diagnostic report (issue #39) for «Esporta il rapporto di diagnostica» in the Dashboard: the finished
/// ones of the last two weeks and the ones in progress, oldest first. They hold no data value
/// (<see cref="SessionTrace"/>).
/// </summary>
+1 -1
View File
@@ -100,7 +100,7 @@ public sealed class OfflineEngine(IClock clock) : IEngineMonitor, IEngineControl
/// <summary>Pieces for building snapshots outside <see cref="EngineMonitor"/> (offline engine, demo).</summary>
public static class SnapshotParts
{
/// <summary>The four main budgets in the order of the Attività page.</summary>
/// <summary>The four main budgets in the order of the Dashboard.</summary>
public static readonly ActionKind[] Main = [ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.DataDownload];
/// <summary>Every category in the order of the table of spec §7.5.</summary>
+1 -1
View File
@@ -3,7 +3,7 @@ using Febe.Core.Storage;
namespace Febe.Web.Engine;
/// <summary>The stops of the last days for the Attività page (spec §7.6: «nella cronologia della pagina Attività»).</summary>
/// <summary>The stops of the last days for the Dashboard (spec §7.6 still says «nella cronologia della pagina Attività», the page before it).</summary>
public interface IIncidentHistory
{
/// <summary>Incidents that started in [from, to), newest first.</summary>
+8 -3
View File
@@ -107,8 +107,8 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| `GET /api/engine`, `POST /api/engine/pause`, `/resume` | Istantanea del motore, collegamento, `canResume` |
| `POST /api/browser/show`, `/api/browser/used` | «Apri il browser» (desktop), uso del browser |
| `GET /api/eventi` | SSE: `motore` (istantanea, al massimo ogni 300 ms, comunque ogni 60 s), `libreria` (al massimo ogni 1,5 s), commento ogni 25 s |
| `GET /api/library/days` | Totali e giorni con conteggio e cursore (per la finestra del mosaico) |
| `GET /api/library?cursor=&direction=older\|newer&limit=` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q` |
| `GET /api/library/days?mode=grouped\|files` | Totali (sempre elementi: `entries`, `accounts`) e giorni con conteggio e cursore (per la finestra del mosaico); con `mode=files` («Tutte le foto») i giorni contano i file presenti in libreria e `files` è la loro somma (altrimenti `null`). Un altro valore di `mode` dà 400. Stessi filtri di `/api/library` |
| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 |
| `GET /api/library/tiles?ids=` | Tessere per chiave |
| `GET /api/thumbnails/{chiave}`, `GET /api/media/{id}/file[?download=1]` | Miniature (immutabili) e file (con range) |
| `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) |
@@ -210,7 +210,12 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da
Pezzi riusabili delle pagine: `pages/mosaic.js` (`Mosaic`: righe giustificate o griglia 9:16, finestre per giorno,
virtualizzazione, selezione, nuovi elementi in cima senza spostare la vista), `pages/viewer.js` (`openViewer`),
`pages/accounts.js` (`checkNow`, `removeAccount`, `accountMenu`, `stateLine`), `pages/library.js` (`confirmDelete`).
`pages/accounts.js` (`checkNow`, `removeAccount`, `accountMenu`, `stateLine`), `pages/library.js` (`confirmDelete`,
`selectionBar`: la barra della selezione, che con «Tutte le foto» dice file ed elementi), `pages/mosaic.js` anche
`storedMode` e `modeSwitch` («Raggruppa i post» / «Tutte le foto», ricordato per pagina nella memoria locale del
browser), `pages/download-order.js` (`orderEditor`: l'elenco da trascinare di «Cosa scaricare prima», con Su/Giù e i
tipi spenti attenuati, usato da Limiti e comportamento e dalla scheda account; `kindName`, `orderOrDefault`,
`DEFAULT_ORDER`).
### Testi, stile, accessibilità
-3
View File
@@ -1,3 +0,0 @@
<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="3 12 7 12 9.5 6 14 18 16.5 12 21 12"/>
</svg>

Before

Width:  |  Height:  |  Size: 228 B

+1 -1
View File
@@ -1,5 +1,5 @@
// The engine and the library as seen by the pages: one event stream (/api/eventi) for the whole interface.
// «motore» carries the snapshot (sidebar, stop strip, Attività); «libreria» says the library changed.
// «motore» carries the snapshot (sidebar, stop strip, Dashboard); «libreria» says the library changed.
import { api, eventsUrl } from './api.js';
import { caps } from './context.js';
+2 -1
View File
@@ -384,7 +384,8 @@ function settingsTab(page, detail) {
label: t('impAccount.ordineScelta'),
});
const orderChoice = segmented({
label: t('impAccount.ordineScelta'),
// The list is «Ordine dei tipi per questo account»; the two-way choice has the name of the section.
label: t('impAccount.ordine'),
value: Array.isArray(form.downloadOrder) && form.downloadOrder.length ? 'own' : 'general',
options: [{ value: 'general', label: t('impAccount.ordineGenerale') }, { value: 'own', label: t('impAccount.ordineSuo') }],
onchange: (v) => {
@@ -53,13 +53,13 @@ export function orderEditor({ read, write, changed, off = () => false, label })
const order = read();
fill(list, order.map((kind, i) => {
const name = kindName(kind);
const spento = off(kind);
const row = h(spento ? 'li.riga-ordine.spenta' : 'li.riga-ordine', { draggable: 'true', dataset: { tipo: kind } },
const switchedOff = off(kind);
const row = h(switchedOff ? 'li.riga-ordine.spenta' : '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),
spento ? h('span.muto.piccolo', t('impostazioni.limiti.ordineSpento')) : null,
kind === 'storie' && i > 0 && !spento ? h('span.muto.piccolo', icon('clock', 'xs'), ' ', t('impostazioni.limiti.ordineStorie')) : null,
switchedOff ? h('span.muto.piccolo', t('impostazioni.limiti.ordineSpento')) : null,
kind === 'storie' && i > 0 && !switchedOff ? 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'),
+13 -4
View File
@@ -13,24 +13,33 @@ import { t, dayName, duration, capitalize } from '../core/text.js';
import { avatar, segmented } from '../core/ui.js';
/**
* «Raggruppa i post» or «Tutte le foto» of a page ('libreria', or 'account' for every account), remembered in this
* browser like the theme (spec §4.6). Storage that is missing, blocked or holds anything else means grouped.
* «Raggruppa i post» or «Tutte le foto» of a page ('libreria', or 'account' for every account), kept only in the
* local storage of this browser (spec §4.6): unlike the theme, Febe does not save it, so another browser starts
* grouped. Storage that is missing, blocked or holds anything else means grouped.
*/
export function storedMode(page) {
return local.get(`mosaico.${page}`, 'grouped') === 'files' ? 'files' : 'grouped';
}
/** The two-voice switch of the tools row; onchange(mode) after the choice is remembered. compact: icons only sooner. */
/**
* The two-voice switch of the tools row; onchange(mode) after the choice is remembered, and only when the mode
* changes: the voice already chosen does nothing (the mosaic, its place and the selection stay). compact: icons only
* sooner.
*/
export function modeSwitch(page, onchange, { compact = false } = {}) {
const labels = { grouped: t('libreria.modi.grouped'), files: t('libreria.modi.files') };
// The mode shown, kept here: without browser storage storedMode() always says grouped.
let current = storedMode(page);
const group = segmented({
label: t('libreria.modi.etichetta'),
value: storedMode(page),
value: current,
options: [
{ value: 'grouped', icon: 'layers', label: h('span.voce', labels.grouped) },
{ value: 'files', icon: 'layout-grid', label: h('span.voce', labels.files) },
],
onchange: (value) => {
if (value === current) return;
current = value;
local.set(`mosaico.${page}`, value);
onchange(value);
},
+13 -2
View File
@@ -112,6 +112,11 @@ export function openViewer({ tile, source, origin, onDeleted }) {
const at = mediaId == null ? -1 : entry.media.findIndex((m) => m.id === mediaId);
if (at >= 0) fileIndex = at;
else fileIndex = index < 0 ? entry.media.length - 1 : Math.min(index, entry.media.length - 1);
if (files && at < 0) {
// Entered from an edge without a file named: the first (or last) file that is a tile.
const tiles = entry.media.map((m, i) => (source.has(m.id) ? i : -1)).filter((i) => i >= 0);
if (tiles.length) fileIndex = index < 0 ? tiles[tiles.length - 1] : tiles[0];
}
draw();
} catch (error) {
showError(error);
@@ -120,7 +125,10 @@ export function openViewer({ tile, source, origin, onDeleted }) {
async function step(delta) {
if (!entry) return;
const target = fileIndex + delta;
let target = fileIndex + delta;
// With «Tutte le foto» the arrows follow the tiles: the files the mosaic does not show (the photos of a post under
// «Video», the videos under «Foto», a file not in the library) are passed over, as the mosaic passes over them.
if (files) while (target >= 0 && target < entry.media.length && !source.has(entry.media[target].id)) target += delta;
if (target >= 0 && target < entry.media.length) {
fileIndex = target;
drawFile();
@@ -149,7 +157,10 @@ export function openViewer({ tile, source, origin, onDeleted }) {
}
function drawWhere() {
const key = source && source.position ? keyAt(0) : null;
// With «Tutte le foto» the place is that of the file on screen; a file that is not a tile (chosen in the series
// strip) has none, and the header says only where the viewer was opened.
const current = files && entry.media[fileIndex];
const key = !source || !source.position ? null : !files ? keyAt(0) : current && source.has(current.id) ? current.id : null;
if (key != null) {
const p = source.position(key);
where.textContent = p.index ? t(files ? 'vis.doveFile' : 'vis.dove', { origine: origin, n: number(p.index), totale: number(p.total) }) : origin;
@@ -175,6 +175,8 @@ public sealed class AlertServiceTests
Assert.IsTrue(bed.Outcomes.Any(o => o.Alert.Kind == AlertKind.UnknownFormat && o.Kind == AlertOutcomeKind.Repeated));
var suspended = texts.Single(t => t.StartsWith("Febe · Ricetta sospesa\n", StringComparison.Ordinal));
StringAssert.Contains(suspended, "modalità sonda");
StringAssert.Contains(suspended, "si riattiva dalla Dashboard («Riattiva»)", "la pagina si chiama Dashboard (tappa D1)");
Assert.IsFalse(suspended.Contains("Attività", StringComparison.Ordinal), suspended);
}
[TestMethod]
+40 -7
View File
@@ -97,10 +97,10 @@ public sealed class LibraryFilesTests
Assert.HasCount(5, photos.Tiles);
Assert.IsTrue(photos.Tiles.All(t => t.CoverKind == MediaKind.Photo));
Assert.AreEqual(7, await db.Entries.CountLibraryFilesAsync(new LibraryFilter()));
Assert.AreEqual(1, await db.Entries.CountLibraryFilesAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }));
Assert.AreEqual(5, await db.Entries.CountLibraryFilesAsync(new LibraryFilter { Kind = LibraryKindFilter.Photos }));
Assert.AreEqual(1, await db.Entries.CountLibraryFilesAsync(new LibraryFilter { Kind = LibraryKindFilter.Stories }));
Assert.AreEqual(7, await FileTotalAsync(db, new LibraryFilter()));
Assert.AreEqual(1, await FileTotalAsync(db, new LibraryFilter { Kind = LibraryKindFilter.Videos }));
Assert.AreEqual(5, await FileTotalAsync(db, new LibraryFilter { Kind = LibraryKindFilter.Photos }));
Assert.AreEqual(1, await FileTotalAsync(db, new LibraryFilter { Kind = LibraryKindFilter.Stories }));
Assert.AreEqual(new LibraryTotals(4, 1), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter()), "the totals stay entries");
var days = await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files);
@@ -113,11 +113,11 @@ public sealed class LibraryFilesTests
var other = await db.Accounts.AddAsync(Make.Account("luca.demo"));
await db.Entries.AddAsync(Make.Entry(other.Id, "o", new DateTimeOffset(2026, 10, 13, 8, 0, 0, TimeSpan.Zero)), [Make.Stored(Make.Photo(), Make.Sha(41), "o/o.jpg")]);
var mine = new LibraryFilter { AccountIds = [accountId] };
Assert.AreEqual(7, await db.Entries.CountLibraryFilesAsync(mine));
Assert.AreEqual(8, await db.Entries.CountLibraryFilesAsync(new LibraryFilter()));
Assert.AreEqual(7, await FileTotalAsync(db, mine));
Assert.AreEqual(8, await FileTotalAsync(db, new LibraryFilter()));
CollectionAssert.AreEqual(days.ToArray(), (await db.Entries.CountLibraryByDayAsync(mine, TestZones.Rome, MosaicMode.Files)).ToArray());
Assert.AreEqual(8, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files)).Sum(d => d.Count));
Assert.AreEqual(1, await db.Entries.CountLibraryFilesAsync(mine with { Kind = LibraryKindFilter.Videos }));
Assert.AreEqual(1, await FileTotalAsync(db, mine with { Kind = LibraryKindFilter.Videos }));
// A day whose files are all of another kind has no row in «Video».
var videoDays = await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files);
@@ -129,8 +129,41 @@ public sealed class LibraryFilesTests
Assert.AreEqual(new DateOnly(2026, 10, 12), LocalCalendar.Today(fromDay.Tiles.Single().PublishedAt, TestZones.Rome));
}
[TestMethod]
public async Task GroupedPhotoAndVideoCountsAgreeWithTheirWindowsWithAndWithoutAccounts()
{
// The counts of the whole library read one list of the entries with such files, those of an account an EXISTS
// per post, the windows always the EXISTS: the same entries every way.
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var (carousel, single, partial, _) = await FillAsync(db);
var accountId = (await db.Entries.GetAsync(carousel))!.AccountId;
var other = await db.Accounts.AddAsync(Make.Account("luca.demo"));
await db.Entries.AddAsync(Make.Entry(other.Id, "v", new DateTimeOffset(2026, 10, 11, 8, 0, 0, TimeSpan.Zero)), [Make.Stored(Make.Video(), Make.Sha(51), "o/v.mp4")]);
foreach (var (kind, mine, everyone) in new[]
{
(LibraryKindFilter.Videos, new[] { carousel }, 2),
(LibraryKindFilter.Photos, new[] { carousel, partial, single }, 3),
})
{
var all = new LibraryFilter { Kind = kind };
var own = all with { AccountIds = [accountId] };
Assert.AreEqual(new LibraryTotals(everyone, kind == LibraryKindFilter.Videos ? 2 : 1), await db.Entries.GetLibraryTotalsAsync(all), $"{kind}");
Assert.AreEqual(everyone, (await db.Entries.CountLibraryByDayAsync(all, TestZones.Rome)).Sum(d => d.Count));
Assert.AreEqual(everyone, (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = all })).Tiles.Count);
Assert.AreEqual(new LibraryTotals(mine.Length, 1), await db.Entries.GetLibraryTotalsAsync(own), $"{kind} di un account");
Assert.AreEqual(mine.Length, (await db.Entries.CountLibraryByDayAsync(own, TestZones.Rome)).Sum(d => d.Count));
CollectionAssert.AreEquivalent(mine, (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = own })).Tiles.Select(t => t.EntryId).ToArray());
}
}
private static string Key(LibraryTile tile) => $"{tile.EntryId}.{tile.FilePosition}";
/// <summary>The files of «Tutte le foto» of a filter: the sum of its days, as /api/library/days gives it.</summary>
private static async Task<int> FileTotalAsync(FebeDatabase db, LibraryFilter filter) =>
(await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome, MosaicMode.Files)).Sum(d => d.Count);
/// <summary>
/// A story (13 Oct, 12:00), a carousel of photo, video, photo (13 Oct, 10:00), a post with its second file still to
/// download (13 Oct, 9:00) and a single photo (12 Oct, 9:00), all of one account.
+14 -4
View File
@@ -22,6 +22,9 @@ public sealed class LibraryScaleTests
private const double IndexBoundMs = 250;
private const double AggregateBoundMs = 1500;
// «Foto» and «Video» over the whole library: 60-180 ms measured; an EXISTS per post took 1.3-1.6 s and must fail.
private const double FilteredAggregateBoundMs = 600;
public TestContext TestContext { get; set; } = null!;
[TestMethod]
@@ -127,12 +130,19 @@ public sealed class LibraryScaleTests
await Measure("tutte le foto: filtro Video", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } }));
await Measure("tutte le foto: un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]] } }));
await Measure("tutte le foto: ricerca comune", AggregateBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Search = "caffe" } }));
var fileCount = await Measure("tutte le foto: totale dei file", AggregateBoundMs, () => db.Entries.CountLibraryFilesAsync(new LibraryFilter()));
Assert.AreEqual(Entries + (Entries / 5), fileCount);
// The days give the total of the files too (/api/library/days): one pass over the media table per request.
var fileDays = await Measure("tutte le foto: conteggi per giorno", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files));
Assert.AreEqual(fileCount, fileDays.Sum(d => d.Count));
Assert.AreEqual(Entries + (Entries / 5), fileDays.Sum(d => d.Count));
var accountFiles = await Measure("tutte le foto: conteggi di un account", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]] }, TestZones.Rome, MosaicMode.Files));
Assert.AreEqual(await db.Entries.CountLibraryFilesAsync(new LibraryFilter { AccountIds = [accountIds[3]] }, ct), accountFiles.Sum(d => d.Count));
Assert.AreEqual(Enumerable.Range(0, Entries).Where(n => n % Accounts == 3).Sum(n => n % 5 == 0 ? 2 : 1), accountFiles.Sum(d => d.Count));
// «Foto» and «Video» in the grouped mosaic: the totals and the days of a whole library must not pay an EXISTS
// per post (over a second); a list of the entries with such files keeps them near a tenth of a second.
var videoTotals = await Measure("totali del filtro Video", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }));
var videoDays = await Measure("conteggi per giorno del filtro Video", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome));
Assert.AreEqual(videoTotals.Entries, videoDays.Sum(d => d.Count));
Assert.AreEqual(Enumerable.Range(0, Entries).Count(n => n % 10 >= 4 && n % 7 == 0), videoTotals.Entries);
var photoTotals = await Measure("totali del filtro Foto", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Kind = LibraryKindFilter.Photos }));
Assert.AreEqual(Enumerable.Range(0, Entries).Count(n => n % 10 >= 4 && (n % 7 != 0 || n % 5 == 0)), photoTotals.Entries);
await Measure("scheda account: Post", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } }));
await Measure("scheda account: Post, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } }));
await Measure("scheda account: conteggi dei Post", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts }, TestZones.Rome));
@@ -200,6 +200,40 @@ public sealed class DownloadOrderTests
Assert.IsLessThanOrEqualTo(20, rounds, $"i taggati sono arrivati in {rounds} giri");
}
[TestMethod]
public void TheReservedPlaceGoesToTheOldestFileOfTheQueueNotToEachKindInTurn()
{
// A new account: 40 posts of the backfill found first, then 5 tagged posts, and 7 new posts every round. The
// share is not a minimum per kind: while older posts wait, their kind takes the reserved place too, and the
// tagged posts come only once that backlog is done. What holds is that no file waits for ever.
var waiting = Enumerable.Range(1, 40).Select(i => Pending(i, EntryKind.Post)).ToList();
waiting.AddRange(Enumerable.Range(100, 5).Select(i => Pending(i, EntryKind.Tagged)));
var next = 1000L;
var taggedByRound = new List<int>();
while (waiting.Any(p => p.Kind == EntryKind.Tagged) && taggedByRound.Count < 100)
{
for (var i = 0; i < 7; i++)
{
waiting.Add(Pending(next++, EntryKind.Post));
}
var ordered = waiting.OrderBy(p => p.Kind == EntryKind.Post ? 0 : 1).ThenBy(p => p.Media.EntryId).ToList();
var longest = waiting.OrderBy(p => p.Media.EntryId).ToList();
var batch = DownloadQueue.ComposeBatch(ordered, longest, 8, 8);
var oldest = longest.First(p => !batch.Take(7).Contains(p));
Assert.AreSame(oldest, batch[7], "il posto riservato va al file che aspetta da più tempo, di qualunque tipo");
taggedByRound.Add(batch.Count(p => p.Kind == EntryKind.Tagged));
foreach (var done in batch)
{
waiting.Remove(done);
}
}
CollectionAssert.AreEqual(new[] { 0, 0, 0, 0, 0 }, taggedByRound.Take(5).ToArray(), "finché i post più vecchi aspettano, i taggati non hanno un posto loro");
Assert.AreEqual(5, taggedByRound.Sum(), "poi arrivano tutti");
Assert.HasCount(10, taggedByRound, "uno per giro, nel posto riservato");
}
[TestMethod]
public async Task TheOrderWeighsTheVisitsAfterTheSweepWithoutMakingThemFixed()
{
@@ -66,6 +66,41 @@ public sealed class LibraryModeInterfaceTests
Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), "le viste degli account hanno la loro scelta");
}
[TestMethod]
public async Task UnderVideoTheArrowsFollowTheTilesAndTheChosenVoiceChangesNothing()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("modo-video-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
await ui.OpenAsync(new Uri(demo.Address, "/libreria?tipo=video"));
await ui.WaitAsync($"{Switch} !== null && document.querySelector('.mosaico .tess') !== null", "Libreria con «Video»");
await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()");
// A video that is the second file of its post (the first is a photo, no tile under «Video»), not the first tile.
const string Second = "[...document.querySelectorAll('.mosaico .tess')].slice(1).find((t) => /^2\\/\\d+$/.test(t.querySelector('.segno span')?.textContent || ''))";
await ui.WaitAsync($"({Second}) !== undefined", "un video in seconda posizione " + ui.Report());
// Clicking the voice already chosen keeps the mosaic, its place and the selection.
await ui.EvalAsync("document.querySelector('.mosaico').dataset.prova = 'stesso'");
await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()");
Assert.AreEqual("stesso", (await ui.EvalAsync("document.querySelector('.mosaico')?.dataset.prova || ''")).GetString(), "«Tutte le foto» di nuovo non ridisegna il mosaico");
await ui.EvalAsync($"({Second}).click()");
await ui.WaitAsync("document.querySelector('.vis .scena video') !== null && /file/.test(document.querySelector('.vis .dove').textContent)", "visualizzatore sul video");
const string Index = "Number((document.querySelector('.vis .dove').textContent.match(/file ([\\d.]+)/) || [])[1]?.replace(/\\./g, '') || 0)";
var at = (await ui.EvalAsync(Index)).GetInt32();
Assert.IsGreaterThan(1, at, ui.Report());
// Left: the photo before it is not a tile, so the viewer goes to the tile before, a video of another post.
await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true }))");
await ui.WaitAsync($"{Index} === {at - 1}", "la freccia va alla tessera precedente");
await ui.WaitAsync("document.querySelector('.vis .scena video') !== null", "di nuovo un video, mai la foto filtrata");
await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))");
await ui.WaitAsync($"{Index} === {at}", "e torna");
Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis .scena video') !== null")).GetBoolean());
}
[TestMethod]
public async Task WithoutTheBrowserStorageTheMosaicIsGrouped()
{
+10 -8
View File
@@ -13,6 +13,7 @@ internal static class Shots
public static IReadOnlyList<Shot> All { get; } =
[
new("/libreria?tema=chiaro", "01-libreria.png", Step: "puntatore.js"),
new("/libreria?tema=chiaro", "01-libreria-tutte-le-foto.png", Step: "tutte-le-foto.js"),
new("/libreria?tema=chiaro", "02-visualizzatore.png", Step: "visualizzatore.js"),
new("/account?tema=chiaro", "03-account.png"),
new("/account?tema=chiaro", "03-account-telefono.png", 390, 844),
@@ -24,14 +25,15 @@ internal static class Shots
new("/libreria?tema=chiaro", "14-telefono.png", 390, 844),
new("/account/2/cronologia?tema=chiaro", "account-cronologia.png"),
// Part 2: Attività, Impostazioni, Collegamento, Importa, doppioni, primo avvio, errore di configurazione.
new("/attivita?scena=fermo&tema=scuro", "11-attivita-fermo-tema-scuro.png"),
new("/attivita?scena=sessione&tema=chiaro", "06-attivita.png"),
new("/attivita?scena=sessione&tema=chiaro", "06-attivita-tutti-i-tetti.png", Step: "tutti-tetti.js"),
new("/attivita?scena=sessione&tema=chiaro", "14-attivita-finestra-stretta.png", 860, 900),
new("/attivita?scena=sessione&tema=chiaro", "14-attivita-telefono.png", 390, 844),
new("/attivita?scena=normale&tema=chiaro", "14-attivita-finestra-stretta-normale.png", 860, 900),
new("/attivita?scena=normale&tema=chiaro", "14-attivita-telefono-normale.png", 390, 844),
// Part 2: Dashboard (once Attività: the files keep the names of mockups 06, 11 and 14), Impostazioni, Collegamento,
// Importa, doppioni, primo avvio, errore di configurazione.
new("/dashboard?scena=fermo&tema=scuro", "11-attivita-fermo-tema-scuro.png"),
new("/dashboard?scena=sessione&tema=chiaro", "06-attivita.png"),
new("/dashboard?scena=sessione&tema=chiaro", "06-attivita-tutti-i-tetti.png", Step: "tutti-tetti.js"),
new("/dashboard?scena=sessione&tema=chiaro", "14-attivita-finestra-stretta.png", 860, 900),
new("/dashboard?scena=sessione&tema=chiaro", "14-attivita-telefono.png", 390, 844),
new("/dashboard?scena=normale&tema=chiaro", "14-attivita-finestra-stretta-normale.png", 860, 900),
new("/dashboard?scena=normale&tema=chiaro", "14-attivita-telefono-normale.png", 390, 844),
new("/impostazioni/limiti?tema=chiaro", "07-limiti-e-comportamento.png", 1440, 1470),
new("/impostazioni/limiti?tema=chiaro", "07-limiti-su-misura.png", Step: "su-misura.js"),
new("/impostazioni/generali?tema=chiaro", "08-impostazioni-generali.png"),
@@ -0,0 +1,5 @@
// Switches the Libreria to «Tutte le foto» (spec §4.6): one tile per file, «2/4» on the files of a series.
await new Promise((r) => setTimeout(r, 500));
document.querySelector('.strumenti .modo-mosaico [data-value=files]')?.click();
await new Promise((r) => setTimeout(r, 2000));
return document.querySelector('.quanti')?.textContent;
+1 -1
View File
@@ -1,4 +1,4 @@
// Opens «Tutti i tetti» on the Attività page (spec §7.4: every category, hourly and daily).
// Opens «Tutti i tetti» on the Dashboard (spec §7.4: every category, hourly and daily).
await new Promise((r) => setTimeout(r, 500));
[...document.querySelectorAll('.testa-blocco .btn.collegamento')].find((b) => b.textContent.includes('tetti'))?.click();
await new Promise((r) => setTimeout(r, 600));