Files
Febe/src/Febe.Data/Stores/EntryStore.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:30:33 +01:00

947 lines
44 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) => MarkDeletedAsync(entryId, at, [], ct);
/// <summary>
/// «Eliminato» inside the caller's transaction: the entry, its files without path, and the conversions for the
/// library of its files (tappa E3) with nothing left to convert or retry (Pending, Failed) go.
/// </summary>
private static void MarkDeleted(WriteContext w, long entryId, DateTimeOffset at)
{
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();
w.Command("""
DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed') AND media_id IN (SELECT id FROM media WHERE entry_id = @id)
""").With("@id", entryId).ExecuteNonQuery();
}
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(removedConversionIds);
var removed = removedConversionIds.Distinct().ToList();
return db.WriteAsync(
w =>
{
MarkDeleted(w, entryId, at);
// The converted files that go (or are gone) are «Tolto», the others stay as they are.
if (removed.Count > 0)
{
var own = new HashSet<long>();
using (var r = w.Command("SELECT mc.id FROM media_conversion mc JOIN media m ON m.id = mc.media_id WHERE m.entry_id = @id")
.With("@id", entryId).ExecuteReader())
{
while (r.Read())
{
own.Add(r.GetInt64(0));
}
}
MediaConversionStore.MarkRemoved(w, removed.Where(own.Contains).ToList(), at);
}
},
ct);
}
public Task<IReadOnlyList<MediaConversion>> MarkDeletedWithConversionsAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync<IReadOnlyList<MediaConversion>>(
w =>
{
var withFiles = new List<MediaConversion>();
using (var r = w.Command($"""
SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
WHERE m.entry_id = @id AND mc.state IN ('Converted', 'Superseded') ORDER BY mc.media_id, mc.id
""").With("@id", entryId).ExecuteReader())
{
while (r.Read())
{
withFiles.Add(MediaConversionStore.ReadRow(r));
}
}
MarkDeleted(w, entryId, at);
MediaConversionStore.MarkRemoved(w, withFiles.Select(c => c.Id).ToList(), at);
return withFiles;
},
ct);
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
MediaConversionStore.DeleteRowsWithoutFile(w, entryId);
try
{
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
}
catch (SqliteException ex) when (ex.IsConstraintViolation())
{
// ON DELETE RESTRICT of media_conversion: a converted file of the library would lose its record.
throw new InvalidOperationException(
"L'elemento ha file convertiti nella libreria: eliminalo con «Elimina dalla libreria», che toglie anche quelli.", ex);
}
},
ct);
public Task<IReadOnlyList<MediaConversion>> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync<IReadOnlyList<MediaConversion>>(
w =>
{
var list = new List<MediaConversion>();
using (var r = w.Command($"""
SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
WHERE m.entry_id = @id ORDER BY mc.media_id, mc.id
""").With("@id", entryId).ExecuteReader())
{
while (r.Read())
{
list.Add(MediaConversionStore.ReadRow(r));
}
}
w.Command("DELETE FROM media_conversion WHERE media_id IN (SELECT id FROM media WHERE entry_id = @id)").With("@id", entryId).ExecuteNonQuery();
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
return list;
},
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, aggregate: true);
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<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 counts = files ? FileCounts(c, filter) : null;
// With the counts of every entry the «Copie» term of the entries adds nothing (an entry without files
// of the class counts 0) and would test each file a second time, once per entry.
var entries = !files ? filter : counts is null ? EntriesOfFiles(filter) : EntriesOfFiles(filter) with { Copies = null };
var where = BuildWhere(c, command, entries, aggregate: true, files: files);
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(c, 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», and of the
/// class of the «Copie» filter. With «Copie» the term reads the entry <c>e</c> of the file too (account and kind), so
/// the caller must have it in scope (<see cref="NeedsEntry"/>).
/// </summary>
/// <param name="c">The connection (for the export tables of «Copie»).</param>
/// <param name="filter">The filter.</param>
/// <param name="bulk">The terms are read on every file of the library (the counts per entry): see ExportFilterSql.FileTerm.</param>
internal static string FileTerms(SqliteConnection c, LibraryFilter filter, bool bulk = false) =>
// 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,
} + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies, bulk) : string.Empty);
/// <summary>The file terms of this filter read the entry of the file (the «Copie» filter).</summary>
private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null;
/// <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;
}
var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m";
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter, bulk: true)} 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(SqliteConnection c, LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(c, 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, files: true);
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);
var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m";
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 {from} WHERE m.entry_id IN ({list}) AND {FileTerms(c, 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, files: true);
var terms = FileTerms(c, filter);
var position = older ? ">" : "<";
// With «Copie» the file terms read the entry: the first branch then joins it instead of testing it apart.
var first = NeedsEntry(filter)
? $"SELECT EXISTS (SELECT 1 FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} AND {where}) "
: $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} "
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) ";
command.CommandText =
first
+ $"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>
/// <param name="c">The connection (for the accounts of a search and the export tables of «Copie»).</param>
/// <param name="command">The command that gets the parameters.</param>
/// <param name="filter">The filter.</param>
/// <param name="files">
/// «Tutte le foto»: «Copie» keeps an entry when one of its files is of the chosen class, rather than judging the entry
/// as a whole (all its due files copied, for «Copiati»).
/// </param>
/// <param name="aggregate">
/// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and
/// «Video» then test the key of each post, on a covering index, against one list of the entries that have such
/// files, read once from ix_media_entry_files (under two tenths of a second over 200,000 entries), instead of an
/// EXISTS per post (over a second: each post needs its table row). A window keeps the EXISTS: it stops after a few
/// hundred posts in index order.
/// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two.
/// </param>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false, bool files = false)
{
var byList = aggregate && filter.AccountIds is not { Count: > 0 };
// The unary + on kind and key keeps SQLite on a covering index of entry (kind, state and account in the index):
// looking up each entry of the list by key would read its table row, 0.85 s for «Foto» over 200,000 entries.
string FilesOfKind(string kind) => byList
? $"+e.kind = 'Post' AND +e.id IN (SELECT mk.entry_id FROM media mk WHERE mk.kind = '{kind}')"
: $"e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = '{kind}')";
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 => FilesOfKind("Photo"),
LibraryKindFilter.Videos => FilesOfKind("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));
}
if (filter.Copies is { } copies)
{
var export = ExportFilterSql.Load(c);
parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies, byList));
}
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);
}
}