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
@@ -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));
|
||||
@@ -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);
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user