D1, quarta parte: «Raggruppa i post» o «Tutte le foto» in Libreria e scheda account

Un post con più foto era una tessera sola: per vederle tutte bisognava aprirlo.
Ora un interruttore nella riga degli strumenti (Libreria e Contenuti
dell'account, non «In evidenza») passa a una tessera per file, video dei
caroselli compresi, con la posizione «2/4» sulla tessera; la scelta resta nel
browser, una per pagina, e il predefinito è raggruppato (§4.6).

- API: /api/library e /api/library/days accettano mode=files; il cursore
  diventa «ms.elemento.posizione», i giorni contano file e il totale dice anche
  quanti file. Le finestre restano a chiavi sull'indice di pubblicazione; per i
  conteggi un indice ix_media_entry_files (entry_id, state, kind) nella
  migrazione 0002 non ancora unita. Prova di scala a 200.000 elementi: finestre
  6-11 ms, conteggi 0,2-0,3 s.
- Visualizzatore: si apre sul file della tessera e va di file in file, anche da
  un elemento al successivo («Libreria, file 12 di 30.340»).
- Selezione di file; elenco CSV ed «Elimina» lavorano sugli elementi interi e
  lo dicono («3 file scelti appartengono a 2 elementi: elimino gli elementi
  interi, 9 file»). «Copia in…» non è in questo ramo.
- Dimostrazione: alcune serie hanno un video in seconda posizione, scelto
  dall'identificativo senza toccare la sequenza casuale.
- Prove di archivio, API, dimostrazione e interfaccia (queste ultime con
  Chromium, solo nella CI); 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 16:40:07 +01:00
1 parent 34fe5e9073
commit 30e159cbd4
23 files changed
+1126 -130

No files matched your search

+284 -5
View File
@@ -242,6 +242,11 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
ArgumentNullException.ThrowIfNull(query);
var limit = Math.Clamp(query.Limit, 1, 1000);
if (query.Mode == MosaicMode.Files)
{
return db.ReadAsync(c => QueryFiles(c, query, limit), ct);
}
return db.ReadAsync(
c =>
{
@@ -327,7 +332,35 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
ct);
}
public Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default)
public Task<int> CountLibraryFilesAsync(LibraryFilter filter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
return db.ReadAsync(
c =>
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, EntriesOfFiles(filter));
var counts = FileCounts(c, filter);
if (counts is null)
{
command.CommandText = $"SELECT COALESCE(SUM({FilesOfEntry(filter)}), 0) FROM entry e WHERE {where}";
return (int)command.ScalarInt64();
}
command.CommandText = $"SELECT e.id FROM entry e WHERE {where}";
var total = 0;
using var r = command.ExecuteReader();
while (r.Read())
{
total += counts.GetValueOrDefault(r.GetInt64(0));
}
return total;
},
ct);
}
public Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
ArgumentNullException.ThrowIfNull(zone);
@@ -337,8 +370,15 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// Stream the publication times in index order and fold them into local days here: no time zone logic
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at";
var files = mode == MosaicMode.Files;
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter);
var counts = files ? FileCounts(c, filter) : null;
var perEntry = files && counts is null;
command.CommandText = !files
? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"
: perEntry
? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at"
: $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at";
var days = new List<DayCount>();
long dayStart = long.MaxValue, dayEnd = long.MinValue;
DateOnly day = default;
@@ -360,7 +400,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
(dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0);
}
count++;
count += !files ? 1 : perEntry ? r.GetInt32(1) : counts!.GetValueOrDefault(r.GetInt64(1));
}
}
@@ -403,6 +443,243 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
return entryIds.Where(byId.ContainsKey).Select(id => byId[id]).ToList();
}
// --------------------------------------------------------------------------------------------- «Tutte le foto»
/// <summary>The files of «Tutte le foto» on <c>media m</c>: those in the library, of the kind of «Foto» or «Video».</summary>
private static string FileTerms(LibraryFilter filter) =>
// The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index.
"+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch
{
LibraryKindFilter.Photos => " AND m.kind = 'Photo'",
LibraryKindFilter.Videos => " AND m.kind = 'Video'",
_ => string.Empty,
};
/// <summary>
/// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a
/// count per entry would cost a subquery for each of 200,000 rows (over a second), this a tenth of that. With a
/// filter on accounts the entries are few and are counted one by one instead (null).
/// </summary>
private static Dictionary<long, int>? FileCounts(SqliteConnection c, LibraryFilter filter)
{
if (filter.AccountIds is { Count: > 0 })
{
return null;
}
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id");
var counts = new Dictionary<long, int>();
using var r = command.ExecuteReader();
while (r.Read())
{
counts[r.GetInt64(0)] = r.GetInt32(1);
}
return counts;
}
/// <summary>
/// The entries whose files a count of «Tutte le foto» adds up: for «Foto» and «Video» every post, since the kind of
/// the files already decides (a post without videos adds 0) and the EXISTS per post of the grouped filter would cost
/// a second over 200,000 entries.
/// </summary>
private static LibraryFilter EntriesOfFiles(LibraryFilter filter) =>
filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter;
/// <summary>A correlated count of the files of «Tutte le foto» of the entry <c>e</c>.</summary>
private static string FilesOfEntry(LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})";
/// <summary>
/// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as
/// the grouped mosaic (so it stays as fast over 200,000 entries), then their files are read by key and laid out in
/// order, entry by entry and each by position. More entries are read only when those had too few files.
/// </summary>
private static LibraryPage QueryFiles(SqliteConnection c, LibraryQuery query, int limit)
{
var newer = query.Direction == LibraryDirection.Newer;
var wanted = limit + 1;
var files = new List<FileRow>(wanted);
var cursor = query.Cursor;
var from = cursor;
// The first read includes the entry of the cursor, for its files after (or before) the cursor's position.
var inclusive = true;
while (files.Count < wanted)
{
var keys = EntryKeys(c, query.Filter, from, newer, inclusive, wanted);
if (keys.Count == 0)
{
break;
}
var byEntry = FilesOf(c, keys.Select(k => k.Id).ToList(), query.Filter);
foreach (var (id, _) in keys)
{
if (!byEntry.TryGetValue(id, out var list))
{
continue;
}
for (var i = 0; i < list.Count && files.Count < wanted; i++)
{
var file = list[newer ? list.Count - 1 - i : i];
if (cursor is { } at && at.EntryId == id && (newer ? file.Position >= at.Position : file.Position <= at.Position))
{
continue;
}
files.Add(file);
}
if (files.Count == wanted)
{
break;
}
}
if (keys.Count < wanted)
{
break;
}
from = new LibraryCursor(Sql.ToTime(keys[^1].PublishedAt), keys[^1].Id);
inclusive = false;
}
var moreInDirection = files.Count > limit;
if (moreInDirection)
{
files.RemoveAt(files.Count - 1);
}
if (newer)
{
files.Reverse();
}
var entries = TilesOf(c, files.Select(f => f.EntryId).Distinct().ToList()).ToDictionary(t => t.EntryId);
var tiles = new List<LibraryTile>(files.Count);
foreach (var f in files)
{
if (entries.TryGetValue(f.EntryId, out var entry))
{
tiles.Add(entry with
{
CoverMediaId = f.MediaId,
CoverKind = f.Kind,
CoverWidth = f.Width,
CoverHeight = f.Height,
CoverDuration = f.Duration,
CoverSha256 = f.Sha256,
CoverHasThumbnail = f.HasThumbnail,
FilePosition = f.Position,
});
}
}
if (tiles.Count == 0)
{
return new LibraryPage(tiles, null, null);
}
var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId, tiles[0].FilePosition ?? 0);
var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId, tiles[^1].FilePosition ?? 0);
bool hasOlder, hasNewer;
if (newer)
{
hasNewer = moreInDirection;
hasOlder = FileExists(c, query.Filter, last, older: true);
}
else
{
hasOlder = moreInDirection;
hasNewer = cursor is not null && FileExists(c, query.Filter, first, older: false);
}
return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null);
}
/// <summary>Keys of the entries of a filter from a cursor, in the order of the direction (the grouped keyset scan).</summary>
private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}");
if (cursor is { } at)
{
var op = (newer, inclusive) switch { (true, true) => ">=", (true, false) => ">", (false, true) => "<=", _ => "<" };
sql.Append(" AND (e.published_at, e.id) ").Append(op).Append(" (@cp, @ci)");
command.With("@cp", Sql.Time(at.PublishedAt)).With("@ci", at.EntryId);
}
var order = string.IsNullOrWhiteSpace(filter.Search) ? "e.published_at" : "+e.published_at";
sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC");
sql.Append(" LIMIT @limit");
command.With("@limit", (long)limit);
command.CommandText = sql.ToString();
var keys = new List<(long, long)>(limit);
using var r = command.ExecuteReader();
while (r.Read())
{
keys.Add((r.GetInt64(0), r.GetInt64(1)));
}
return keys;
}
/// <summary>The files of «Tutte le foto» of the given entries, each list by position.</summary>
private static Dictionary<long, List<FileRow>> FilesOf(SqliteConnection c, IReadOnlyList<long> entryIds, LibraryFilter filter)
{
var byEntry = new Dictionary<long, List<FileRow>>(entryIds.Count);
foreach (var chunk in entryIds.Chunk(500))
{
using var command = c.Command(string.Empty);
var list = command.AddList("f", chunk);
command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail "
+ $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position";
using var r = command.ExecuteReader();
while (r.Read())
{
var row = new FileRow(
r.GetInt64(0),
r.GetInt64(1),
r.GetInt32(2),
r.GetEnum<MediaKind>(3),
r.GetInt32OrNull(4),
r.GetInt32OrNull(5),
r.GetDurationOrNull(6),
r.GetTextOrNull(7),
r.GetBool(8));
if (!byEntry.TryGetValue(row.EntryId, out var files))
{
byEntry[row.EntryId] = files = [];
}
files.Add(row);
}
}
return byEntry;
}
/// <summary>Whether «Tutte le foto» has a file after (older) or before (newer) a cursor.</summary>
private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var terms = FileTerms(filter);
command.CommandText =
$"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} "
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) "
+ $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) "
+ $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))";
command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position);
return command.ScalarInt64() != 0;
}
/// <summary>A file of «Tutte le foto»: what its tile needs.</summary>
private readonly record struct FileRow(long EntryId, long MediaId, int Position, MediaKind Kind, int? Width, int? Height, TimeSpan? Duration, string? Sha256, bool HasThumbnail);
private static void Validate(Entry entry, IReadOnlyList<Media> media)
{
ArgumentNullException.ThrowIfNull(entry);
@@ -492,7 +769,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
parts.Add(filter.Kind switch
{
LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')",
LibraryKindFilter.Posts => "e.kind = 'Post'",
// Like «Tutto», a broad term: on the kind index every post would need its table row for the state (most of
// the library); the publication index already holds kind and state.
LibraryKindFilter.Posts => "+e.kind = 'Post'",
LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')",
LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')",
LibraryKindFilter.Stories => "e.kind = 'Story'",