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:
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++;
|
||||
|
||||
@@ -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).",
|
||||
|
||||
@@ -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><Libreria>/<username></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.
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>>());
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user