From 0547c747c56f799dc3cbc25007d04687ab5cba78 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 25 Nov 2026 15:25:34 +0100 Subject: [PATCH] =?UTF-8?q?D1,=20seconda=20parte:=20=C2=ABCosa=20scaricare?= =?UTF-8?q?=20prima=C2=BB=20anche=20per=20account,=20reel=20distinti=20e?= =?UTF-8?q?=20quota=20per=20chi=20aspetta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L'ordine dei tipi (storie, evidenza, post, reel, taggati) ora vale anche per il singolo account: nella scheda account → Impostazioni si sceglie «Come le impostazioni generali» o un ordine suo, con lo stesso elenco da trascinare (o Su/Giù da tastiera) di Limiti e comportamento, ora un modulo solo (download-order.js). Il motore pesa le visite con l'ordine dell'account, la coda dei file mette ogni file al posto del suo tipo nell'ordine del suo account, stabile dentro il tipo (scadenza, scoperta, elemento, posizione). Perché nessun tipo resti fermo per sempre quando il tetto dei dati finisce prima della coda, un posto su otto di ogni giro della coda va al file che aspetta da più tempo, di qualunque tipo. I reel non si inventano (regola 9): un post è reel se viene dalla scheda Reel o se la risposta ha product_type «clips», valore visto nei campioni ripuliti. Il segno si scrive da solo e non si toglie mai, così una copia vecchia non sposta di nuovo i file in coda. Migrazione 0002_ordine_scaricamento (account.download_order, entry.is_reel): prende il primo numero dopo quelle unite, E1 userà il successivo. Prove su motore (seme fisso), coda, lettori, ricette e API; dimostrazione con un account che ha l'ordine suo; guida e decisioni aggiornate. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 5 + docs/guida/Account-e-impostazioni.md | 4 + docs/guida/Limiti-e-comportamento.md | 5 +- .../Collection/Downloads/DownloadQueue.cs | 69 +++++++- .../Collection/Readers/ReadMapping.cs | 1 + .../Collection/Readers/ReadModels.cs | 5 +- .../Collection/Readers/ReaderVocabulary.cs | 12 ++ .../Collection/Readers/ShapeReader.cs | 2 + .../Collection/Recipes/CollectionWriter.cs | 22 ++- .../Recipes/RecipeRunner.Profile.cs | 7 +- src/Febe.Core/Config/lettori.instagram.json | 6 +- src/Febe.Core/Domain/Account.cs | 7 + src/Febe.Core/Domain/DownloadKind.cs | 23 +++ src/Febe.Core/Domain/Entry.cs | 7 + src/Febe.Core/Domain/Media.cs | 6 +- src/Febe.Core/Engine/DownloadOrder.cs | 83 +++++---- src/Febe.Core/Engine/SessionComposer.cs | 5 +- src/Febe.Core/Storage/DownloadQueueOrder.cs | 15 ++ src/Febe.Core/Storage/IAccountStore.cs | 6 + src/Febe.Core/Storage/IEntryStore.cs | 6 + src/Febe.Core/Storage/IMediaStore.cs | 15 +- .../Migrations/0002_ordine_scaricamento.sql | 11 ++ src/Febe.Data/Stores/AccountStore.cs | 31 +++- src/Febe.Data/Stores/EntryMapping.cs | 6 +- src/Febe.Data/Stores/EntryStore.cs | 10 +- src/Febe.Data/Stores/MediaStore.cs | 74 ++++++-- src/Febe.Web/Api/AccountSettingsMapper.cs | 4 +- src/Febe.Web/Api/AccountsApi.cs | 3 +- src/Febe.Web/Api/Dtos.cs | 11 +- src/Febe.Web/Demo/DemoSeeder.cs | 9 +- src/Febe.Web/wwwroot/css/febe.css | 2 + src/Febe.Web/wwwroot/js/pages/account.js | 33 ++++ .../wwwroot/js/pages/download-order.js | 100 +++++++++++ .../wwwroot/js/pages/settings-limits.js | 76 ++------- src/Febe.Web/wwwroot/testi/it.json | 7 + .../Collection/DownloadQueueTests.cs | 38 +++++ .../Collection/InstagramReaderTests.cs | 12 +- .../Collection/RequestRecipeTests.cs | 5 +- tests/Febe.Tests/Engine/DownloadOrderTests.cs | 159 +++++++++++++++++- tests/Febe.Tests/Web/DashboardApiTests.cs | 31 ++++ 40 files changed, 775 insertions(+), 158 deletions(-) create mode 100644 src/Febe.Core/Domain/DownloadKind.cs create mode 100644 src/Febe.Core/Storage/DownloadQueueOrder.cs create mode 100644 src/Febe.Data/Migrations/0002_ordine_scaricamento.sql create mode 100644 src/Febe.Web/wwwroot/js/pages/download-order.js diff --git a/docs/decisioni.md b/docs/decisioni.md index f5d5559..78dfd29 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -544,3 +544,8 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | +| 2026-11-25 | D1, seconda parte: migrazione `0002_ordine_scaricamento` con `account.download_order` (testo dell'ordine suo, NULL per «Come le impostazioni generali») ed `entry.is_reel` (0/1, predefinito 0). Prende il numero 0002 perché è la prima migrazione dopo quelle unite; E1 userà il numero libero successivo (0003 se D1 si unisce prima) | §16 e la tabella delle tappe dicono «D1 ha una migrazione sua, numerata dopo quelle già unite»; il gestore delle migrazioni vuole numeri senza buchi, quindi E1 non può tenere 0002 se D1 arriva prima. Da sistemare nei documenti: §15 dice ancora «E1: migrazione `0002`» | +| 2026-11-25 | Un post è un reel per la coda quando è stato trovato nella scheda Reel (il percorso Reel segna ogni contenuto che salva) o quando la risposta ha `product_type` «clips» (`productType` e `reelTypes` nuovi in `lettori.instagram.json`, visti in post-video, post-del-profilo, reel-del-profilo e con-tag; il sito di prova non li ha). Il segno non si toglie mai: `MarkReelAsync` scrive solo quella colonna e `UpdateAsync` tiene il massimo fra il valore salvato e quello nuovo. Un taggato non è mai un reel. I post già in libreria restano post | Regola 9: il valore viene dai campioni ripuliti, non è inventato. Scrivere solo la colonna evita di riscrivere lo stato che la coda sta cambiando nello stesso momento; un reel che torna post per una copia vecchia sposterebbe di nuovo i suoi file in coda | +| 2026-11-25 | Coda dei file con «Cosa scaricare prima»: ogni file prende la posizione del suo tipo nell'ordine del suo account (il suo se ce l'ha, altrimenti il generale; gli account con lo stesso ordine suo condividono un ramo del `CASE`), poi scadenza, scoperta, elemento e posizione. Un posto su otto (`DownloadOptions.LongestWaitingShare`) va al file che aspetta da più tempo, di qualunque tipo | Senza la quota un tipo in fondo all'ordine aspetterebbe per sempre quando il tetto dei dati finisce ogni giorno prima della coda o il primo tipo non si esaurisce mai. Ogni file prima o poi è il più vecchio in attesa (i nuovi sono sempre più giovani), quindi ogni tipo ha almeno 1/8 degli scaricamenti finché ha file in coda; 7 posti su 8 restano all'ordine, così le storie in cima scadono come prima | +| 2026-11-25 | Nel motore il peso del tipo è quello dell'ordine dell'account della visita (`DownloadOrder.For`): il suo, o il generale. Le visite senza account (giro, elenco dei seguiti) restano fuori dall'ordine | §4.4: l'ordine suo pesa «sulle visite del motore a quell'account»; la prova con seme fisso mostra che i post di account con l'ordine suo vengono più spesso per primi senza diventare fissi, e che il giro resta primo | +| 2026-11-25 | Interfaccia: l'elenco da trascinare di «Cosa scaricare prima» è un modulo solo (`js/pages/download-order.js`) usato da Limiti e comportamento e dalla scheda account → Impostazioni («Come le impostazioni generali» mostra l'ordine generale in una riga, «Un ordine suo» parte da quello); i tipi spenti in «Cosa scaricare» restano attenuati con «spento in «Cosa scaricare»». Nella dimostrazione @luca.viaggi.demo ha un ordine suo e i post con un solo video sono reel | Due copie dello stesso elenco divergerebbero (tastiera, annunci per i lettori di schermo); i dati della dimostrazione mostrano i due casi | diff --git a/docs/guida/Account-e-impostazioni.md b/docs/guida/Account-e-impostazioni.md index 6e0c0f6..0e1f63e 100644 --- a/docs/guida/Account-e-impostazioni.md +++ b/docs/guida/Account-e-impostazioni.md @@ -131,6 +131,10 @@ foto del profilo), **Impostazioni** e **Cronologia** (i controlli con il loro es dentro la fascia. - **Cosa scaricare:** Foto dei post, Video e reel, Storie, Storie in evidenza, Post in cui è taggato, Foto del profilo. Quello che togli resta in libreria, ma non viene più aggiornato. +- **Cosa scaricare prima:** «Come le impostazioni generali» (di solito) oppure «Un ordine suo», che parte dall'ordine + generale e si cambia trascinando le righe o con «Su» e «Giù». Pesa sulle visite di Febe a questo account e sulla coda + dei suoi file, come l'ordine generale ([Limiti e comportamento](Limiti-e-comportamento)). I tipi spenti in «Cosa + scaricare» restano nell'elenco, attenuati. - **Limiti per questo account:** quanto indietro nel tempo (tutto, gli ultimi N post, da una data); massimo di post di storico al giorno; dimensione oltre la quale un video si salta (vuoto: nessun limite); video delle storie sì o no. Valgono insieme ai limiti generali: vince sempre il più stretto. diff --git a/docs/guida/Limiti-e-comportamento.md b/docs/guida/Limiti-e-comportamento.md index aff704c..4b1bc25 100644 --- a/docs/guida/Limiti-e-comportamento.md +++ b/docs/guida/Limiti-e-comportamento.md @@ -92,7 +92,10 @@ righe, oppure usa «Su» e «Giù», poi «Salva». Dopo il giro dei profili che 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. +scadano prima di essere scaricate. Un account può avere un ordine suo (scheda dell'account → Impostazioni, vedi +[Account e impostazioni](Account-e-impostazioni)). Un reel conta come reel quando Febe sa che lo è (l'ha trovato nella +scheda Reel, o la risposta lo dice), altrimenti come post. Perché i tipi in fondo non restino ad aspettare per sempre, +un file su otto della coda è quello che aspetta da più tempo, di qualunque tipo sia. ## Avvio graduale diff --git a/src/Febe.Core/Collection/Downloads/DownloadQueue.cs b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs index 4ebd97b..db0083a 100644 --- a/src/Febe.Core/Collection/Downloads/DownloadQueue.cs +++ b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs @@ -74,6 +74,15 @@ public sealed record DownloadOptions /// How many pending files are read from the database at a time. public int BatchSize { get; init; } = 200; + /// + /// «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. + /// + public int LongestWaitingShare { get; init; } = 8; + /// When idle, how long to wait before looking at the database again (a ends it earlier). public TimeSpan IdlePoll { get; init; } = TimeSpan.FromMinutes(1); } @@ -242,12 +251,15 @@ 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); - // «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(); + // «Cosa scaricare prima» (spec §6.5, §7.2), general and per account, read at every batch so that a change + // counts from the next one; one file in LongestWaitingShare is the longest waiting, whatever its kind. + var order = await DownloadOrder.LoadQueueOrderAsync(_storage, ct).ConfigureAwait(false); + bool Ready(PendingDownload p) => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now); + var ordered = (await _storage.Media.ListPendingDownloadsAsync(window, order, ct).ConfigureAwait(false)).Where(Ready).ToList(); + var longest = _options.LongestWaitingShare > 1 && ordered.Count > 0 + ? (await _storage.Media.ListLongestWaitingDownloadsAsync(window, ct).ConfigureAwait(false)).Where(Ready).ToList() + : []; + var batch = ComposeBatch(ordered, longest, _options.BatchSize, _options.LongestWaitingShare); if (batch.Count == 0) { break; @@ -271,6 +283,51 @@ public sealed class DownloadQueue return tally.ToReport(); } + /// + /// A batch of at most files (spec §6.5, §7.2): in the order of «Cosa scaricare prima», except + /// that every -th place goes to the file that has waited longest and is not in the batch yet, + /// whatever its kind. A file is never taken twice; when one list runs out the other fills the places. + /// + /// The waiting files in the order of «Cosa scaricare prima». + /// The same files, the longest waiting first. + /// Places in the batch. + /// One place in this many for the longest waiting; 0 or 1 for the order alone. + internal static List ComposeBatch(IReadOnlyList ordered, IReadOnlyList longest, int size, int share) + { + var batch = new List(Math.Max(0, Math.Min(size, ordered.Count + longest.Count))); + var taken = new HashSet(); + int nextOrdered = 0, nextLongest = 0; + PendingDownload? Next(IReadOnlyList list, ref int index) + { + while (index < list.Count) + { + var candidate = list[index++]; + if (taken.Add(candidate.Media.Id)) + { + return candidate; + } + } + + return null; + } + + while (batch.Count < size) + { + var oldestTurn = share > 1 && batch.Count % share == share - 1; + var next = oldestTurn + ? Next(longest, ref nextLongest) ?? Next(ordered, ref nextOrdered) + : Next(ordered, ref nextOrdered) ?? Next(longest, ref nextLongest); + if (next is null) + { + break; + } + + batch.Add(next); + } + + return batch; + } + private bool IsDue(long mediaId, DateTimeOffset now) { if (!_retryAt.TryGetValue(mediaId, out var at)) diff --git a/src/Febe.Core/Collection/Readers/ReadMapping.cs b/src/Febe.Core/Collection/Readers/ReadMapping.cs index 318b442..40bda0a 100644 --- a/src/Febe.Core/Collection/Readers/ReadMapping.cs +++ b/src/Febe.Core/Collection/Readers/ReadMapping.cs @@ -26,6 +26,7 @@ public static class ReadMapping AuthorInstagramId = foreignAuthor ? item.Owner?.Id : null, DiscoveredAt = now, ExpiresAt = kind == EntryKind.Story ? item.ExpiresAt ?? item.TakenAt.AddHours(24) : null, + IsReel = kind == EntryKind.Post && item.IsReel, }; } diff --git a/src/Febe.Core/Collection/Readers/ReadModels.cs b/src/Febe.Core/Collection/Readers/ReadModels.cs index 702669a..6a2df60 100644 --- a/src/Febe.Core/Collection/Readers/ReadModels.cs +++ b/src/Febe.Core/Collection/Readers/ReadModels.cs @@ -90,9 +90,12 @@ public sealed record ContentItem /// Order of appearance in the response, from 0. public int Order { get; init; } + /// The response marks it as a reel, or it was found in the Reel tab (spec §7.2, «Cosa scaricare prima»). + public bool IsReel { get; init; } + private bool PrintMembers(StringBuilder builder) { - builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, Files = {Files.Count}, IsComplete = {IsComplete}"); + builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, IsReel = {IsReel}, Files = {Files.Count}, IsComplete = {IsComplete}"); return true; } } diff --git a/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs b/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs index 236c441..9f8d03c 100644 --- a/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs +++ b/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs @@ -87,6 +87,12 @@ public sealed record ContentKeys /// Video duration in seconds (on the node or on the video version). public VocabularyKeys Duration { get; init; } = VocabularyKeys.None; + + /// The type of the content as the site names it (a text): a post is a reel when it is one of . + public VocabularyKeys ProductType { get; init; } = VocabularyKeys.None; + + /// The values of that mean «reel» (spec §7.2, «Cosa scaricare prima»). Empty: never told. + public IReadOnlyList ReelTypes { get; init; } = []; } /// Keys of one version of a file (one size of an image, one rendition of a video). @@ -356,6 +362,8 @@ public sealed record ReaderVocabulary Pinned = K(c.Pinned), ExpiresAt = K(c.ExpiresAt), Duration = K(c.Duration), + ProductType = K(c.ProductType), + ReelTypes = [.. (c.ReelTypes ?? []).Where(v => !string.IsNullOrWhiteSpace(v)).Select(v => v.Trim()).Distinct(StringComparer.Ordinal)], }, Version = new VersionKeys { Url = K(v.Url), Width = K(v.Width), Height = K(v.Height), HasAudio = K(v.HasAudio) }, Profile = new ProfileKeys @@ -448,6 +456,10 @@ internal sealed class ContentDto public List? ExpiresAt { get; set; } public List? Duration { get; set; } + + public List? ProductType { get; set; } + + public List? ReelTypes { get; set; } } internal sealed class VersionDto diff --git a/src/Febe.Core/Collection/Readers/ShapeReader.cs b/src/Febe.Core/Collection/Readers/ShapeReader.cs index d8a76c3..ffc2662 100644 --- a/src/Febe.Core/Collection/Readers/ShapeReader.cs +++ b/src/Febe.Core/Collection/Readers/ShapeReader.cs @@ -335,6 +335,8 @@ public sealed class ShapeReader IsComplete = complete, HighlightId = highlightId, Order = walk.Contents.Count, + IsReel = _v.Content.ReelTypes.Count > 0 && AsText(Get(_v.Content.ProductType, node)) is { } type + && _v.Content.ReelTypes.Contains(type, StringComparer.Ordinal), }; } diff --git a/src/Febe.Core/Collection/Recipes/CollectionWriter.cs b/src/Febe.Core/Collection/Recipes/CollectionWriter.cs index a76e621..5d7de3b 100644 --- a/src/Febe.Core/Collection/Recipes/CollectionWriter.cs +++ b/src/Febe.Core/Collection/Recipes/CollectionWriter.cs @@ -158,6 +158,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) if (known is not null) { await RefreshFilesAsync(known, item, fromHighlight: false, ct).ConfigureAwait(false); + known = await MarkReelAsync(known, item, ct).ConfigureAwait(false); return (new SaveResult(SaveOutcome.Known, known), 0, 0); } @@ -175,6 +176,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) InstagramId = item.Id, Code = imported.Code ?? item.Code, Caption = imported.Caption ?? item.Caption, + IsReel = imported.IsReel || (kind == EntryKind.Post && item.IsReel), }; await storage.Entries.UpdateAsync(enriched, ct).ConfigureAwait(false); return (new SaveResult(SaveOutcome.Enriched, enriched), 0, 0); @@ -186,7 +188,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) var added = await storage.Entries.AddAsync(entry, media, ct).ConfigureAwait(false); if (!added.Created) { - return (new SaveResult(SaveOutcome.Known, added.Stored.Entry), 0, 0); + return (new SaveResult(SaveOutcome.Known, await MarkReelAsync(added.Stored.Entry, item, ct).ConfigureAwait(false)), 0, 0); } if (!item.IsComplete && kind is EntryKind.Post or EntryKind.Tagged) @@ -197,6 +199,22 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) return (new SaveResult(SaveOutcome.Created, added.Stored.Entry), media.Count(m => m.State == MediaState.ToDownload), media.Count(m => m.State == MediaState.Skipped)); } + /// + /// A known post that the content now marks as a reel (the Reel tab, or the response) becomes one, for the queue of + /// the files (spec §7.2); a reel never goes back to a plain post. Returns the entry as stored. + /// + private async Task MarkReelAsync(Entry known, ContentItem item, CancellationToken ct) + { + if (known.Kind != EntryKind.Post || known.IsReel || !item.IsReel || known.State == EntryState.Deleted) + { + return known; + } + + // Only the flag is written: the queue may be changing the state of the same entry at this moment. + await storage.Entries.MarkReelAsync(known.Id, ct).ConfigureAwait(false); + return known with { IsReel = true }; + } + /// /// Saves the profile picture when its address identity is new (code = first eight hex digits of SHA-256). A /// picture already known whose file expired or failed takes the fresh address just read: the identity is the path @@ -278,6 +296,8 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) await storage.Entries.UpdateAsync(latest with { Code = latest.Code ?? item.Code, Caption = latest.Caption ?? item.Caption }, ct).ConfigureAwait(false); } + await MarkReelAsync(entry, item, ct).ConfigureAwait(false); + return changed; } diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs index 24adad9..b3a2c18 100644 --- a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs @@ -20,6 +20,9 @@ public sealed partial class RecipeRunner public bool IsGrid => TabTarget is null; + /// The Reel tab: every post it gives is a reel (). + public bool MarksReels => TabTarget == SiteTargets.ProfileTabReels; + /// The grid and the reels come newest first (pinned posts aside); the order of tagged posts is not known. public bool IsChronological => Kind != EntryKind.Tagged; @@ -566,7 +569,9 @@ public sealed partial class RecipeRunner } } - var saved = await Writer.SaveAsync(account, item, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false); + // What the Reel tab gives is a reel, whatever the response says (spec §7.2, «Cosa scaricare prima»). + var content = walk.MarksReels && !item.IsReel ? item with { IsReel = true } : item; + var saved = await Writer.SaveAsync(account, content, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false); if (saved.Outcome == SaveOutcome.Created) { run.NewEntries++; diff --git a/src/Febe.Core/Config/lettori.instagram.json b/src/Febe.Core/Config/lettori.instagram.json index e42e9b3..d798e87 100644 --- a/src/Febe.Core/Config/lettori.instagram.json +++ b/src/Febe.Core/Config/lettori.instagram.json @@ -3,7 +3,7 @@ "status": "confermato", "note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR) e completato il 12 novembre con quelle del secondo HAR (scheda del profilo, post del profilo, raccolte del profilo, storie), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome; nel blocco incorporato nella pagina iniziale (vassoio-storie, 12 novembre) ha anche username e profile_pic_url, e il lettore lo legge come Viewer (H10, da provare con la raccolta vera).", "content": { - "note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza, raccolta-pagina-successiva, post-del-profilo (reel e serie) e storie-di-un-profilo. Le griglie delle schede Reel e Con tag (reel-del-profilo, con-tag) sono anteprime senza taken_at né video_versions: non sono contenuti, il contenuto intero arriva da post-del-profilo o da /api/v1/media/…/info/. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media, media_type 8): i figli sono contenuti con le loro image_versions2 e video_versions, visti in post-del-profilo (6 foto) e serie-con-video (20 figli, uno video).", + "note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza, raccolta-pagina-successiva, post-del-profilo (reel e serie) e storie-di-un-profilo. Le griglie delle schede Reel e Con tag (reel-del-profilo, con-tag) sono anteprime senza taken_at né video_versions: non sono contenuti, il contenuto intero arriva da post-del-profilo o da /api/v1/media/…/info/. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media, media_type 8): i figli sono contenuti con le loro image_versions2 e video_versions, visti in post-del-profilo (6 foto) e serie-con-video (20 figli, uno video). product_type dice il tipo del contenuto: «clips» per i reel (post-video, post-del-profilo, reel-del-profilo, con-tag), «feed», «carousel_container», «carousel_item» e «story» per gli altri; serve solo a «Cosa scaricare prima» (un post segnato «clips» conta come reel nella coda dei file).", "id": ["pk"], "code": ["code"], "takenAt": ["taken_at"], @@ -15,7 +15,9 @@ "owner": ["user", "owner"], "pinned": [], "expiresAt": ["expiring_at"], - "duration": ["video_duration"] + "duration": ["video_duration"], + "productType": ["product_type"], + "reelTypes": ["clips"] }, "version": { "note": "Una versione: candidates di image_versions2 (url, width, height, da 10 a 14 per contenuto) e video_versions (type 101, 102, 103 e url; dimensioni solo nei post, non nelle storie). Se il video ha l'audio lo dice il contenuto (has_audio), non la versione: hasAudio resta vuoto e ogni versione conta come file completo (H5 da confermare scaricando).", diff --git a/src/Febe.Core/Domain/Account.cs b/src/Febe.Core/Domain/Account.cs index 065f590..3106649 100644 --- a/src/Febe.Core/Domain/Account.cs +++ b/src/Febe.Core/Domain/Account.cs @@ -119,6 +119,13 @@ public sealed record Account public AccountLimits Limits { get; init; } = new(); + /// + /// «Cosa scaricare prima» of this account (spec §4.4, §7.2, tappa D1): the stored text of its own order (the Italian + /// names of the five kinds, read by Febe.Core.Engine.DownloadOrder.Parse). Null: «Come le impostazioni + /// generali». + /// + public string? DownloadOrder { get; init; } + /// /// Folder of the account. Null means the default <Libreria>/<username>; a relative path is relative /// to the library (a renamed account keeps its old folder this way); an absolute path may be outside the library. diff --git a/src/Febe.Core/Domain/DownloadKind.cs b/src/Febe.Core/Domain/DownloadKind.cs new file mode 100644 index 0000000..b483d26 --- /dev/null +++ b/src/Febe.Core/Domain/DownloadKind.cs @@ -0,0 +1,23 @@ +namespace Febe.Core.Domain; + +/// +/// A type of «Cosa scaricare prima» (spec §7.2, tappa D1): the kinds of recipes of §6.3, grouped as Alberto names them. +/// The order of the kinds is Febe.Core.Engine.DownloadOrder. +/// +public enum DownloadKind +{ + /// «Storie»: Storie di un account. + Stories, + + /// «Evidenza»: Raccolta in evidenza. + Highlights, + + /// «Post»: Controllo del profilo and Storico, profile pictures included. + Posts, + + /// «Reel»: Reel, and in the queue the posts Febe knows to be reels (). + Reels, + + /// «Taggati»: Taggati. + Tagged, +} diff --git a/src/Febe.Core/Domain/Entry.cs b/src/Febe.Core/Domain/Entry.cs index 2149591..02a13cc 100644 --- a/src/Febe.Core/Domain/Entry.cs +++ b/src/Febe.Core/Domain/Entry.cs @@ -50,6 +50,13 @@ public sealed record Entry /// For stories: when the story stops being available on the site (downloads give them precedence). public DateTimeOffset? ExpiresAt { get; init; } + /// + /// A post that Febe knows to be a reel (spec §7.2, tappa D1): found in the Reel tab, or marked so in the response. + /// Only for ; once known it stays (the store never clears it). It weighs only on the queue of the files («Cosa + /// scaricare prima»): a reel is a post everywhere else. + /// + public bool IsReel { get; init; } + /// The value of the {codice} placeholder (spec §4.3) for this entry. /// SHA-256 of the file, needed for profile pictures (first eight hex digits). public string NameCode(string? sha256 = null) => Kind switch diff --git a/src/Febe.Core/Domain/Media.cs b/src/Febe.Core/Domain/Media.cs index 10b0a0a..9ca6613 100644 --- a/src/Febe.Core/Domain/Media.cs +++ b/src/Febe.Core/Domain/Media.cs @@ -76,7 +76,11 @@ public sealed record Media public sealed record MediaLocation(Media Media, Entry Entry, string Username); /// A file waiting for the download queue (spec §6.5), with what the queue needs to order it. -public sealed record PendingDownload(Media Media, long AccountId, EntryKind Kind, DateTimeOffset PublishedAt, DateTimeOffset? ExpiresAt); +public sealed record PendingDownload(Media Media, long AccountId, EntryKind Kind, DateTimeOffset PublishedAt, DateTimeOffset? ExpiresAt) +{ + /// The entry is a post Febe knows to be a reel (): «Reel» in «Cosa scaricare prima». + public bool IsReel { get; init; } +} /// What the safe writer and the hashing produced for a file now on disk. /// Path relative to the account folder, '/' separated. diff --git a/src/Febe.Core/Engine/DownloadOrder.cs b/src/Febe.Core/Engine/DownloadOrder.cs index f80e167..c360b7a 100644 --- a/src/Febe.Core/Engine/DownloadOrder.cs +++ b/src/Febe.Core/Engine/DownloadOrder.cs @@ -3,38 +3,20 @@ using Febe.Core.Storage; namespace Febe.Core.Engine; -/// A type of «Cosa scaricare prima» (spec §7.2): the kinds of recipes of §6.3, grouped as Alberto names them. -public enum DownloadKind -{ - /// «Storie»: Storie di un account. - Stories, - - /// «Evidenza»: Raccolta in evidenza. - Highlights, - - /// «Post»: Controllo del profilo and Storico, profile pictures included. - Posts, - - /// «Reel»: Reel. - Reels, - - /// «Taggati»: Taggati. - Tagged, -} - /// -/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in as their -/// Italian names separated by commas. It weighs the next visit after the Giro dei seguiti (the weight of a kind is -/// , multiplied by the weight of the account) and the order of the queue of the files (spec §6.5). It -/// never adds a visit, never brings one forward and never makes the order fixed: it only weighs the choices the engine -/// already makes among the work that is due and allowed. +/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in (general) +/// or in (an account's own) as their Italian names separated by commas. It weighs the +/// next visit after the Giro dei seguiti (the weight of a kind is , multiplied by the weight of the +/// account) and the order of the queue of the files (spec §6.5). It never adds a visit, never brings one forward and +/// never makes the order fixed: it only weighs the choices the engine already makes among the work that is due and +/// allowed. /// public sealed class DownloadOrder { /// The general order (Impostazioni → Limiti e comportamento). public const string SettingKey = "scaricamento.ordine"; - /// The weights of the positions, first to last (spec §7.4 table, «Peso di un tipo nella scelta»). + /// The weights of the positions, first to last (spec §7.2 table, «Peso di un tipo nella scelta»). public static readonly IReadOnlyList Weights = [16, 8, 4, 2, 1]; private static readonly (DownloadKind Kind, string Name)[] Names = @@ -60,6 +42,9 @@ public sealed class DownloadOrder /// The Italian name of a kind, as stored and as the interface sends it. public static string NameOf(DownloadKind kind) => Names.First(n => n.Kind == kind).Name; + /// The names of the five kinds, first to last, as the interface shows them. + public IReadOnlyList ToNames() => [.. Kinds.Select(NameOf)]; + /// /// 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 . @@ -93,6 +78,16 @@ public sealed class DownloadOrder /// The stored text: the five names, comma separated. public override string ToString() => string.Join(',', Kinds.Select(NameOf)); + /// + /// The order that applies to an account: its own when it has one (spec §4.4, «Un ordine suo»), otherwise + /// («Come le impostazioni generali»). + /// + public static DownloadOrder For(Account? account, DownloadOrder general) + { + ArgumentNullException.ThrowIfNull(general); + return account?.DownloadOrder is { } own && !string.IsNullOrWhiteSpace(own) ? Parse(own) : general; + } + /// 0 for the first kind, 4 for the last. public int Position(DownloadKind kind) { @@ -125,24 +120,18 @@ public sealed class DownloadOrder }; /// - /// The kind of a file in the queue (spec §6.5): profile pictures go with the posts; a reel counts as a post until Febe - /// keeps whether a post is a reel (spec §8.3, the flag of entry of D1). + /// The kind of a file in the queue (spec §6.5, §7.2): a post counts as a reel when Febe knows that it is one + /// (), otherwise as a post; profile pictures go with the posts. /// - public static DownloadKind KindOf(EntryKind entry) => entry switch + public static DownloadKind KindOf(EntryKind entry, bool isReel = false) => entry switch { EntryKind.Story => DownloadKind.Stories, EntryKind.Highlight => DownloadKind.Highlights, EntryKind.Tagged => DownloadKind.Tagged, + EntryKind.Post when isReel => DownloadKind.Reels, _ => DownloadKind.Posts, }; - /// The entry kinds in the order of the queue: the position of each , first to last. - public IReadOnlyList EntryKinds() - { - var all = Enum.GetValues(); - return [.. all.OrderBy(e => Position(KindOf(e))).ThenBy(e => Array.IndexOf(all, e))]; - } - /// The general order stored in the settings. public static async Task LoadAsync(ISettingsStore settings, CancellationToken ct = default) { @@ -150,11 +139,33 @@ public sealed class DownloadOrder return Parse(await settings.GetAsync(SettingKey, ct).ConfigureAwait(false)); } - /// Stores the general order; the default is stored as no value («come le impostazioni predefinite»). + /// Stores the general order; the default is stored as no value (the setting is absent). 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); } + + /// + /// The order of the queue of the files (spec §6.5): the general order and the own order of each account that has + /// one, read fresh so that a change counts from the next batch. + /// + public static async Task LoadQueueOrderAsync(IFebeStorage storage, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(storage); + var general = await LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var own = await storage.Accounts.ListDownloadOrdersAsync(ct).ConfigureAwait(false); + var accounts = new Dictionary>(own.Count); + foreach (var (accountId, text) in own) + { + var order = Parse(text); + if (!order.Kinds.SequenceEqual(general.Kinds)) + { + accounts[accountId] = order.Kinds; + } + } + + return new DownloadQueueOrder(general.Kinds, accounts); + } } diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index 6e05b38..cf6f5d6 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -474,8 +474,9 @@ internal sealed class SessionComposer 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 owner = task.AccountId is { } ownerId ? accounts.GetValueOrDefault(ownerId) : null; + var kindWeight = kind is { } k ? DownloadOrder.For(owner, order).Weight(k) : 1; + if (owner is { } account) { var interval = task.Kind == EngineTaskKind.AccountStories ? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay) diff --git a/src/Febe.Core/Storage/DownloadQueueOrder.cs b/src/Febe.Core/Storage/DownloadQueueOrder.cs new file mode 100644 index 0000000..4979463 --- /dev/null +++ b/src/Febe.Core/Storage/DownloadQueueOrder.cs @@ -0,0 +1,15 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// +/// The order of «Cosa scaricare prima» for the queue of the files (spec §6.5, §7.2): the five kinds first to last, in +/// general and for the accounts with an order of their own. Built by Febe.Core.Engine.DownloadOrder.LoadQueueOrderAsync. +/// +/// The general order. +/// The own order of an account, by its local key; the others follow . +public sealed record DownloadQueueOrder(IReadOnlyList General, IReadOnlyDictionary> Accounts) +{ + /// The order for every account: , no account with its own. + public static DownloadQueueOrder Everywhere(IReadOnlyList general) => new(general, new Dictionary>()); +} diff --git a/src/Febe.Core/Storage/IAccountStore.cs b/src/Febe.Core/Storage/IAccountStore.cs index db210a1..61b6a42 100644 --- a/src/Febe.Core/Storage/IAccountStore.cs +++ b/src/Febe.Core/Storage/IAccountStore.cs @@ -19,6 +19,12 @@ public interface IAccountStore /// All accounts, ordered by user name. Task> ListAsync(CancellationToken ct = default); + /// + /// The stored text of «Cosa scaricare prima» of the accounts that have an order of their own (spec §4.4), by local + /// key; the accounts that follow the general order are left out. Read by the queue of the files at every batch. + /// + Task> ListDownloadOrdersAsync(CancellationToken ct = default); + /// All accounts with their counts; «new» counts are entries discovered at or after . Task> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default); diff --git a/src/Febe.Core/Storage/IEntryStore.cs b/src/Febe.Core/Storage/IEntryStore.cs index f7824c0..0df9c30 100644 --- a/src/Febe.Core/Storage/IEntryStore.cs +++ b/src/Febe.Core/Storage/IEntryStore.cs @@ -43,6 +43,12 @@ public interface IEntryStore /// Replaces the mutable fields of an entry (Instagram identifier, code, caption, author, state, dates). Task UpdateAsync(Entry entry, CancellationToken ct = default); + /// + /// Marks a post as a reel (spec §7.2, «Cosa scaricare prima»), writing only that flag; other kinds are left as they are. + /// A reel never goes back to a plain post: keeps the flag once set. + /// + Task MarkReelAsync(long entryId, CancellationToken ct = default); + Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default); /// Recomputes the state of an entry from its files (). diff --git a/src/Febe.Core/Storage/IMediaStore.cs b/src/Febe.Core/Storage/IMediaStore.cs index a54aab0..cd0d70b 100644 --- a/src/Febe.Core/Storage/IMediaStore.cs +++ b/src/Febe.Core/Storage/IMediaStore.cs @@ -31,11 +31,18 @@ public interface IMediaStore Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default); /// - /// Files waiting to be downloaded in the order of «Cosa scaricare prima» (spec §6.5, §7.2): the files of the entry kind - /// that comes first in , then the other kinds in that order, and within a kind the ones - /// that expire first, then the oldest waiting. A kind left out of the list goes last. + /// Files waiting to be downloaded in the order of «Cosa scaricare prima» (spec §6.5, §7.2): for each file the position + /// of its kind (a post Febe knows to be a reel counts as a reel) in the order of its account, which is the account's + /// own when it has one, else the general one; within a position the ones that expire first, then the oldest + /// waiting, then entry and position (stable). /// - Task> ListPendingDownloadsAsync(int limit, IReadOnlyList kindOrder, CancellationToken ct = default); + Task> ListPendingDownloadsAsync(int limit, DownloadQueueOrder order, CancellationToken ct = default); + + /// + /// Files waiting to be downloaded, the longest waiting first (discovery, then entry and position), whatever their + /// kind: the share of the queue that keeps the later kinds of «Cosa scaricare prima» from waiting for ever. + /// + Task> ListLongestWaitingDownloadsAsync(int limit, CancellationToken ct = default); /// Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»). Task CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default); diff --git a/src/Febe.Data/Migrations/0002_ordine_scaricamento.sql b/src/Febe.Data/Migrations/0002_ordine_scaricamento.sql new file mode 100644 index 0000000..d282293 --- /dev/null +++ b/src/Febe.Data/Migrations/0002_ordine_scaricamento.sql @@ -0,0 +1,11 @@ +-- Febe, schema version 2: «Cosa scaricare prima» (tappa D1, issue #59; spec §7.2, §4.4, §8.3). +-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner. +-- Only columns are added: no behaviour changes for the data already stored. + +-- The order of «Cosa scaricare prima» of the account: the Italian names of the five kinds, comma separated +-- («storie,evidenza,post,reel,taggati»). NULL: «Come le impostazioni generali» (setting scaricamento.ordine). +ALTER TABLE account ADD COLUMN download_order TEXT; + +-- A post that Febe knows to be a reel (found in the Reel tab, or marked so in the response): it counts as a reel in +-- the queue of the files. 0 for every post stored before, which Febe cannot tell apart without asking the site again. +ALTER TABLE entry ADD COLUMN is_reel INTEGER NOT NULL DEFAULT 0 CHECK (is_reel IN (0, 1)); diff --git a/src/Febe.Data/Stores/AccountStore.cs b/src/Febe.Data/Stores/AccountStore.cs index 1dd8aaf..24de29f 100644 --- a/src/Febe.Data/Stores/AccountStore.cs +++ b/src/Febe.Data/Stores/AccountStore.cs @@ -12,9 +12,9 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore + "a.unreachable_reason, a.keep_updated, a.frequency, a.custom_post_interval_min, a.custom_story_interval_min, a.content_types, " + "a.history_depth, a.history_last_posts, a.history_from, a.backfill_posts_per_day, a.max_video_bytes, a.story_videos, a.folder, " + "a.backfill_cursor, a.backfill_completed_at, a.post_count, a.last_profile_check_at, a.next_profile_check_at, " - + "a.last_stories_check_at, a.next_stories_check_at, a.notices, a.previous_username, a.renamed_at, a.format_unrecognized_at, a.added_at"; + + "a.last_stories_check_at, a.next_stories_check_at, a.notices, a.previous_username, a.renamed_at, a.format_unrecognized_at, a.added_at, a.download_order"; - internal const int ColumnCount = 34; + internal const int ColumnCount = 35; private static readonly string Visible = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'")); @@ -57,6 +57,7 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore RenamedAt = r.GetTimeOrNull(o + 31), FormatUnrecognizedAt = r.GetTimeOrNull(o + 32), AddedAt = r.GetTime(o + 33), + DownloadOrder = r.GetTextOrNull(o + 34), }; private static void Bind(SqliteCommand c, Account a) @@ -93,13 +94,16 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore .With("@previous_username", Sql.Text(a.PreviousUsername)) .With("@renamed_at", Sql.Time(a.RenamedAt)) .With("@format_unrecognized_at", Sql.Time(a.FormatUnrecognizedAt)) - .With("@added_at", Sql.Time(a.AddedAt)); + .With("@added_at", Sql.Time(a.AddedAt)) + .With("@download_order", Sql.Text(NormalizeOrder(a.DownloadOrder))); } private static string? Normalize(string? instagramId) => string.IsNullOrWhiteSpace(instagramId) ? null : instagramId.Trim(); private static string NormalizeUsername(string username) => username.Trim().TrimStart('@'); + private static string? NormalizeOrder(string? order) => string.IsNullOrWhiteSpace(order) ? null : order.Trim(); + private static void Validate(Account account) { ArgumentNullException.ThrowIfNull(account); @@ -153,6 +157,21 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore }, ct); + public Task> ListDownloadOrdersAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command("SELECT id, download_order FROM account WHERE download_order IS NOT NULL").ExecuteReader(); + var orders = new Dictionary(); + while (r.Read()) + { + orders[r.GetInt64(0)] = r.GetString(1); + } + + return orders; + }, + ct); + public Task> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default) => db.ReadAsync>( c => @@ -261,12 +280,12 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore unreachable_reason, keep_updated, frequency, custom_post_interval_min, custom_story_interval_min, content_types, history_depth, history_last_posts, history_from, backfill_posts_per_day, max_video_bytes, story_videos, folder, backfill_cursor, backfill_completed_at, post_count, last_profile_check_at, next_profile_check_at, - last_stories_check_at, next_stories_check_at, notices, previous_username, renamed_at, format_unrecognized_at, added_at) + last_stories_check_at, next_stories_check_at, notices, previous_username, renamed_at, format_unrecognized_at, added_at, download_order) VALUES (@instagram_id, @username, @display_name, @is_private, @is_followed, @is_mine, @state, @state_changed_at, @unreachable_reason, @keep_updated, @frequency, @custom_post_interval_min, @custom_story_interval_min, @content_types, @history_depth, @history_last_posts, @history_from, @backfill_posts_per_day, @max_video_bytes, @story_videos, @folder, @backfill_cursor, @backfill_completed_at, @post_count, @last_profile_check_at, @next_profile_check_at, - @last_stories_check_at, @next_stories_check_at, @notices, @previous_username, @renamed_at, @format_unrecognized_at, @added_at) + @last_stories_check_at, @next_stories_check_at, @notices, @previous_username, @renamed_at, @format_unrecognized_at, @added_at, @download_order) """); Bind(c, account); try @@ -305,7 +324,7 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore last_profile_check_at = @last_profile_check_at, next_profile_check_at = @next_profile_check_at, last_stories_check_at = @last_stories_check_at, next_stories_check_at = @next_stories_check_at, notices = @notices, previous_username = @previous_username, renamed_at = @renamed_at, format_unrecognized_at = @format_unrecognized_at, - added_at = @added_at + added_at = @added_at, download_order = @download_order WHERE id = @id """); Bind(c, account); diff --git a/src/Febe.Data/Stores/EntryMapping.cs b/src/Febe.Data/Stores/EntryMapping.cs index 7c3d245..d6ee406 100644 --- a/src/Febe.Data/Stores/EntryMapping.cs +++ b/src/Febe.Data/Stores/EntryMapping.cs @@ -9,9 +9,9 @@ internal static class EntryMapping { public const string EntryColumns = "e.id, e.account_id, e.kind, e.instagram_id, e.code, e.published_at, e.caption, e.author_username, e.author_instagram_id, " - + "e.state, e.provenance, e.discovered_at, e.downloaded_at, e.deleted_at, e.expires_at"; + + "e.state, e.provenance, e.discovered_at, e.downloaded_at, e.deleted_at, e.expires_at, e.is_reel"; - public const int EntryColumnCount = 15; + public const int EntryColumnCount = 16; public const string MediaColumns = "m.id, m.entry_id, m.position, m.kind, m.instagram_id, m.width, m.height, m.duration_ms, m.state, m.relative_path, m.bytes, " @@ -54,6 +54,7 @@ internal static class EntryMapping DownloadedAt = r.GetTimeOrNull(o + 12), DeletedAt = r.GetTimeOrNull(o + 13), ExpiresAt = r.GetTimeOrNull(o + 14), + IsReel = r.GetBool(o + 15), }; public static Media ReadMedia(SqliteDataReader r, int o = 0) => new() @@ -112,6 +113,7 @@ internal static class EntryMapping .With("@downloaded_at", Sql.Time(e.DownloadedAt)) .With("@deleted_at", Sql.Time(e.DeletedAt)) .With("@expires_at", Sql.Time(e.ExpiresAt)) + .With("@is_reel", Sql.Bool(e.Kind == EntryKind.Post && e.IsReel)) .With("@search_text", TextSearch.ForEntry(e.Caption, e.AuthorUsername)); public static void BindMedia(SqliteCommand c, Media m) => diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index b26129e..5bb91e9 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -110,7 +110,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore UPDATE entry SET instagram_id = @instagram_id, code = @code, published_at = @published_at, caption = @caption, author_username = @author_username, author_instagram_id = @author_instagram_id, state = @state, provenance = @provenance, discovered_at = @discovered_at, downloaded_at = @downloaded_at, - deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text + deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text, + is_reel = max(is_reel, @is_reel) WHERE id = @id """); BindEntry(c, entry); @@ -130,6 +131,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore ct); } + public Task MarkReelAsync(long entryId, CancellationToken ct = default) => + db.WriteAsync(w => w.Command("UPDATE entry SET is_reel = 1 WHERE id = @id AND kind = 'Post'").With("@id", entryId).ExecuteNonQuery(), ct); + public Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default) => db.WriteAsync( w => @@ -419,9 +423,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore var stored = entry with { InstagramId = instagramId, State = state }; var insert = w.Command(""" INSERT INTO entry (account_id, kind, instagram_id, code, published_at, caption, author_username, author_instagram_id, state, - provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text) + provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text, is_reel) VALUES (@account_id, @kind, @instagram_id, @code, @published_at, @caption, @author_username, @author_instagram_id, @state, - @provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text) + @provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text, @is_reel) """); BindEntry(insert, stored); insert.ExecuteNonQuery(); diff --git a/src/Febe.Data/Stores/MediaStore.cs b/src/Febe.Data/Stores/MediaStore.cs index f71c5cd..c3e7607 100644 --- a/src/Febe.Data/Stores/MediaStore.cs +++ b/src/Febe.Data/Stores/MediaStore.cs @@ -1,3 +1,5 @@ +using System.Globalization; +using System.Text; using Febe.Core.Domain; using Febe.Core.Storage; using static Febe.Data.Stores.EntryMapping; @@ -81,39 +83,85 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore ct); public Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) => - ListPendingAsync(limit, "(e.kind = 'Story') DESC", ct); + ListPendingAsync(limit, "(e.kind = 'Story') DESC, e.expires_at IS NULL, e.expires_at, e.discovered_at", ct); - public Task> ListPendingDownloadsAsync(int limit, IReadOnlyList kindOrder, CancellationToken ct = default) + public Task> ListPendingDownloadsAsync(int limit, DownloadQueueOrder order, CancellationToken ct = default) { - ArgumentNullException.ThrowIfNull(kindOrder); + ArgumentNullException.ThrowIfNull(order); - // 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++) + // Only enum names and integer keys go into the text of the query, never text from outside. The accounts with the + // same own order share one branch (at most 120 orders exist), so the expression stays short with many accounts. + var rank = new StringBuilder(); + var groups = order.Accounts + .GroupBy(a => string.Join(',', a.Value), StringComparer.Ordinal) + .Select(g => (Kinds: g.First().Value, Ids: g.Select(a => a.Key).Order().ToList())) + .ToList(); + if (groups.Count > 0) { - rank.Append(" WHEN '").Append(kindOrder[i].ToString()).Append("' THEN ").Append(i.ToString(System.Globalization.CultureInfo.InvariantCulture)); + rank.Append("CASE"); + foreach (var (kinds, ids) in groups) + { + rank.Append(" WHEN e.account_id IN (").AppendJoin(',', ids.Select(id => id.ToString(CultureInfo.InvariantCulture))).Append(") THEN "); + AppendRank(rank, kinds); + } + + rank.Append(" ELSE "); + AppendRank(rank, order.General); + rank.Append(" END"); + } + else + { + AppendRank(rank, order.General); } - rank.Append(" ELSE ").Append(kindOrder.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)).Append(" END"); - return ListPendingAsync(limit, rank.ToString(), ct); + return ListPendingAsync(limit, $"{rank}, e.expires_at IS NULL, e.expires_at, e.discovered_at", ct); } - private Task> ListPendingAsync(int limit, string first, CancellationToken ct) => + public Task> ListLongestWaitingDownloadsAsync(int limit, CancellationToken ct = default) => + ListPendingAsync(limit, "e.discovered_at", ct); + + /// The position of the kind of entry e in : 0 for the first, 5 for a kind left out. + private static void AppendRank(StringBuilder rank, IReadOnlyList kinds) + { + string Position(DownloadKind kind) + { + for (var i = 0; i < kinds.Count; i++) + { + if (kinds[i] == kind) + { + return i.ToString(CultureInfo.InvariantCulture); + } + } + + return kinds.Count.ToString(CultureInfo.InvariantCulture); + } + + rank.Append("(CASE WHEN e.kind = 'Story' THEN ").Append(Position(DownloadKind.Stories)) + .Append(" WHEN e.kind = 'Highlight' THEN ").Append(Position(DownloadKind.Highlights)) + .Append(" WHEN e.kind = 'Tagged' THEN ").Append(Position(DownloadKind.Tagged)) + .Append(" WHEN e.kind = 'Post' AND e.is_reel = 1 THEN ").Append(Position(DownloadKind.Reels)) + .Append(" ELSE ").Append(Position(DownloadKind.Posts)).Append(" END)"); + } + + private Task> ListPendingAsync(int limit, string order, CancellationToken ct) => db.ReadAsync>( c => { using var r = c.Command($""" - SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at + SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at, e.is_reel FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' - ORDER BY {first}, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position + ORDER BY {order}, m.entry_id, m.position LIMIT @limit """).With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader(); var list = new List(); while (r.Read()) { var o = MediaColumnCount; - list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3))); + list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3)) + { + IsReel = r.GetBool(o + 4), + }); } return list; diff --git a/src/Febe.Web/Api/AccountSettingsMapper.cs b/src/Febe.Web/Api/AccountSettingsMapper.cs index 40c0a51..a7e7cae 100644 --- a/src/Febe.Web/Api/AccountSettingsMapper.cs +++ b/src/Febe.Web/Api/AccountSettingsMapper.cs @@ -38,7 +38,8 @@ public static class AccountSettingsMapper account.Limits.BackfillPostsPerDay, account.Limits.MaxVideoBytes is { } bytes ? Math.Round(bytes / 1024d / 1024d, 1) : null, account.Limits.StoryVideos, - account.Folder); + account.Folder, + account.DownloadOrder is { } own ? DownloadOrder.Parse(own).ToNames() : null); } /// @@ -144,6 +145,7 @@ public static class AccountSettingsMapper StoryVideos = dto.StoryVideos, }, Folder = folder, + DownloadOrder = dto.DownloadOrder is { Count: > 0 } names ? DownloadOrder.From(names).ToString() : null, State = state, StateChangedAt = changedAt, }; diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs index ac0444c..41afc54 100644 --- a/src/Febe.Web/Api/AccountsApi.cs +++ b/src/Febe.Web/Api/AccountsApi.cs @@ -310,7 +310,8 @@ public static class AccountsApi account.Folder is null, account.State == AccountState.ArchiveOnly && account.InstagramId is null && account.IsMine is false ? null : InstagramLinks.Profile(account.Username), highlights, - AccountSettingsMapper.MaxBackfillPerDay); + AccountSettingsMapper.MaxBackfillPerDay, + (await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).ToNames()); } /// «Con queste impostazioni», recomputed at every change of the form (spec §4.4). diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs index d0757a6..0e08a4a 100644 --- a/src/Febe.Web/Api/Dtos.cs +++ b/src/Febe.Web/Api/Dtos.cs @@ -151,7 +151,10 @@ public sealed record AccountListDto(long Now, AccountCountsDto Counts, IReadOnly public sealed record AccountStatsDto(int Entries, int Posts, int Stories, int HighlightItems, int Tagged, int ProfilePictures, int Collections, long Bytes, int PendingFiles); -/// The editable settings of an account (mockup 05). +/// +/// The editable settings of an account (mockup 05). is «Cosa scaricare prima» (spec §4.4): +/// the names of the five kinds first to last for «Un ordine suo», null or empty for «Come le impostazioni generali». +/// public sealed record AccountSettingsDto( bool KeepUpdated, string Frequency, @@ -164,7 +167,8 @@ public sealed record AccountSettingsDto( int BackfillPerDay, double? MaxVideoMb, bool StoryVideos, - string? Folder); + string? Folder, + IReadOnlyList? DownloadOrder = null); public sealed record PlanLineDto(string Key, string Title, string Text); @@ -190,7 +194,8 @@ public sealed record AccountDetailDto( bool FolderIsDefault, string? InstagramUrl, IReadOnlyList Highlights, - int MaxBackfillPerDay); + int MaxBackfillPerDay, + IReadOnlyList? GeneralDownloadOrder = null); public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message); diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs index cecf818..7c4f9d1 100644 --- a/src/Febe.Web/Demo/DemoSeeder.cs +++ b/src/Febe.Web/Demo/DemoSeeder.cs @@ -119,7 +119,7 @@ public static class DemoSeeder new("tuo.profilo", "Il tuo profilo", false, false, AccountState.UpToDate, 420, 980, 140, 5, 402, 4, [DemoSubject.Hills, DemoSubject.Sea, DemoSubject.Food, DemoSubject.Portrait, DemoSubject.Room, DemoSubject.Sunset, DemoSubject.CityNight]) { Mine = true }, new("marta.demo", "Marta B.", true, true, AccountState.UpToDate, 810, 312, 92, 6, 40, 4, [DemoSubject.Portrait, DemoSubject.Flowers, DemoSubject.Food, DemoSubject.Room, DemoSubject.Sunset, DemoSubject.CityNight, DemoSubject.Sea, DemoSubject.Houses, DemoSubject.Hills]) { Imported = 30, Tagging = true }, new("studio.lumen.demo", "Studio Lumen", false, false, AccountState.Backfilling, 340, 8, 4, 4, 0, 3, [DemoSubject.Room, DemoSubject.Portrait, DemoSubject.Bokeh, DemoSubject.Leaves]) { PostCount = 1280, BackfillToday = 300 }, - new("luca.viaggi.demo", "Luca in viaggio", false, true, AccountState.UpToDate, 1900, 1000, 208, 8, 0, 4, [DemoSubject.Mountains, DemoSubject.Sea, DemoSubject.Road, DemoSubject.Hills, DemoSubject.Houses, DemoSubject.Sunset]) { Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories, ProfilePictures = 2 }, + new("luca.viaggi.demo", "Luca in viaggio", false, true, AccountState.UpToDate, 1900, 1000, 208, 8, 0, 4, [DemoSubject.Mountains, DemoSubject.Sea, DemoSubject.Road, DemoSubject.Hills, DemoSubject.Houses, DemoSubject.Sunset]) { Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories, ProfilePictures = 2, DownloadOrder = "post,reel,storie,evidenza,taggati" }, new("nonna.pina.demo", "Pina", true, true, AccountState.UpToDate, 150, 50, 14, 2, 0, 3, [DemoSubject.Food, DemoSubject.Flowers, DemoSubject.Room, DemoSubject.Portrait]) { Types = ContentTypes.PostPhotos | ContentTypes.Stories | ContentTypes.Highlights }, new("circolo.foto.demo", "Circolo fotografico", false, true, AccountState.Backfilling, 2060, 0, 11, 3, 0, 4, [DemoSubject.Mountains, DemoSubject.CityNight, DemoSubject.Sea, DemoSubject.Hills, DemoSubject.Bokeh, DemoSubject.Houses, DemoSubject.Road]) { PostCount = 2410, BackfillToday = 150, Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Highlights | ContentTypes.Tagged | ContentTypes.ProfilePicture }, new("giulia.corre.demo", "Giulia", false, true, AccountState.UpToDate, 600, 230, 46, 3, 0, 3, [DemoSubject.Road, DemoSubject.Hills, DemoSubject.Mountains, DemoSubject.Portrait, DemoSubject.Sea]) { ProfilePictures = 3, Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories | ContentTypes.Highlights }, @@ -362,6 +362,9 @@ public static class DemoSeeder ExpiresAt = item.Kind == EntryKind.Story ? item.Published + TimeSpan.FromHours(24) : null, }; var media = Media(item, entry, spec, account, folder, collectionTitle, layout, zone, pool, random); + + // A downloaded post with a single video is shown as a reel (spec §7.2: Febe knows it from the Reel tab). + entry = entry with { IsReel = item.Kind == EntryKind.Post && !item.Imported && media.Count == 1 && media[0].Kind == MediaKind.Video }; pending.Add(new NewEntry(entry, media)); created.Add((account.Id, item.Kind, item.Discovered, media.Sum(m => m.Bytes ?? 0), media.Count, item.Backfill)); entriesCount += item.Kind == EntryKind.ProfilePicture ? 0 : 1; @@ -641,6 +644,9 @@ public static class DemoSeeder public ContentTypes? Types { get; init; } public Frequency Frequency { get; init; } = Frequency.Normal; + + /// «Cosa scaricare prima» of its own (spec §4.4); null: «Come le impostazioni generali». + public string? DownloadOrder { get; init; } } private static ContentTypes DefaultTypes(AccountSpec spec) => @@ -674,6 +680,7 @@ public static class DemoSeeder ContentTypes = spec.State == AccountState.ArchiveOnly ? ContentTypes.None : spec.Types ?? DefaultTypes(spec), PostCount = spec.PostCount ?? (spec.State == AccountState.ArchiveOnly ? null : spec.Posts), BackfillCompletedAt = spec.State == AccountState.Backfilling || spec.State == AccountState.ArchiveOnly ? null : added + TimeSpan.FromDays(4), + DownloadOrder = spec.DownloadOrder, AddedAt = added, }; } diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index 59bdc93..a5336c3 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -696,6 +696,8 @@ a.stato:hover{border-color:var(--bordo-forte)} .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} +.riga-ordine.spenta b,.riga-ordine.spenta .posizione{color:var(--testo-3)} +.ordine-account{margin-top:10px} @media (max-width:1000px){ .cruscotto{flex-direction:column} .cruscotto .anteprima{width:100%} diff --git a/src/Febe.Web/wwwroot/js/pages/account.js b/src/Febe.Web/wwwroot/js/pages/account.js index 8c25139..c2fda66 100644 --- a/src/Febe.Web/wwwroot/js/pages/account.js +++ b/src/Febe.Web/wwwroot/js/pages/account.js @@ -13,6 +13,7 @@ import { avatar, checkbox, confirmDialog, menu, segmented, showError, toast, tog import { accountLabels, accountMenu, checkNow, openProfile } from './accounts.js'; import { confirmDelete } from './library.js'; import { Mosaic, justify, tileElement, defaultDayLabel } from './mosaic.js'; +import { kindName, orderEditor, orderOrDefault } from './download-order.js'; import { openViewer } from './viewer.js'; const KINDS = [ @@ -325,6 +326,7 @@ function settingsTab(page, detail) { function changed() { drawSaveBar(); recompute(); + drawOrder(); } // Tieni aggiornato. @@ -361,6 +363,36 @@ function settingsTab(page, detail) { return box; })); + // Cosa scaricare prima (spec §4.4, §7.2): «Come le impostazioni generali» or an order of its own, which starts from the + // general one. The kinds switched off in «Cosa scaricare» stay in the list, attenuated. + const general = orderOrDefault(detail.generalDownloadOrder); + const KIND_TYPES = { storie: ['stories'], evidenza: ['highlights'], post: ['photos', 'videos'], reel: ['videos'], taggati: ['tagged'] }; + const orderBox = h('div.ordine-account'); + const order = orderEditor({ + read: () => form.downloadOrder, + write: (next) => { form.downloadOrder = next; }, + changed, + off: (kind) => !(KIND_TYPES[kind] || []).some((key) => form.types[key]), + label: t('impAccount.ordineScelta'), + }); + const orderChoice = segmented({ + label: t('impAccount.ordineScelta'), + 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) => { + form.downloadOrder = v === 'own' ? [...general] : null; + changed(); + }, + }); + function drawOrder() { + if (Array.isArray(form.downloadOrder) && form.downloadOrder.length) { + order.draw(); + fill(orderBox, h('div.pannello', order.list), order.status); + } else { + fill(orderBox, h('p.nota', t('impAccount.ordineOra', { ordine: general.map(kindName).join(', ') }))); + } + } + drawOrder(); // Limiti. const depth = h('select', { id: 'profondita' }, ['all', 'lastPosts', 'fromDate'].map((d) => h('option', { value: d, selected: form.depth === d }, t(`impAccount.profondita.${d}`)))); const lastPosts = h('input', { type: 'number', min: '1', step: '1', value: form.lastPosts ?? 100, id: 'ultimi', inputmode: 'numeric' }); @@ -417,6 +449,7 @@ function settingsTab(page, detail) { h('div.sezione', keep, h('p.aiuto', { style: { margin: '6px 0 0 46px' } }, t('impAccount.tieniAiuto'))), h('div.sezione', h('h2.sez', t('impAccount.frequenza')), h('div.frequenza', frequency, frequencyNote), customFields), h('div.sezione', h('h2.sez', t('impAccount.cosa')), h('p.aiuto', t('impAccount.cosaAiuto')), types), + h('div.sezione', h('h2.sez', t('impAccount.ordine')), h('p.aiuto', t('impAccount.ordineAiuto')), orderChoice, orderBox), h('div.sezione', h('h2.sez', t('impAccount.limiti')), h('p.aiuto', t('impAccount.limitiAiuto')), h('div.riga-campi', h('div', h('label.etichetta', { for: 'profondita' }, t('impAccount.quanto')), h('label.campo.scelta', depth, icon('chevron-down', 's'))), diff --git a/src/Febe.Web/wwwroot/js/pages/download-order.js b/src/Febe.Web/wwwroot/js/pages/download-order.js new file mode 100644 index 0000000..8065e5d --- /dev/null +++ b/src/Febe.Web/wwwroot/js/pages/download-order.js @@ -0,0 +1,100 @@ +// «Cosa scaricare prima» (spec §7.2, §4.4, tappa D1): the list of the five kinds that moves by dragging (mouse) or with +// «Su» and «Giù» (keyboard), shared by Impostazioni → Limiti e comportamento and by the account card → Impostazioni. +// The page keeps the order and saves it with its save bar; this module only draws and moves the rows. + +import { h, icon, fill } from '../core/dom.js'; +import { t } from '../core/text.js'; + +/** The default order of the kinds, the one the server also uses. */ +export const DEFAULT_ORDER = ['storie', 'evidenza', 'post', 'reel', 'taggati']; + +/** The Italian name of a kind («Storie», «In evidenza», ...). */ +export function kindName(kind) { + return t(`impostazioni.limiti.tipi.${kind}`); +} + +/** An order as the server sent it, or the default one when it is missing. */ +export function orderOrDefault(order) { + return Array.isArray(order) && order.length ? [...order] : [...DEFAULT_ORDER]; +} + +/** + * The editor of an order. + * @param {object} options + * @param {() => string[]} options.read the current order of the page + * @param {(order: string[]) => void} options.write stores a new order in the page + * @param {() => void} options.changed called after every move (save bar, recomputations) + * @param {(kind: string) => boolean} [options.off] kinds switched off in «Cosa scaricare»: they stay, attenuated + * @param {string} [options.label] accessible name of the list + * @returns {{ list: HTMLElement, status: HTMLElement, draw: () => void }} + */ +export function orderEditor({ read, write, changed, off = () => false, label }) { + const list = h('ol.ordine-tipi', { 'aria-label': label ?? t('impostazioni.limiti.ordine') }); + const status = h('span.vh', { 'aria-live': 'polite' }); + let dragged = null; + + function move(from, to, focus) { + const order = [...read()]; + if (to < 0 || to >= order.length || from === to) return; + const [kind] = order.splice(from, 1); + order.splice(to, 0, kind); + write(order); + draw(); + changed(); + status.textContent = t('impostazioni.limiti.ordineSpostato', { tipo: kindName(kind), n: to + 1 }); + if (focus) { + const again = list.querySelector(`[data-tipo="${kind}"] [data-verso="${focus}"]`); + if (again && !again.disabled) again.focus(); + else list.querySelector(`[data-tipo="${kind}"] button:not([disabled])`)?.focus(); + } + } + + function draw() { + 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 } }, + 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, + 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 === 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; + })); + } + + return { list, status, draw }; +} diff --git a/src/Febe.Web/wwwroot/js/pages/settings-limits.js b/src/Febe.Web/wwwroot/js/pages/settings-limits.js index ecf464a..8f362ac 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings-limits.js +++ b/src/Febe.Web/wwwroot/js/pages/settings-limits.js @@ -9,11 +9,10 @@ import { h, icon, fill } from '../core/dom.js'; import { refreshEngine } from '../core/engine.js'; import { t, list, number, decimal } from '../core/text.js'; import { checkbox, confirmDialog, label, showError, toast, toggle } from '../core/ui.js'; +import { DEFAULT_ORDER, orderEditor, orderOrDefault } from './download-order.js'; 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) { @@ -34,73 +33,20 @@ 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], + order: orderOrDefault(d.downloadOrder), }; } // ------------------------------------------------------------------------------------------- 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; - })); - } + // The rows move by dragging or with «Su» and «Giù» (download-order.js); the order is saved with the save bar. + const order = orderEditor({ + read: () => form.order, + write: (next) => { form.order = next; }, + changed: () => drawSaveBar(), + }); + const orderList = order.list; + const orderStatus = order.status; + const drawOrder = order.draw; const orderReset = h('button.btn.collegamento', { type: 'button', diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index fc7d854..db1c238 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -430,6 +430,12 @@ "ore": "ore", "cosa": "Cosa scaricare", "cosaAiuto": "Quello che togli resta in libreria, ma non viene più aggiornato.", + "ordine": "Cosa scaricare prima", + "ordineAiuto": "Pesa sulle visite di Febe a questo account e sulla coda dei suoi file: il tipo più in alto viene di norma prima, ma non sempre. Non aggiunge controlli e non scavalca tetti, pause e frequenze.", + "ordineScelta": "Ordine dei tipi per questo account", + "ordineGenerale": "Come le impostazioni generali", + "ordineSuo": "Un ordine suo", + "ordineOra": "Ordine generale: {ordine}. Si cambia in Impostazioni → Limiti e comportamento.", "tipi": { "photos": "Foto dei post", "videos": "Video e reel", @@ -686,6 +692,7 @@ "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.", + "ordineSpento": "spento in «Cosa scaricare»", "ordineMetti": "Ripristina l'ordine predefinito", "ordineManiglia": "Trascina per spostare", "ordineSu": "Su", diff --git a/tests/Febe.Tests/Collection/DownloadQueueTests.cs b/tests/Febe.Tests/Collection/DownloadQueueTests.cs index effa3dd..fc387d3 100644 --- a/tests/Febe.Tests/Collection/DownloadQueueTests.cs +++ b/tests/Febe.Tests/Collection/DownloadQueueTests.cs @@ -406,6 +406,44 @@ public sealed class DownloadQueueTests Assert.AreEqual(1, cdp.Sent.Count(c => c.Method == "IO.close")); } + [TestMethod] + public async Task TheFilesArriveInTheOrderOfEachAccountWithAShareForTheLongestWaiting() + { + // «Cosa scaricare prima» (spec §6.5, §7.2): the general order for one account, an order of its own for the other. + using var temp = new TempFolder("coda-ordine"); + await using var library = await TestLibrary.CreateAsync(temp); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001")); + var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.prova", "1002") with { DownloadOrder = "taggati,post" }); + await AddAsync(library.Db, marta, "s", EntryKind.Story, "https://cdn.esempio/m/storia.jpg"); + await AddAsync(library.Db, marta, "p", EntryKind.Post, "https://cdn.esempio/m/post.jpg"); + await AddAsync(library.Db, luca, "q", EntryKind.Post, "https://cdn.esempio/m/post-luca.jpg"); + await AddAsync(library.Db, luca, "g", EntryKind.Tagged, "https://cdn.esempio/m/taggato-luca.jpg"); + var asked = new List(); + var fetcher = new ScriptedFetcher((address, destination, ct) => + { + lock (asked) + { + asked.Add(address!.AbsolutePath); + } + + return ScriptedFetcher.PhotoByPath(address, destination, ct); + }); + + var orderOnly = Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1, LongestWaitingShare = 0 }); + Assert.AreEqual(4, (await orderOnly.RunOnceAsync(CancellationToken.None)).Stored); + CollectionAssert.AreEqual(new[] { "/m/storia.jpg", "/m/taggato-luca.jpg", "/m/post-luca.jpg", "/m/post.jpg" }, asked); + + // With one place in two for the longest waiting, Marta's post, found first, is the second file. + asked.Clear(); + var older = (await library.Db.Entries.AddAsync(Make.Entry(marta.Id, "vecchio", Make.T0.AddDays(-3)) with { DiscoveredAt = Make.T0.AddDays(-2) }, [Make.Photo() with { SourceUrl = "https://cdn.esempio/m/vecchio.jpg", SourceSeenAt = Make.T0 }])).Stored.Entry; + await AddAsync(library.Db, marta, "s2", EntryKind.Story, "https://cdn.esempio/m/storia-2.jpg"); + await AddAsync(library.Db, marta, "s3", EntryKind.Story, "https://cdn.esempio/m/storia-3.jpg"); + var shared = Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1, LongestWaitingShare = 2 }); + Assert.AreEqual(3, (await shared.RunOnceAsync(CancellationToken.None)).Stored); + CollectionAssert.AreEqual(new[] { "/m/storia-2.jpg", "/m/vecchio.jpg", "/m/storia-3.jpg" }, asked); + Assert.AreEqual(EntryState.Downloaded, (await library.Db.Entries.GetAsync(older.Id))!.State); + } + private static DownloadQueue Queue(TestLibrary library, TempFolder temp, IFileFetcher fetcher, SignalDetector? signals = null, DownloadOptions? options = null, IDataBudget? budget = null) => new(library.Db, library.Ingest, fetcher, budget ?? new FakeDataBudget(), library.Clock, new SeededRandom(1), options ?? new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei") }, signals); diff --git a/tests/Febe.Tests/Collection/InstagramReaderTests.cs b/tests/Febe.Tests/Collection/InstagramReaderTests.cs index 3c84908..bbbae8f 100644 --- a/tests/Febe.Tests/Collection/InstagramReaderTests.cs +++ b/tests/Febe.Tests/Collection/InstagramReaderTests.cs @@ -65,7 +65,7 @@ public sealed class InstagramReaderTests { Vocabulary.Content.Id, Vocabulary.Content.Code, Vocabulary.Content.TakenAt, Vocabulary.Content.Caption, Vocabulary.Content.Images, Vocabulary.Content.Videos, Vocabulary.Content.Children, Vocabulary.Content.ChildCount, Vocabulary.Content.Owner, Vocabulary.Content.Pinned, - Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height, + Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Content.ProductType, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height, Vocabulary.Version.HasAudio, Vocabulary.Profile.Id, Vocabulary.Profile.Username, Vocabulary.Profile.DisplayName, Vocabulary.Profile.IsPrivate, Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt, Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items, Vocabulary.Highlight.Cover, @@ -82,6 +82,14 @@ public sealed class InstagramReaderTests { Assert.IsTrue(names.Contains(key), $"«{key}» non compare in nessun campione ripulito di Instagram."); } + + // The values that mean «reel» are values of the samples too (rule 9). + var samples = string.Concat(Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json").Select(File.ReadAllText)); + Assert.IsNotEmpty(Vocabulary.Content.ReelTypes); + foreach (var value in Vocabulary.Content.ReelTypes) + { + Assert.Contains($"\"product_type\": \"{value}\"", samples, $"«{value}» non compare come product_type in nessun campione ripulito di Instagram."); + } } [TestMethod] @@ -230,6 +238,8 @@ public sealed class InstagramReaderTests Assert.AreEqual(MediaKind.Video, reel.Kind); Assert.AreEqual((720, 1280), (reel.Best.Width, reel.Best.Height)); Assert.IsNotNull(reel.Cover); + Assert.IsTrue(result.Contents[0].IsReel, "product_type «clips»: a reel for «Cosa scaricare prima»."); + Assert.IsFalse(result.Contents[1].IsReel, "product_type «carousel_container»: a series."); var series = result.Contents[1].Files; Assert.AreEqual(6, series.Count, "carousel_media: one file for each child."); diff --git a/tests/Febe.Tests/Collection/RequestRecipeTests.cs b/tests/Febe.Tests/Collection/RequestRecipeTests.cs index 780e7dc..ef42d62 100644 --- a/tests/Febe.Tests/Collection/RequestRecipeTests.cs +++ b/tests/Febe.Tests/Collection/RequestRecipeTests.cs @@ -120,7 +120,10 @@ public sealed class RequestRecipeTests CollectionAssert.AreEqual(new[] { "taggati", "reel" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray()); CollectionAssert.AreEqual(new[] { ActionKind.BackfillPage, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray()); Assert.AreEqual(3, (await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count); - Assert.AreEqual(6, (await bed.Db.Entries.ListByAccountAsync(reels.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count); + var reelPosts = await bed.Db.Entries.ListByAccountAsync(reels.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 }); + Assert.AreEqual(6, reelPosts.Count); + Assert.IsTrue(reelPosts.All(e => e.IsReel), "what the Reel tab gives is a reel («Cosa scaricare prima», spec §7.2)"); + Assert.IsTrue((await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).All(e => !e.IsReel), "a tagged post is never a reel"); Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{Id(marta)}.completo")); Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.reel.{Id(reels)}.completo")); } diff --git a/tests/Febe.Tests/Engine/DownloadOrderTests.cs b/tests/Febe.Tests/Engine/DownloadOrderTests.cs index 8b5f361..6190fce 100644 --- a/tests/Febe.Tests/Engine/DownloadOrderTests.cs +++ b/tests/Febe.Tests/Engine/DownloadOrderTests.cs @@ -1,5 +1,7 @@ +using Febe.Core.Collection.Downloads; using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Storage; using Febe.Tests.Engine.Support; using Febe.Tests.Support; @@ -51,9 +53,23 @@ public sealed class DownloadOrderTests 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"); + Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EntryKind.Post)); + Assert.AreEqual(DownloadKind.Reels, DownloadOrder.KindOf(EntryKind.Post, isReel: true), "un post che Febe sa essere un reel conta come reel"); + Assert.AreEqual(DownloadKind.Tagged, DownloadOrder.KindOf(EntryKind.Tagged, isReel: true), "un taggato resta un taggato"); + Assert.AreEqual(DownloadKind.Stories, DownloadOrder.KindOf(EntryKind.Story)); + Assert.AreEqual(DownloadKind.Highlights, DownloadOrder.KindOf(EntryKind.Highlight)); + } - var queue = DownloadOrder.Parse("taggati,post").EntryKinds(); - CollectionAssert.AreEqual(new[] { EntryKind.Tagged, EntryKind.Post, EntryKind.ProfilePicture, EntryKind.Story, EntryKind.Highlight }, queue.ToArray()); + [TestMethod] + public void AnAccountWithoutAnOrderOfItsOwnFollowsTheGeneralOne() + { + var general = DownloadOrder.Parse("post,storie"); + var account = Make.Account("marta.demo"); + Assert.AreSame(general, DownloadOrder.For(account, general), "«Come le impostazioni generali»"); + Assert.AreSame(general, DownloadOrder.For(account with { DownloadOrder = " " }, general)); + Assert.AreSame(general, DownloadOrder.For(null, general)); + Assert.AreEqual("taggati,reel,storie,evidenza,post", DownloadOrder.For(account with { DownloadOrder = "taggati,reel" }, general).ToString(), "«Un ordine suo»"); + Assert.AreEqual(16, DownloadOrder.For(account with { DownloadOrder = "taggati,reel" }, general).Weight(DownloadKind.Tagged)); } [TestMethod] @@ -66,12 +82,122 @@ public sealed class DownloadOrderTests 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()); + var standard = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Default)); 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()); + var tagged = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Parse("taggati,post,storie"))); 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"); + Assert.AreEqual(2, tagged[2].Media.Position); + } + + [TestMethod] + public async Task AReelGoesInTheQueueAsAReelAndStaysOne() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var a = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var post = (await db.Entries.AddAsync(Make.Entry(a.Id, "post", Make.T0), [Make.Photo()])).Stored.Entry; + var reel = (await db.Entries.AddAsync(Make.Entry(a.Id, "reel", Make.T0) with { IsReel = true }, [Make.Video()])).Stored.Entry; + var tagged = (await db.Entries.AddAsync(Make.Entry(a.Id, "taggato", Make.T0, EntryKind.Tagged) with { IsReel = true }, [Make.Video()])).Stored.Entry; + Assert.IsTrue(reel.IsReel); + Assert.IsTrue((await db.Entries.GetAsync(reel.Id))!.IsReel, "il segno del reel resta nel database (migrazione 0002)"); + Assert.IsFalse((await db.Entries.GetAsync(tagged.Id))!.IsReel, "solo un post può essere un reel"); + + var reelsFirst = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Parse("reel,taggati,post"))); + CollectionAssert.AreEqual(new[] { reel.Id, tagged.Id, post.Id }, reelsFirst.Select(p => p.Media.EntryId).ToArray()); + Assert.IsTrue(reelsFirst[0].IsReel); + var standard = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Default)); + CollectionAssert.AreEqual(new[] { post.Id, reel.Id, tagged.Id }, standard.Select(p => p.Media.EntryId).ToArray(), "post, poi reel, poi taggati"); + + // A known post marked as a reel later becomes one; a full update with a stale copy never clears the mark. + await db.Entries.MarkReelAsync(post.Id); + Assert.IsTrue((await db.Entries.GetAsync(post.Id))!.IsReel); + await db.Entries.UpdateAsync(post with { Caption = "didascalia" }); + Assert.IsTrue((await db.Entries.GetAsync(post.Id))!.IsReel, "un reel non torna un post"); + await db.Entries.MarkReelAsync(tagged.Id); + Assert.IsFalse((await db.Entries.GetAsync(tagged.Id))!.IsReel); + } + + [TestMethod] + public async Task EachAccountHasItsOwnOrderInTheQueue() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var general = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var own = await db.Accounts.AddAsync(Make.Account("luca.demo") with { DownloadOrder = "taggati,post" }); + var other = await db.Accounts.AddAsync(Make.Account("pina.demo") with { DownloadOrder = "taggati,post" }); + var same = await db.Accounts.AddAsync(Make.Account("anna.demo") with { DownloadOrder = DownloadOrder.Default.ToString() }); + Assert.AreEqual("taggati,post", (await db.Accounts.GetAsync(own.Id))!.DownloadOrder); + Assert.IsNull((await db.Accounts.GetAsync(general.Id))!.DownloadOrder); + + var story = (await db.Entries.AddAsync(Make.Entry(general.Id, "s", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(3) }, [Make.Photo()])).Stored.Entry; + var post = (await db.Entries.AddAsync(Make.Entry(general.Id, "p", Make.T0), [Make.Photo()])).Stored.Entry; + var ownPost = (await db.Entries.AddAsync(Make.Entry(own.Id, "q", Make.T0), [Make.Photo()])).Stored.Entry; + var ownTagged = (await db.Entries.AddAsync(Make.Entry(own.Id, "g", Make.T0, EntryKind.Tagged), [Make.Photo()])).Stored.Entry; + var ownStory = (await db.Entries.AddAsync(Make.Entry(own.Id, "t", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(3) }, [Make.Photo()])).Stored.Entry; + var otherTagged = (await db.Entries.AddAsync(Make.Entry(other.Id, "h", Make.T0, EntryKind.Tagged), [Make.Photo()])).Stored.Entry; + + var order = await DownloadOrder.LoadQueueOrderAsync(db); + Assert.HasCount(2, order.Accounts, "an own order equal to the general one changes nothing in the queue"); + Assert.IsFalse(order.Accounts.ContainsKey(same.Id)); + + // Positions: the story of the general account 0, the tagged of the two accounts with their own order 0, their + // post 1, their story 2, the post of the general account 2. Within a position: expiring first, then discovery. + var queue = await db.Media.ListPendingDownloadsAsync(20, order); + CollectionAssert.AreEqual( + new[] { story.Id, ownTagged.Id, otherTagged.Id, ownPost.Id, ownStory.Id, post.Id }, + queue.Select(p => p.Media.EntryId).ToArray()); + } + + [TestMethod] + public void TheLongestWaitingFileHasItsShareOfTheBatch() + { + // Ten stories that keep coming and one tagged post that has waited the longest. + var stories = Enumerable.Range(1, 10).Select(i => Pending(i, EntryKind.Story)).ToList(); + var tagged = Pending(100, EntryKind.Tagged); + var ordered = stories.Append(tagged).ToList(); + var longest = new[] { tagged }.Concat(stories).ToList(); + + var batch = DownloadQueue.ComposeBatch(ordered, longest, 8, 4); + CollectionAssert.AreEqual(new long[] { 1, 2, 3, 100, 4, 5, 6, 7 }, batch.Select(p => p.Media.Id).ToArray(), "un posto su quattro va a chi aspetta da più tempo"); + + var orderOnly = DownloadQueue.ComposeBatch(ordered, longest, 11, 0); + Assert.AreEqual(100, orderOnly[^1].Media.Id, "senza la quota il taggato viene per ultimo"); + + var all = DownloadQueue.ComposeBatch(ordered, longest, 50, 4); + Assert.HasCount(11, all, "nessun file due volte, e tutti quando c'è posto"); + Assert.AreEqual(11, all.Select(p => p.Media.Id).Distinct().Count()); + + Assert.IsEmpty(DownloadQueue.ComposeBatch([], [], 8, 4)); + CollectionAssert.AreEqual(new long[] { 100 }, DownloadQueue.ComposeBatch([], [tagged], 8, 4).Select(p => p.Media.Id).ToArray()); + } + + [TestMethod] + public void NoKindWaitsForEverEvenWhenTheFirstKindNeverEnds() + { + // Every round (a day with its data budget) brings 6 new stories and downloads only 4 files: with the order + // alone the tagged posts would wait for ever; with one place in four for the longest waiting they all arrive. + var waiting = Enumerable.Range(1, 5).Select(i => Pending(1000 + i, EntryKind.Tagged, discovered: i)).ToList(); + var next = 1L; + var rounds = 0; + while (waiting.Any(p => p.Kind == EntryKind.Tagged) && rounds++ < 100) + { + for (var i = 0; i < 6; i++) + { + waiting.Add(Pending(next, EntryKind.Story, discovered: 100 + next)); + next++; + } + + var ordered = waiting.OrderBy(p => p.Kind == EntryKind.Story ? 0 : 4).ThenBy(p => p.Media.EntryId).ToList(); + var longest = waiting.OrderBy(p => p.Media.EntryId).ToList(); + foreach (var done in DownloadQueue.ComposeBatch(ordered, longest, 4, 4)) + { + waiting.Remove(done); + } + } + + Assert.IsLessThanOrEqualTo(20, rounds, $"i taggati sono arrivati in {rounds} giri"); } [TestMethod] @@ -88,6 +214,18 @@ public sealed class DownloadOrderTests Assert.AreEqual(standard.SweepFirst, postsFirst.SweepFirst, 0.15, "la composizione delle sessioni non cambia"); } + [TestMethod] + public async Task TheOwnOrderOfAnAccountWeighsItsVisitsAsTheGeneralOneDoes() + { + // The accounts of the posts put «post» first in an order of their own, the general order stays the default. + var standard = await FirstVisitsAsync(null); + var own = await FirstVisitsAsync(null, postsOwnOrder: "post,storie"); + + Assert.IsGreaterThan(10, own.Sessions); + Assert.IsGreaterThan(standard.PostsFirst + 0.1, own.PostsFirst, $"post per primi: {own.PostsFirst:P0} contro {standard.PostsFirst:P0}"); + Assert.IsLessThan(1.0, own.PostsFirst, "l'ordine pesa ma non diventa fisso"); + Assert.AreEqual(standard.SweepFirst, own.SweepFirst, 0.15, "il giro resta primo, la composizione non cambia"); + } [TestMethod] public async Task AKindWithNothingDueIsNotVisited() { @@ -107,11 +245,16 @@ public sealed class DownloadOrderTests Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck), "il resto del lavoro va avanti"); } + private static DownloadQueueOrder Everywhere(DownloadOrder order) => DownloadQueueOrder.Everywhere(order.Kinds); + + /// A file waiting in the queue; orders the longest waiting (here: the entry key). + private static PendingDownload Pending(long id, EntryKind kind, long? discovered = null) => + new(Make.Photo() with { Id = id, EntryId = discovered ?? id }, 1, kind, Make.T0, null); /// /// Three days of the engine with accounts that want only their stories and accounts that want only their posts: in /// how many sessions with both, the first of them after the sweep was a profile check. /// - private static async Task<(double PostsFirst, double SweepFirst, int Sessions)> FirstVisitsAsync(string? order) + private static async Task<(double PostsFirst, double SweepFirst, int Sessions)> FirstVisitsAsync(string? order, string? postsOwnOrder = null) { await using var bed = await EngineTestBed.CreateAsync(Morning, seed: 11); if (order is not null) @@ -123,7 +266,11 @@ public sealed class DownloadOrderTests 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 posts = await bed.AddAccountAsync($"post{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos); + if (postsOwnOrder is not null) + { + await bed.Db.Accounts.UpdateAsync(posts with { DownloadOrder = postsOwnOrder }); + } } var runner = new ScriptedRunner(bed.Governor, bed.Clock); diff --git a/tests/Febe.Tests/Web/DashboardApiTests.cs b/tests/Febe.Tests/Web/DashboardApiTests.cs index b008c88..6e2f7f5 100644 --- a/tests/Febe.Tests/Web/DashboardApiTests.cs +++ b/tests/Febe.Tests/Web/DashboardApiTests.cs @@ -1,4 +1,5 @@ using System.Net; +using System.Text.Json; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Tests.Support; @@ -65,4 +66,34 @@ public sealed class DashboardApiTests 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"); } + + [TestMethod] + public async Task AnAccountFollowsTheGeneralOrderOrHasOneOfItsOwn() + { + await using var server = await Part2.StartAsync(); + await server.Db.Settings.SetAsync(DownloadOrder.SettingKey, "post,storie"); + var account = await server.Db.Accounts.AddAsync(Make.Account("marta.prova")); + + var detail = await server.GetJsonAsync($"/api/accounts/{account.Id}"); + Assert.AreEqual(JsonValueKind.Null, detail.GetProperty("settings").GetProperty("downloadOrder").ValueKind, "«Come le impostazioni generali»"); + CollectionAssert.AreEqual(new[] { "post", "storie", "evidenza", "reel", "taggati" }, detail.Items("generalDownloadOrder").Select(k => k.GetString()).ToArray()); + + // «Un ordine suo»: saved with the other settings, completed to the five kinds. + var settings = JsonSerializer.Deserialize>(detail.GetProperty("settings").GetRawText())!; + settings["downloadOrder"] = JsonSerializer.SerializeToElement(new[] { "reel", "taggati" }); + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", settings); + Assert.AreEqual(HttpStatusCode.OK, status); + CollectionAssert.AreEqual(new[] { "reel", "taggati", "storie", "evidenza", "post" }, saved.GetProperty("settings").Items("downloadOrder").Select(k => k.GetString()).ToArray()); + Assert.AreEqual("reel,taggati,storie,evidenza,post", (await server.Db.Accounts.GetAsync(account.Id))!.DownloadOrder); + + // «Tieni aggiornato» from the table keeps it; back to «Come le impostazioni generali» with null. + (status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/keep-updated", new { value = false }); + Assert.AreEqual(HttpStatusCode.OK, status); + Assert.AreEqual("reel,taggati,storie,evidenza,post", (await server.Db.Accounts.GetAsync(account.Id))!.DownloadOrder); + settings = JsonSerializer.Deserialize>((await server.GetJsonAsync($"/api/accounts/{account.Id}")).GetProperty("settings").GetRawText())!; + settings["downloadOrder"] = JsonSerializer.SerializeToElement(null); + (status, _) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", settings); + Assert.AreEqual(HttpStatusCode.OK, status); + Assert.IsNull((await server.Db.Accounts.GetAsync(account.Id))!.DownloadOrder); + } }