D1, seconda parte: «Cosa scaricare prima» anche per account, reel distinti e quota per chi aspetta

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 15:25:34 +01:00
1 parent d6c0ef851d
commit 0547c747c5
40 files changed
+775 -158

No files matched your search

@@ -74,6 +74,15 @@ public sealed record DownloadOptions
/// <summary>How many pending files are read from the database at a time.</summary>
public int BatchSize { get; init; } = 200;
/// <summary>
/// «Cosa scaricare prima» never starves the later kinds (spec §6.5, §7.2): one file in this many is the one that has
/// waited longest, whatever its kind; the others follow the order. Every file in the queue becomes the longest
/// waiting sooner or later (new files are always younger), so every kind gets at least this share of the downloads
/// while it has files waiting, even when the daily data budget ends each day before the queue does. 0 or 1: the
/// order alone.
/// </summary>
public int LongestWaitingShare { get; init; } = 8;
/// <summary>When idle, how long to wait before looking at the database again (a <see cref="DownloadQueue.Wake"/> ends it earlier).</summary>
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();
}
/// <summary>
/// A batch of at most <paramref name="size"/> files (spec §6.5, §7.2): in the order of «Cosa scaricare prima», except
/// that every <paramref name="share"/>-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.
/// </summary>
/// <param name="ordered">The waiting files in the order of «Cosa scaricare prima».</param>
/// <param name="longest">The same files, the longest waiting first.</param>
/// <param name="size">Places in the batch.</param>
/// <param name="share">One place in this many for the longest waiting; 0 or 1 for the order alone.</param>
internal static List<PendingDownload> ComposeBatch(IReadOnlyList<PendingDownload> ordered, IReadOnlyList<PendingDownload> longest, int size, int share)
{
var batch = new List<PendingDownload>(Math.Max(0, Math.Min(size, ordered.Count + longest.Count)));
var taken = new HashSet<long>();
int nextOrdered = 0, nextLongest = 0;
PendingDownload? Next(IReadOnlyList<PendingDownload> 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))
@@ -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,
};
}
@@ -90,9 +90,12 @@ public sealed record ContentItem
/// <summary>Order of appearance in the response, from 0.</summary>
public int Order { get; init; }
/// <summary>The response marks it as a reel, or it was found in the Reel tab (spec §7.2, «Cosa scaricare prima»).</summary>
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;
}
}
@@ -87,6 +87,12 @@ public sealed record ContentKeys
/// <summary>Video duration in seconds (on the node or on the video version).</summary>
public VocabularyKeys Duration { get; init; } = VocabularyKeys.None;
/// <summary>The type of the content as the site names it (a text): a post is a reel when it is one of <see cref="ReelTypes"/>.</summary>
public VocabularyKeys ProductType { get; init; } = VocabularyKeys.None;
/// <summary>The values of <see cref="ProductType"/> that mean «reel» (spec §7.2, «Cosa scaricare prima»). Empty: never told.</summary>
public IReadOnlyList<string> ReelTypes { get; init; } = [];
}
/// <summary>Keys of one version of a file (one size of an image, one rendition of a video).</summary>
@@ -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<string>? ExpiresAt { get; set; }
public List<string>? Duration { get; set; }
public List<string>? ProductType { get; set; }
public List<string>? ReelTypes { get; set; }
}
internal sealed class VersionDto
@@ -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),
};
}
@@ -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));
}
/// <summary>
/// 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.
/// </summary>
private async Task<Entry> 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 };
}
/// <summary>
/// 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;
}
@@ -20,6 +20,9 @@ public sealed partial class RecipeRunner
public bool IsGrid => TabTarget is null;
/// <summary>The Reel tab: every post it gives is a reel (<see cref="Entry.IsReel"/>).</summary>
public bool MarksReels => TabTarget == SiteTargets.ProfileTabReels;
/// <summary>The grid and the reels come newest first (pinned posts aside); the order of tagged posts is not known.</summary>
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++;
+4 -2
View File
@@ -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).",
+7
View File
@@ -119,6 +119,13 @@ public sealed record Account
public AccountLimits Limits { get; init; } = new();
/// <summary>
/// «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 <c>Febe.Core.Engine.DownloadOrder.Parse</c>). Null: «Come le impostazioni
/// generali».
/// </summary>
public string? DownloadOrder { get; init; }
/// <summary>
/// Folder of the account. Null means the default <c>&lt;Libreria&gt;/&lt;username&gt;</c>; 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.
+23
View File
@@ -0,0 +1,23 @@
namespace Febe.Core.Domain;
/// <summary>
/// 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 <c>Febe.Core.Engine.DownloadOrder</c>.
/// </summary>
public enum DownloadKind
{
/// <summary>«Storie»: Storie di un account.</summary>
Stories,
/// <summary>«Evidenza»: Raccolta in evidenza.</summary>
Highlights,
/// <summary>«Post»: Controllo del profilo and Storico, profile pictures included.</summary>
Posts,
/// <summary>«Reel»: Reel, and in the queue the posts Febe knows to be reels (<see cref="Entry.IsReel"/>).</summary>
Reels,
/// <summary>«Taggati»: Taggati.</summary>
Tagged,
}
+7
View File
@@ -50,6 +50,13 @@ public sealed record Entry
/// <summary>For stories: when the story stops being available on the site (downloads give them precedence).</summary>
public DateTimeOffset? ExpiresAt { get; init; }
/// <summary>
/// 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 <see cref="EntryKind.Post"/>; 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.
/// </summary>
public bool IsReel { get; init; }
/// <summary>The value of the <c>{codice}</c> placeholder (spec §4.3) for this entry.</summary>
/// <param name="sha256">SHA-256 of the file, needed for profile pictures (first eight hex digits).</param>
public string NameCode(string? sha256 = null) => Kind switch
+5 -1
View File
@@ -76,7 +76,11 @@ public sealed record Media
public sealed record MediaLocation(Media Media, Entry Entry, string Username);
/// <summary>A file waiting for the download queue (spec §6.5), with what the queue needs to order it.</summary>
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)
{
/// <summary>The entry is a post Febe knows to be a reel (<see cref="Entry.IsReel"/>): «Reel» in «Cosa scaricare prima».</summary>
public bool IsReel { get; init; }
}
/// <summary>What the safe writer and the hashing produced for a file now on disk.</summary>
/// <param name="RelativePath">Path relative to the account folder, '/' separated.</param>
+47 -36
View File
@@ -3,38 +3,20 @@ using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>A type of «Cosa scaricare prima» (spec §7.2): the kinds of recipes of §6.3, grouped as Alberto names them.</summary>
public enum DownloadKind
{
/// <summary>«Storie»: Storie di un account.</summary>
Stories,
/// <summary>«Evidenza»: Raccolta in evidenza.</summary>
Highlights,
/// <summary>«Post»: Controllo del profilo and Storico, profile pictures included.</summary>
Posts,
/// <summary>«Reel»: Reel.</summary>
Reels,
/// <summary>«Taggati»: Taggati.</summary>
Tagged,
}
/// <summary>
/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in <see cref="SettingKey"/> as their
/// Italian names separated by commas. It weighs the next visit after the Giro dei seguiti (the weight of a kind is
/// <see cref="Weight"/>, multiplied by the weight of the account) and the order of the queue of the files (spec §6.5). It
/// never adds a visit, never brings one forward and never makes the order fixed: it only weighs the choices the engine
/// already makes among the work that is due and allowed.
/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in <see cref="SettingKey"/> (general)
/// or in <see cref="Account.DownloadOrder"/> (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 <see cref="Weight"/>, multiplied by the weight of the
/// account) and the order of the queue of the files (spec §6.5). It never adds a visit, never brings one forward and
/// never makes the order fixed: it only weighs the choices the engine already makes among the work that is due and
/// allowed.
/// </summary>
public sealed class DownloadOrder
{
/// <summary>The general order (Impostazioni → Limiti e comportamento).</summary>
public const string SettingKey = "scaricamento.ordine";
/// <summary>The weights of the positions, first to last (spec §7.4 table, «Peso di un tipo nella scelta»).</summary>
/// <summary>The weights of the positions, first to last (spec §7.2 table, «Peso di un tipo nella scelta»).</summary>
public static readonly IReadOnlyList<double> Weights = [16, 8, 4, 2, 1];
private static readonly (DownloadKind Kind, string Name)[] Names =
@@ -60,6 +42,9 @@ public sealed class DownloadOrder
/// <summary>The Italian name of a kind, as stored and as the interface sends it.</summary>
public static string NameOf(DownloadKind kind) => Names.First(n => n.Kind == kind).Name;
/// <summary>The names of the five kinds, first to last, as the interface shows them.</summary>
public IReadOnlyList<string> ToNames() => [.. Kinds.Select(NameOf)];
/// <summary>
/// Reads a stored order. Unknown names are left out, a kind named twice counts once and the kinds missing are added
/// at the end in the default order, so any text gives the five kinds; null or empty gives <see cref="Default"/>.
@@ -93,6 +78,16 @@ public sealed class DownloadOrder
/// <summary>The stored text: the five names, comma separated.</summary>
public override string ToString() => string.Join(',', Kinds.Select(NameOf));
/// <summary>
/// The order that applies to an account: its own when it has one (spec §4.4, «Un ordine suo»), otherwise
/// <paramref name="general"/> («Come le impostazioni generali»).
/// </summary>
public static DownloadOrder For(Account? account, DownloadOrder general)
{
ArgumentNullException.ThrowIfNull(general);
return account?.DownloadOrder is { } own && !string.IsNullOrWhiteSpace(own) ? Parse(own) : general;
}
/// <summary>0 for the first kind, 4 for the last.</summary>
public int Position(DownloadKind kind)
{
@@ -125,24 +120,18 @@ public sealed class DownloadOrder
};
/// <summary>
/// The kind of a file in the queue (spec §6.5): profile pictures go with the posts; a reel counts as a post until Febe
/// keeps whether a post is a reel (spec §8.3, the flag of <c>entry</c> of D1).
/// 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
/// (<see cref="Entry.IsReel"/>), otherwise as a post; profile pictures go with the posts.
/// </summary>
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,
};
/// <summary>The entry kinds in the order of the queue: the position of each <see cref="EntryKind"/>, first to last.</summary>
public IReadOnlyList<EntryKind> EntryKinds()
{
var all = Enum.GetValues<EntryKind>();
return [.. all.OrderBy(e => Position(KindOf(e))).ThenBy(e => Array.IndexOf(all, e))];
}
/// <summary>The general order stored in the settings.</summary>
public static async Task<DownloadOrder> LoadAsync(ISettingsStore settings, CancellationToken ct = default)
{
@@ -150,11 +139,33 @@ public sealed class DownloadOrder
return Parse(await settings.GetAsync(SettingKey, ct).ConfigureAwait(false));
}
/// <summary>Stores the general order; the default is stored as no value («come le impostazioni predefinite»).</summary>
/// <summary>Stores the general order; the default is stored as no value (the setting is absent).</summary>
public static Task SaveAsync(ISettingsStore settings, DownloadOrder order, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(order);
return settings.SetAsync(SettingKey, order.IsDefault ? null : order.ToString(), ct);
}
/// <summary>
/// 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.
/// </summary>
public static async Task<DownloadQueueOrder> 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<long, IReadOnlyList<DownloadKind>>(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);
}
}
+3 -2
View File
@@ -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)
@@ -0,0 +1,15 @@
using Febe.Core.Domain;
namespace Febe.Core.Storage;
/// <summary>
/// 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 <c>Febe.Core.Engine.DownloadOrder.LoadQueueOrderAsync</c>.
/// </summary>
/// <param name="General">The general order.</param>
/// <param name="Accounts">The own order of an account, by its local key; the others follow <paramref name="General"/>.</param>
public sealed record DownloadQueueOrder(IReadOnlyList<DownloadKind> General, IReadOnlyDictionary<long, IReadOnlyList<DownloadKind>> Accounts)
{
/// <summary>The order for every account: <paramref name="general"/>, no account with its own.</summary>
public static DownloadQueueOrder Everywhere(IReadOnlyList<DownloadKind> general) => new(general, new Dictionary<long, IReadOnlyList<DownloadKind>>());
}
+6
View File
@@ -19,6 +19,12 @@ public interface IAccountStore
/// <summary>All accounts, ordered by user name.</summary>
Task<IReadOnlyList<Account>> ListAsync(CancellationToken ct = default);
/// <summary>
/// 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.
/// </summary>
Task<IReadOnlyDictionary<long, string>> ListDownloadOrdersAsync(CancellationToken ct = default);
/// <summary>All accounts with their counts; «new» counts are entries discovered at or after <paramref name="newSince"/>.</summary>
Task<IReadOnlyList<AccountSummary>> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default);
+6
View File
@@ -43,6 +43,12 @@ public interface IEntryStore
/// <summary>Replaces the mutable fields of an entry (Instagram identifier, code, caption, author, state, dates).</summary>
Task UpdateAsync(Entry entry, CancellationToken ct = default);
/// <summary>
/// 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: <see cref="UpdateAsync"/> keeps the flag once set.
/// </summary>
Task MarkReelAsync(long entryId, CancellationToken ct = default);
Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default);
/// <summary>Recomputes the state of an entry from its files (<see cref="EntryStateRules.FromMedia"/>).</summary>
+11 -4
View File
@@ -31,11 +31,18 @@ public interface IMediaStore
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default);
/// <summary>
/// Files waiting to be downloaded in the order of «Cosa scaricare prima» (spec §6.5, §7.2): the files of the entry kind
/// that comes first in <paramref name="kindOrder"/>, then the other kinds in that order, and within a kind the ones
/// that expire first, then the oldest waiting. A kind left out of the list goes last.
/// 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).
/// </summary>
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, IReadOnlyList<EntryKind> kindOrder, CancellationToken ct = default);
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, DownloadQueueOrder order, CancellationToken ct = default);
/// <summary>
/// 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.
/// </summary>
Task<IReadOnlyList<PendingDownload>> ListLongestWaitingDownloadsAsync(int limit, CancellationToken ct = default);
/// <summary>Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»).</summary>
Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default);
@@ -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));
+25 -6
View File
@@ -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<IReadOnlyDictionary<long, string>> ListDownloadOrdersAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<long, string>>(
c =>
{
using var r = c.Command("SELECT id, download_order FROM account WHERE download_order IS NOT NULL").ExecuteReader();
var orders = new Dictionary<long, string>();
while (r.Read())
{
orders[r.GetInt64(0)] = r.GetString(1);
}
return orders;
},
ct);
public Task<IReadOnlyList<AccountSummary>> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<AccountSummary>>(
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);
+4 -2
View File
@@ -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) =>
+7 -3
View File
@@ -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();
+61 -13
View File
@@ -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<IReadOnlyList<PendingDownload>> 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<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, IReadOnlyList<EntryKind> kindOrder, CancellationToken ct = default)
public Task<IReadOnlyList<PendingDownload>> 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<IReadOnlyList<PendingDownload>> ListPendingAsync(int limit, string first, CancellationToken ct) =>
public Task<IReadOnlyList<PendingDownload>> ListLongestWaitingDownloadsAsync(int limit, CancellationToken ct = default) =>
ListPendingAsync(limit, "e.discovered_at", ct);
/// <summary>The position of the kind of <c>entry e</c> in <paramref name="kinds"/>: 0 for the first, 5 for a kind left out.</summary>
private static void AppendRank(StringBuilder rank, IReadOnlyList<DownloadKind> 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<IReadOnlyList<PendingDownload>> ListPendingAsync(int limit, string order, CancellationToken ct) =>
db.ReadAsync<IReadOnlyList<PendingDownload>>(
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<PendingDownload>();
while (r.Read())
{
var o = MediaColumnCount;
list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum<EntryKind>(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3)));
list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum<EntryKind>(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3))
{
IsReel = r.GetBool(o + 4),
});
}
return list;
+3 -1
View File
@@ -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);
}
/// <summary>
@@ -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,
};
+2 -1
View File
@@ -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());
}
/// <summary>«Con queste impostazioni», recomputed at every change of the form (spec §4.4).</summary>
+8 -3
View File
@@ -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);
/// <summary>The editable settings of an account (mockup 05).</summary>
/// <summary>
/// The editable settings of an account (mockup 05). <see cref="DownloadOrder"/> 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».
/// </summary>
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<string>? 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<HighlightDto> Highlights,
int MaxBackfillPerDay);
int MaxBackfillPerDay,
IReadOnlyList<string>? GeneralDownloadOrder = null);
public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message);
+8 -1
View File
@@ -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;
/// <summary>«Cosa scaricare prima» of its own (spec §4.4); null: «Come le impostazioni generali».</summary>
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,
};
}
+2
View File
@@ -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%}
+33
View File
@@ -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'))),
@@ -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 };
}
@@ -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',
+7
View File
@@ -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",