using Febe.Core.Domain; using Febe.Core.Library; using Microsoft.Data.Sqlite; namespace Febe.Data.Stores; /// Column lists and readers shared by the entry, media and highlight stores. 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"; public const int EntryColumnCount = 15; 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, " + "m.sha256, m.phash, m.has_thumbnail, m.source_url, m.cover_url, m.source_seen_at, m.attempts, m.last_error, m.downloaded_at"; public const int MediaColumnCount = 20; /// /// Tile columns; the query must join media c (the cover, see ). The user name is a /// correlated subquery on purpose: with a join, SQLite (with ANALYZE statistics) drives the query from the small /// account table and sorts every entry, which costs a second on 200,000 entries instead of a millisecond. /// public const string TileColumns = "e.id, e.account_id, (SELECT a.username FROM account a WHERE a.id = e.account_id), e.kind, e.published_at, e.state, e.provenance, " + "(SELECT COUNT(*) FROM media mc WHERE mc.entry_id = e.id), " + "c.id, c.kind, c.width, c.height, c.duration_ms, c.sha256, c.has_thumbnail"; /// The cover is the first file present, or the first file. public const string TileFrom = "FROM entry e " + "LEFT JOIN media c ON c.id = (SELECT m1.id FROM media m1 WHERE m1.entry_id = e.id " + "ORDER BY (m1.state IN ('Downloaded', 'Imported')) DESC, m1.position LIMIT 1)"; public static readonly string VisibleStates = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'")); public static Entry ReadEntry(SqliteDataReader r, int o = 0) => new() { Id = r.GetInt64(o), AccountId = r.GetInt64(o + 1), Kind = r.GetEnum(o + 2), InstagramId = r.GetTextOrNull(o + 3), Code = r.GetTextOrNull(o + 4), PublishedAt = r.GetTime(o + 5), Caption = r.GetTextOrNull(o + 6), AuthorUsername = r.GetTextOrNull(o + 7), AuthorInstagramId = r.GetTextOrNull(o + 8), State = r.GetEnum(o + 9), Provenance = r.GetEnum(o + 10), DiscoveredAt = r.GetTime(o + 11), DownloadedAt = r.GetTimeOrNull(o + 12), DeletedAt = r.GetTimeOrNull(o + 13), ExpiresAt = r.GetTimeOrNull(o + 14), }; public static Media ReadMedia(SqliteDataReader r, int o = 0) => new() { Id = r.GetInt64(o), EntryId = r.GetInt64(o + 1), Position = r.GetInt32(o + 2), Kind = r.GetEnum(o + 3), InstagramId = r.GetTextOrNull(o + 4), Width = r.GetInt32OrNull(o + 5), Height = r.GetInt32OrNull(o + 6), Duration = r.GetDurationOrNull(o + 7), State = r.GetEnum(o + 8), RelativePath = r.GetTextOrNull(o + 9), Bytes = r.GetInt64OrNull(o + 10), Sha256 = r.GetTextOrNull(o + 11), PerceptualHash = r.GetHashOrNull(o + 12), HasThumbnail = r.GetBool(o + 13), SourceUrl = r.GetTextOrNull(o + 14), CoverUrl = r.GetTextOrNull(o + 15), SourceSeenAt = r.GetTimeOrNull(o + 16), Attempts = r.GetInt32(o + 17), LastError = r.GetTextOrNull(o + 18), DownloadedAt = r.GetTimeOrNull(o + 19), }; public static Core.Storage.LibraryTile ReadTile(SqliteDataReader r) => new( EntryId: r.GetInt64(0), AccountId: r.GetInt64(1), Username: r.GetString(2), Kind: r.GetEnum(3), PublishedAt: r.GetTime(4), State: r.GetEnum(5), Provenance: r.GetEnum(6), MediaCount: r.GetInt32(7), CoverMediaId: r.GetInt64OrNull(8), CoverKind: r.GetEnumOrNull(9), CoverWidth: r.GetInt32OrNull(10), CoverHeight: r.GetInt32OrNull(11), CoverDuration: r.GetDurationOrNull(12), CoverSha256: r.GetTextOrNull(13), CoverHasThumbnail: !r.IsDBNull(14) && r.GetBool(14)); public static void BindEntry(SqliteCommand c, Entry e) => c.With("@account_id", e.AccountId) .With("@kind", Sql.Enum(e.Kind)) .With("@instagram_id", Sql.Text(NormalizeId(e.InstagramId))) .With("@code", Sql.Text(e.Code)) .With("@published_at", Sql.Time(e.PublishedAt)) .With("@caption", Sql.Text(e.Caption)) .With("@author_username", Sql.Text(e.AuthorUsername)) .With("@author_instagram_id", Sql.Text(e.AuthorInstagramId)) .With("@state", Sql.Enum(e.State)) .With("@provenance", Sql.Enum(e.Provenance)) .With("@discovered_at", Sql.Time(e.DiscoveredAt)) .With("@downloaded_at", Sql.Time(e.DownloadedAt)) .With("@deleted_at", Sql.Time(e.DeletedAt)) .With("@expires_at", Sql.Time(e.ExpiresAt)) .With("@search_text", TextSearch.ForEntry(e.Caption, e.AuthorUsername)); public static void BindMedia(SqliteCommand c, Media m) => c.With("@entry_id", m.EntryId) .With("@position", (long)m.Position) .With("@kind", Sql.Enum(m.Kind)) .With("@instagram_id", Sql.Text(NormalizeId(m.InstagramId))) .With("@width", Sql.Int(m.Width)) .With("@height", Sql.Int(m.Height)) .With("@duration_ms", Sql.Duration(m.Duration)) .With("@state", Sql.Enum(m.State)) .With("@relative_path", Sql.Text(m.RelativePath)) .With("@bytes", Sql.Int(m.Bytes)) .With("@sha256", Sql.Text(m.Sha256?.ToLowerInvariant())) .With("@phash", Sql.Hash(m.PerceptualHash)) .With("@has_thumbnail", Sql.Bool(m.HasThumbnail)) .With("@source_url", Sql.Text(m.SourceUrl)) .With("@cover_url", Sql.Text(m.CoverUrl)) .With("@source_seen_at", Sql.Time(m.SourceSeenAt)) .With("@attempts", (long)m.Attempts) .With("@last_error", Sql.Text(m.LastError)) .With("@downloaded_at", Sql.Time(m.DownloadedAt)); public const string InsertMediaSql = """ INSERT INTO media (entry_id, position, kind, instagram_id, width, height, duration_ms, state, relative_path, bytes, sha256, phash, has_thumbnail, source_url, cover_url, source_seen_at, attempts, last_error, downloaded_at) VALUES (@entry_id, @position, @kind, @instagram_id, @width, @height, @duration_ms, @state, @relative_path, @bytes, @sha256, @phash, @has_thumbnail, @source_url, @cover_url, @source_seen_at, @attempts, @last_error, @downloaded_at) """; public static string? NormalizeId(string? id) => string.IsNullOrWhiteSpace(id) ? null : id.Trim(); /// Files of an entry; creates (or reuses) a command for a SQL text. public static List ReadMediaOf(Func command, long entryId) { using var r = command($"SELECT {MediaColumns} FROM media m WHERE m.entry_id = @e ORDER BY m.position") .With("@e", entryId).ExecuteReader(); var list = new List(); while (r.Read()) { list.Add(ReadMedia(r)); } return list; } public static Entry? ReadEntryById(Func command, long entryId) { using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.id = @id").With("@id", entryId).ExecuteReader(); return r.Read() ? ReadEntry(r) : null; } /// Recomputes and stores the state of an entry from its files. Returns the new state. public static EntryState RecomputeState(WriteContext w, long entryId, DateTimeOffset? downloadedAt = null) { var entry = ReadEntryById(w.Command, entryId) ?? throw new KeyNotFoundException($"Elemento {entryId} non trovato."); var states = new List(); using (var r = w.Command("SELECT state FROM media WHERE entry_id = @e").With("@e", entryId).ExecuteReader()) { while (r.Read()) { states.Add(r.GetEnum(0)); } } var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, states); var becameComplete = state is EntryState.Downloaded or EntryState.Imported && entry.DownloadedAt is null; w.Command("UPDATE entry SET state = @s, downloaded_at = CASE WHEN @c = 1 THEN @d ELSE downloaded_at END WHERE id = @id") .With("@s", Sql.Enum(state)) .With("@c", becameComplete && downloadedAt is not null ? 1L : 0L) .With("@d", Sql.Time(downloadedAt)) .With("@id", entryId) .ExecuteNonQuery(); return state; } }