Files
Febe/src/Febe.Data/Stores/EntryStore.cs
T
Alby96andClaude Opus 5.5 30e159cbd4 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>
2026-11-25 16:40:07 +01:00

835 lines
37 KiB
C#

using System.Text;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
using static Febe.Data.Stores.EntryMapping;
namespace Febe.Data.Stores;
internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
public Task<Entry?> GetAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadEntryById(sql => c.Command(sql), entryId), ct);
public Task<EntryWithMedia?> GetWithMediaAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var entry = ReadEntryById(sql => c.Command(sql), entryId);
return entry is null ? null : new EntryWithMedia(entry, ReadMediaOf(sql => c.Command(sql), entryId));
},
ct);
public Task<Entry?> FindAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync(c => FindIdentity(sql => c.Command(sql), accountId, kind, instagramId.Trim()), ct);
}
public async Task<bool> IsKnownAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default) =>
await FindAsync(accountId, kind, instagramId, ct).ConfigureAwait(false) is not null;
public Task<IReadOnlySet<string>> GetKnownInstagramIdsAsync(long accountId, EntryKind kind, IReadOnlyCollection<string> instagramIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(instagramIds);
var ids = instagramIds.Where(i => !string.IsNullOrWhiteSpace(i)).Select(i => i.Trim()).Distinct(StringComparer.Ordinal).ToList();
return db.ReadAsync<IReadOnlySet<string>>(
c =>
{
var known = new HashSet<string>(StringComparer.Ordinal);
foreach (var chunk in ids.Chunk(500))
{
var command = c.Command(string.Empty).With("@a", accountId).With("@k", Sql.Enum(kind));
var list = command.AddList("i", chunk);
command.CommandText = $"SELECT instagram_id FROM entry WHERE account_id = @a AND kind = @k AND instagram_id IN ({list})";
using var r = command.ExecuteReader();
while (r.Read())
{
known.Add(r.GetString(0));
}
}
return known;
},
ct);
}
public Task<IReadOnlyList<Entry>> FindByInstagramIdAsync(long accountId, string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync<IReadOnlyList<Entry>>(
c => ReadEntries(c.Command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.instagram_id = @i ORDER BY e.id")
.With("@a", accountId).With("@i", instagramId.Trim())),
ct);
}
public Task<Entry?> FindByPublicationTimeAsync(long accountId, EntryKind kind, DateTimeOffset publishedAt, TimeSpan tolerance, CancellationToken ct = default)
{
var ms = Sql.Time(publishedAt);
var tol = (long)Math.Abs(tolerance.TotalMilliseconds);
return db.ReadAsync(
c =>
{
using var r = c.Command($"""
SELECT {EntryColumns} FROM entry e
WHERE e.account_id = @a AND e.kind = @k AND e.published_at BETWEEN @from AND @to
ORDER BY abs(e.published_at - @p), e.id LIMIT 1
""")
.With("@a", accountId).With("@k", Sql.Enum(kind)).With("@from", ms - tol).With("@to", ms + tol).With("@p", ms)
.ExecuteReader();
return r.Read() ? ReadEntry(r) : null;
},
ct);
}
public Task<AddEntryResult> AddAsync(Entry entry, IReadOnlyList<Media> media, CancellationToken ct = default)
{
Validate(entry, media);
return db.WriteAsync(w => Add(w, entry, media), ct);
}
public Task<IReadOnlyList<AddEntryResult>> AddManyAsync(IReadOnlyList<NewEntry> entries, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entries);
foreach (var item in entries)
{
Validate(item.Entry, item.Media);
}
return db.WriteAsync<IReadOnlyList<AddEntryResult>>(w => entries.Select(item => Add(w, item.Entry, item.Media)).ToList(), ct);
}
public Task UpdateAsync(Entry entry, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entry);
return db.WriteAsync(
w =>
{
var c = w.Command("""
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,
is_reel = max(is_reel, @is_reel)
WHERE id = @id
""");
BindEntry(c, entry);
c.With("@id", entry.Id);
try
{
if (c.ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Elemento {entry.Id} non trovato.");
}
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException("Esiste già un elemento con lo stesso identificativo Instagram per questo account e tipo.", ex);
}
},
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 =>
{
if (w.Command("UPDATE entry SET state = @s WHERE id = @id").With("@s", Sql.Enum(state)).With("@id", entryId).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
}
},
ct);
public Task<EntryState> RecomputeStateAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync(w => RecomputeState(w, entryId), ct);
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id")
.With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery();
if (rows == 0)
{
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
}
w.Command("""
UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL
WHERE entry_id = @id
""").With("@id", entryId).ExecuteNonQuery();
},
ct);
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct);
public Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default)
{
options ??= new EntryListOptions();
return db.ReadAsync<IReadOnlyList<Entry>>(
c =>
{
var command = c.Command(string.Empty).With("@a", accountId).With("@limit", (long)Math.Clamp(options.Limit, 1, 10_000));
var sql = new StringBuilder($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a");
if (options.Kind is { } kind)
{
sql.Append(" AND e.kind = @k");
command.With("@k", Sql.Enum(kind));
}
if (options.States is { Count: > 0 } states)
{
sql.Append(" AND e.state IN (").Append(command.AddList("s", states.Select(s => s.ToString()))).Append(')');
}
if (options.Before is { } before)
{
sql.Append(" AND (e.published_at, e.id) < (@bp, @bi)");
command.With("@bp", Sql.Time(before.PublishedAt)).With("@bi", before.EntryId);
}
sql.Append(" ORDER BY e.published_at DESC, e.id DESC LIMIT @limit");
command.CommandText = sql.ToString();
return ReadEntries(command);
},
ct);
}
// The window of a recipe is a few minutes: the range on ix_entry_discovered (migration 0002) reads only those rows,
// whatever the size of the library or of the account.
private const string ArrivedWhere = """
discovered_at >= @f AND discovered_at <= @t AND (@a IS NULL OR account_id = @a) AND provenance = @p AND state <> 'Deleted'
""";
public Task<ArrivedEntries> ListDiscoveredAsync(long? accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var ids = new List<long>();
using (var r = c.Command($"""
SELECT id FROM entry WHERE {ArrivedWhere}
ORDER BY discovered_at DESC, id DESC LIMIT @l
""").With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@p", Sql.Enum(Provenance.Downloaded))
.With("@l", (long)Math.Clamp(limit, 1, 100)).ExecuteReader())
{
while (r.Read())
{
ids.Add(r.GetInt64(0));
}
}
var total = (int)c.Command($"""
SELECT COUNT(*) FROM entry WHERE {ArrivedWhere}
""").With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@p", Sql.Enum(Provenance.Downloaded)).ScalarInt64();
return new ArrivedEntries(ids, total);
},
ct);
public Task<int> CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync(
c => (int)c.Command("""
SELECT COUNT(*) FROM entry WHERE account_id = @a AND kind = @k AND discovered_at >= @f AND discovered_at < @t
""").With("@a", accountId).With("@k", Sql.Enum(kind)).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ScalarInt64(),
ct);
public Task<LibraryPage> QueryLibraryAsync(LibraryQuery query, CancellationToken ct = default)
{
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 =>
{
// Phase 1: keys only, so that sorting never computes the tile columns of rows outside the window.
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, query.Filter);
var newer = query.Direction == LibraryDirection.Newer;
var sql = new StringBuilder($"SELECT e.id FROM entry e WHERE {where}");
if (query.Cursor is { } cursor)
{
sql.Append(newer ? " AND (e.published_at, e.id) > (@cp, @ci)" : " AND (e.published_at, e.id) < (@cp, @ci)");
command.With("@cp", Sql.Time(cursor.PublishedAt)).With("@ci", cursor.EntryId);
}
// With a text search the whole table is scanned and the matches sorted: about a tenth of a second on
// 200,000 entries whether the word is rare or common, instead of walking the index row by row.
var order = string.IsNullOrWhiteSpace(query.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 + 1);
command.CommandText = sql.ToString();
var ids = new List<long>(limit + 1);
using (var r = command.ExecuteReader())
{
while (r.Read())
{
ids.Add(r.GetInt64(0));
}
}
var moreInDirection = ids.Count > limit;
if (moreInDirection)
{
ids.RemoveAt(ids.Count - 1);
}
if (newer)
{
ids.Reverse();
}
// Phase 2: the tiles of the window, in display order.
var tiles = TilesOf(c, ids);
if (tiles.Count == 0)
{
return new LibraryPage(tiles, null, null);
}
var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId);
var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId);
bool hasOlder, hasNewer;
if (newer)
{
hasNewer = moreInDirection;
hasOlder = Exists(c, query.Filter, last, older: true);
}
else
{
hasOlder = moreInDirection;
hasNewer = query.Cursor is not null && Exists(c, query.Filter, first, older: false);
}
return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null);
},
ct);
}
public Task<LibraryTotals> GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
return db.ReadAsync(
c =>
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entry e WHERE {where}";
using var r = command.ExecuteReader();
r.Read();
return new LibraryTotals(r.GetInt32(0), r.GetInt32(1));
},
ct);
}
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);
return db.ReadAsync<IReadOnlyList<DayCount>>(
c =>
{
// 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 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;
var count = 0;
using (var r = command.ExecuteReader())
{
while (r.Read())
{
var ms = r.GetInt64(0);
if (ms < dayStart || ms >= dayEnd)
{
if (count > 0)
{
days.Add(new DayCount(day, count));
}
day = LocalCalendar.Today(Sql.ToTime(ms), zone);
var (start, end) = LocalCalendar.DayBounds(day, zone);
(dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0);
}
count += !files ? 1 : perEntry ? r.GetInt32(1) : counts!.GetValueOrDefault(r.GetInt64(1));
}
}
if (count > 0)
{
days.Add(new DayCount(day, count));
}
days.Reverse();
return days;
},
ct);
}
public Task<IReadOnlyList<LibraryTile>> GetTilesAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIds);
return db.ReadAsync<IReadOnlyList<LibraryTile>>(c => TilesOf(c, entryIds), ct);
}
// ---------------------------------------------------------------------------------------------
/// <summary>Tiles of the given entries, in the given order (unknown keys are skipped).</summary>
private static List<LibraryTile> TilesOf(SqliteConnection c, IReadOnlyList<long> entryIds)
{
var byId = new Dictionary<long, LibraryTile>(entryIds.Count);
foreach (var chunk in entryIds.Distinct().Chunk(500))
{
using var command = c.Command(string.Empty);
var list = command.AddList("i", chunk);
command.CommandText = $"SELECT {TileColumns} {TileFrom} WHERE e.id IN ({list})";
using var r = command.ExecuteReader();
while (r.Read())
{
var tile = ReadTile(r);
byId[tile.EntryId] = tile;
}
}
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);
ArgumentNullException.ThrowIfNull(media);
if (media.Select(m => m.Position).Distinct().Count() != media.Count)
{
throw new ArgumentException("Le posizioni dei file di un elemento devono essere distinte.", nameof(media));
}
if (media.Any(m => m.Position < 1))
{
throw new ArgumentException("Le posizioni dei file partono da 1.", nameof(media));
}
}
private static AddEntryResult Add(WriteContext w, Entry entry, IReadOnlyList<Media> media)
{
var instagramId = NormalizeId(entry.InstagramId);
if (instagramId is not null && FindIdentity(w.Command, entry.AccountId, entry.Kind, instagramId) is { } existing)
{
return new AddEntryResult(new EntryWithMedia(existing, ReadMediaOf(w.Command, existing.Id)), false);
}
var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, media.Select(m => m.State).ToList());
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, 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, @is_reel)
""");
BindEntry(insert, stored);
insert.ExecuteNonQuery();
var entryId = w.LastInsertRowId();
stored = stored with { Id = entryId };
var files = new List<Media>(media.Count);
foreach (var file in media.OrderBy(m => m.Position))
{
var row = file with { EntryId = entryId, Sha256 = file.Sha256?.ToLowerInvariant(), InstagramId = NormalizeId(file.InstagramId) };
var command = w.Command(InsertMediaSql);
BindMedia(command, row);
command.ExecuteNonQuery();
files.Add(row with { Id = w.LastInsertRowId() });
}
return new AddEntryResult(new EntryWithMedia(stored, files), true);
}
private static Entry? FindIdentity(Func<string, SqliteCommand> command, long accountId, EntryKind kind, string instagramId)
{
using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.kind = @k AND e.instagram_id = @i")
.With("@a", accountId).With("@k", Sql.Enum(kind)).With("@i", instagramId).ExecuteReader();
return r.Read() ? ReadEntry(r) : null;
}
private static List<Entry> ReadEntries(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<Entry>();
while (r.Read())
{
list.Add(ReadEntry(r));
}
return list;
}
private static bool Exists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi))";
command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId);
return command.ScalarInt64() != 0;
}
/// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter)
{
var parts = new List<string>();
var states = filter.States is { Count: > 0 } s ? s : EntryStateRules.Visible;
// The unary + keeps SQLite from using the state and kind indexes for these broad terms: the keyset scan of the
// publication index is what keeps a window fast over 200,000 entries, with or without ANALYZE statistics.
parts.Add($"+e.state IN ({command.AddList("st", states.Select(x => x.ToString()))})");
parts.Add(filter.Kind switch
{
LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')",
// 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'",
LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))",
LibraryKindFilter.Tagged => "e.kind = 'Tagged'",
LibraryKindFilter.ProfilePictures => "e.kind = 'ProfilePicture'",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter.Kind, null),
});
if (filter.AccountIds is { } accounts)
{
parts.Add($"e.account_id IN ({command.AddList("ac", accounts)})");
}
if (filter.From is { } from)
{
parts.Add("e.published_at >= @from");
command.With("@from", Sql.Time(from));
}
if (filter.To is { } to)
{
parts.Add("e.published_at < @to");
command.With("@to", Sql.Time(to));
}
if (filter.Provenance is { } provenance)
{
parts.Add("e.provenance = @prov");
command.With("@prov", Sql.Enum(provenance));
}
var term = TextSearch.Normalize(filter.Search);
if (term.Length > 0)
{
// Accounts are few: match their names here, accent-insensitively, then filter entries by key.
var matching = new List<long>();
using (var r = c.Command("SELECT id, username, display_name FROM account").ExecuteReader())
{
while (r.Read())
{
var name = TextSearch.Normalize(r.GetString(1));
var display = TextSearch.Normalize(r.GetTextOrNull(2));
var bare = term.TrimStart('@');
if (name.Contains(bare, StringComparison.Ordinal) || display.Contains(term, StringComparison.Ordinal))
{
matching.Add(r.GetInt64(0));
}
}
}
command.With("@q", TextSearch.LikePattern(term));
parts.Add(matching.Count == 0
? "e.search_text LIKE @q ESCAPE '\\'"
: $"(e.search_text LIKE @q ESCAPE '\\' OR e.account_id IN ({command.AddList("sa", matching)}))");
}
return string.Join(" AND ", parts);
}
}