using Febe.Core.Domain; using Febe.Core.Library; using Febe.Core.Storage; using Microsoft.Data.Sqlite; namespace Febe.Data.Stores; internal sealed class AccountStore(FebeDatabase db) : IAccountStore { internal const string Columns = "a.id, a.instagram_id, a.username, a.display_name, a.is_private, a.is_followed, a.is_mine, a.state, a.state_changed_at, " + "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.download_order"; internal const int ColumnCount = 35; private static readonly string Visible = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'")); internal static Account Read(SqliteDataReader r, int o = 0) => new() { Id = r.GetInt64(o), InstagramId = r.GetTextOrNull(o + 1), Username = r.GetString(o + 2), DisplayName = r.GetTextOrNull(o + 3), IsPrivate = r.GetBool(o + 4), IsFollowed = r.GetBool(o + 5), IsMine = r.GetBool(o + 6), State = r.GetEnum(o + 7), StateChangedAt = r.GetTimeOrNull(o + 8), UnreachableReason = r.GetEnumOrNull(o + 9), KeepUpdated = r.GetBool(o + 10), Frequency = r.GetEnum(o + 11), CustomPostInterval = r.GetMinutesOrNull(o + 12), CustomStoryInterval = r.GetMinutesOrNull(o + 13), ContentTypes = (ContentTypes)r.GetInt32(o + 14), Limits = new AccountLimits { Depth = r.GetEnum(o + 15), LastPosts = r.GetInt32OrNull(o + 16), FromDate = r.GetTimeOrNull(o + 17), BackfillPostsPerDay = r.GetInt32(o + 18), MaxVideoBytes = r.GetInt64OrNull(o + 19), StoryVideos = r.GetBool(o + 20), }, Folder = r.GetTextOrNull(o + 21), BackfillCursor = r.GetTextOrNull(o + 22), BackfillCompletedAt = r.GetTimeOrNull(o + 23), PostCount = r.GetInt32OrNull(o + 24), LastProfileCheckAt = r.GetTimeOrNull(o + 25), NextProfileCheckAt = r.GetTimeOrNull(o + 26), LastStoriesCheckAt = r.GetTimeOrNull(o + 27), NextStoriesCheckAt = r.GetTimeOrNull(o + 28), Notices = (AccountNotices)r.GetInt32(o + 29), PreviousUsername = r.GetTextOrNull(o + 30), 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) { c.With("@instagram_id", Sql.Text(Normalize(a.InstagramId))) .With("@username", NormalizeUsername(a.Username)) .With("@display_name", Sql.Text(a.DisplayName)) .With("@is_private", Sql.Bool(a.IsPrivate)) .With("@is_followed", Sql.Bool(a.IsFollowed)) .With("@is_mine", Sql.Bool(a.IsMine)) .With("@state", Sql.Enum(a.State)) .With("@state_changed_at", Sql.Time(a.StateChangedAt)) .With("@unreachable_reason", Sql.Enum(a.UnreachableReason)) .With("@keep_updated", Sql.Bool(a.KeepUpdated)) .With("@frequency", Sql.Enum(a.Frequency)) .With("@custom_post_interval_min", Sql.Minutes(a.CustomPostInterval)) .With("@custom_story_interval_min", Sql.Minutes(a.CustomStoryInterval)) .With("@content_types", (long)a.ContentTypes) .With("@history_depth", Sql.Enum(a.Limits.Depth)) .With("@history_last_posts", Sql.Int(a.Limits.LastPosts)) .With("@history_from", Sql.Time(a.Limits.FromDate)) .With("@backfill_posts_per_day", (long)a.Limits.BackfillPostsPerDay) .With("@max_video_bytes", Sql.Int(a.Limits.MaxVideoBytes)) .With("@story_videos", Sql.Bool(a.Limits.StoryVideos)) .With("@folder", Sql.Text(a.Folder)) .With("@backfill_cursor", Sql.Text(a.BackfillCursor)) .With("@backfill_completed_at", Sql.Time(a.BackfillCompletedAt)) .With("@post_count", Sql.Int(a.PostCount)) .With("@last_profile_check_at", Sql.Time(a.LastProfileCheckAt)) .With("@next_profile_check_at", Sql.Time(a.NextProfileCheckAt)) .With("@last_stories_check_at", Sql.Time(a.LastStoriesCheckAt)) .With("@next_stories_check_at", Sql.Time(a.NextStoriesCheckAt)) .With("@notices", (long)a.Notices) .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("@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); ArgumentException.ThrowIfNullOrWhiteSpace(account.Username); if (account.Limits.BackfillPostsPerDay < 0) { throw new ArgumentException("Il massimo di storico al giorno non può essere negativo.", nameof(account)); } if (account.Frequency == Frequency.Custom && (account.CustomPostInterval is null || account.CustomStoryInterval is null)) { throw new ArgumentException("Con la frequenza «Su misura» servono i due intervalli.", nameof(account)); } } public Task GetAsync(long accountId, CancellationToken ct = default) => db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.id = @id").With("@id", accountId)), ct); public Task FindByInstagramIdAsync(string instagramId, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(instagramId); return db.ReadAsync( c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.instagram_id = @id").With("@id", instagramId.Trim())), ct); } public Task FindByUsernameAsync(string username, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(username); var name = username.Trim().TrimStart('@'); return db.ReadAsync( c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.username = @u ORDER BY a.id LIMIT 1").With("@u", name)), ct); } public Task GetMineAsync(CancellationToken ct = default) => db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.is_mine = 1")), ct); public Task> ListAsync(CancellationToken ct = default) => db.ReadAsync>( c => { using var r = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader(); var list = new List(); while (r.Read()) { list.Add(Read(r)); } return list; }, ct); public Task> ListDownloadOrdersAsync(CancellationToken ct = default) => db.ReadAsync>( c => { using var r = c.Command("SELECT id, download_order FROM account WHERE download_order IS NOT NULL").ExecuteReader(); var orders = new Dictionary(); while (r.Read()) { orders[r.GetInt64(0)] = r.GetString(1); } return orders; }, ct); public Task> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default) => db.ReadAsync>( c => { // One pass over the (account, kind, state, discovered) index for every account at once. var counts = new Dictionary(); var sql = $""" SELECT e.account_id, SUM(e.kind <> 'ProfilePicture' AND e.state IN ({Visible})), SUM(e.kind = 'Post' AND e.state IN ({Visible})), SUM(e.kind = 'Post' AND e.discovered_at >= @since), SUM(e.kind = 'Story' AND e.discovered_at >= @since) FROM entry e GROUP BY e.account_id """; using (var r = c.Command(sql).With("@since", Sql.Time(newSince)).ExecuteReader()) { while (r.Read()) { counts[r.GetInt64(0)] = (r.GetInt32(1), r.GetInt32(2), r.GetInt32(3), r.GetInt32(4)); } } using var accounts = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader(); var list = new List(); while (accounts.Read()) { var account = Read(accounts); var (entries, posts, newPosts, newStories) = counts.GetValueOrDefault(account.Id); list.Add(new AccountSummary(account, entries, posts, newPosts, newStories)); } return list; }, ct); public Task GetStatsAsync(long accountId, CancellationToken ct = default) => db.ReadAsync( c => { var sql = $""" SELECT e.kind, COUNT(*), MAX(e.published_at) FROM entry e WHERE e.account_id = @a AND e.state IN ({Visible}) GROUP BY e.kind """; var stats = new AccountStats { AccountId = accountId }; DateTimeOffset? last = null; using (var r = c.Command(sql).With("@a", accountId).ExecuteReader()) { while (r.Read()) { var kind = r.GetEnum(0); var count = r.GetInt32(1); var max = r.GetTimeOrNull(2); stats = kind switch { EntryKind.Post => stats with { Posts = count }, EntryKind.Story => stats with { Stories = count }, EntryKind.Highlight => stats with { HighlightItems = count }, EntryKind.Tagged => stats with { Tagged = count }, EntryKind.ProfilePicture => stats with { ProfilePictures = count }, _ => stats, }; if (kind != EntryKind.ProfilePicture && max is { } m && (last is null || m > last)) { last = m; } } } // One pass over the account's files, driven from its entries (CROSS JOIN keeps entry as the outer loop): // without ANALYZE statistics SQLite otherwise starts from the media state index and reads the files of // the whole library for one account's card (#46). long bytes, pending; using (var r = c.Command(""" SELECT COALESCE(SUM(CASE WHEN m.state IN ('Downloaded', 'Imported') THEN m.bytes END), 0), COALESCE(SUM(m.state IN ('ToDownload', 'Expired')), 0) FROM entry e CROSS JOIN media m ON m.entry_id = e.id WHERE e.account_id = @a """).With("@a", accountId).ExecuteReader()) { r.Read(); bytes = r.GetInt64(0); pending = r.GetInt64(1); } var collections = c.Command("SELECT COUNT(*) FROM highlight WHERE account_id = @a AND removed_at IS NULL") .With("@a", accountId).ScalarInt64(); return stats with { EntriesInLibrary = stats.Posts + stats.Stories + stats.HighlightItems + stats.Tagged, Bytes = bytes, PendingFiles = (int)pending, HighlightCollections = (int)collections, LastPublishedAt = last, }; }, ct); public Task AddAsync(Account account, CancellationToken ct = default) { Validate(account); return db.WriteAsync( w => { var c = w.Command(""" INSERT INTO account (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, 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, @download_order) """); Bind(c, account); try { c.ExecuteNonQuery(); } catch (SqliteException ex) when (ex.IsUniqueViolation()) { throw new DuplicateRecordException( account.IsMine ? "Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente." : "Esiste già un account con lo stesso identificativo Instagram.", ex); } var added = account with { Id = w.LastInsertRowId(), InstagramId = Normalize(account.InstagramId), Username = NormalizeUsername(account.Username) }; // An account removed before and added again (a new id) gets back its copies of the general folder, so // its Removed and Superseded copies are never copied again by themselves (spec §4.10). ExportStore.RelinkOrphanCopies(w, added.Id, added.InstagramId, added.Username); return added; }, ct); } public Task UpdateAsync(Account account, CancellationToken ct = default) { Validate(account); return db.WriteAsync( w => { var c = w.Command(""" UPDATE account SET instagram_id = @instagram_id, username = @username, display_name = @display_name, is_private = @is_private, is_followed = @is_followed, is_mine = @is_mine, state = @state, state_changed_at = @state_changed_at, unreachable_reason = @unreachable_reason, keep_updated = @keep_updated, frequency = @frequency, custom_post_interval_min = @custom_post_interval_min, custom_story_interval_min = @custom_story_interval_min, content_types = @content_types, history_depth = @history_depth, history_last_posts = @history_last_posts, history_from = @history_from, backfill_posts_per_day = @backfill_posts_per_day, max_video_bytes = @max_video_bytes, story_videos = @story_videos, folder = @folder, backfill_cursor = @backfill_cursor, backfill_completed_at = @backfill_completed_at, post_count = @post_count, 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, download_order = @download_order WHERE id = @id """); Bind(c, account); c.With("@id", account.Id); try { RequireOne(c.ExecuteNonQuery(), account.Id); } catch (SqliteException ex) when (ex.IsUniqueViolation()) { throw new DuplicateRecordException("Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente.", ex); } // The Instagram id may be known only now (an imported account): its copies come back as in AddAsync. ExportStore.RelinkOrphanCopies(w, account.Id, Normalize(account.InstagramId), NormalizeUsername(account.Username)); }, ct); } public Task SetStateAsync(long accountId, AccountState state, DateTimeOffset at, UnreachableReason? reason = null, CancellationToken ct = default) => db.WriteAsync( w => RequireOne( w.Command(""" UPDATE account SET state = @state, unreachable_reason = @reason, state_changed_at = CASE WHEN state = @state THEN state_changed_at ELSE @at END WHERE id = @id """) .With("@state", Sql.Enum(state)) .With("@reason", state == AccountState.Unreachable ? Sql.Enum(reason) : DBNull.Value) .With("@at", Sql.Time(at)) .With("@id", accountId) .ExecuteNonQuery(), accountId), ct); public Task UpdateChecksAsync(long accountId, AccountCheckTimes times, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(times); return db.WriteAsync( w => RequireOne( w.Command(""" UPDATE account SET last_profile_check_at = COALESCE(@lp, last_profile_check_at), next_profile_check_at = COALESCE(@np, next_profile_check_at), last_stories_check_at = COALESCE(@ls, last_stories_check_at), next_stories_check_at = COALESCE(@ns, next_stories_check_at), post_count = COALESCE(@pc, post_count), is_private = COALESCE(@pr, is_private), is_followed = COALESCE(@fo, is_followed), display_name = COALESCE(@dn, display_name) WHERE id = @id """) .With("@lp", Sql.Time(times.LastProfileCheckAt)) .With("@np", Sql.Time(times.NextProfileCheckAt)) .With("@ls", Sql.Time(times.LastStoriesCheckAt)) .With("@ns", Sql.Time(times.NextStoriesCheckAt)) .With("@pc", Sql.Int(times.PostCount)) .With("@pr", Sql.Bool(times.IsPrivate)) .With("@fo", Sql.Bool(times.IsFollowed)) .With("@dn", Sql.Text(times.DisplayName)) .With("@id", accountId) .ExecuteNonQuery(), accountId), ct); } public Task SetBackfillAsync(long accountId, string? cursor, DateTimeOffset? completedAt, CancellationToken ct = default) => db.WriteAsync( w => RequireOne( w.Command("UPDATE account SET backfill_cursor = @c, backfill_completed_at = @d WHERE id = @id") .With("@c", Sql.Text(cursor)) .With("@d", Sql.Time(completedAt)) .With("@id", accountId) .ExecuteNonQuery(), accountId), ct); public Task RenameAsync(long accountId, string newUsername, DateTimeOffset at, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(newUsername); var name = newUsername.Trim().TrimStart('@'); return db.WriteAsync( w => { string? oldName; string? instagramId; using (var r = w.Command("SELECT username, folder, instagram_id FROM account WHERE id = @id").With("@id", accountId).ExecuteReader()) { if (!r.Read()) { throw new KeyNotFoundException($"Account {accountId} non trovato."); } oldName = r.GetString(0); instagramId = r.GetTextOrNull(2); } if (string.Equals(oldName, name, StringComparison.Ordinal)) { return; } // A default folder follows the user name: pin it to the old name so the folder is kept (spec §4.2). w.Command(""" UPDATE account SET folder = COALESCE(folder, @pinned), previous_username = username, username = @u, renamed_at = @at, notices = notices | @renamed WHERE id = @id """) .With("@pinned", WindowsFileNames.SanitizeSegment(oldName)) .With("@u", name) .With("@at", Sql.Time(at)) .With("@renamed", (long)AccountNotices.Renamed) .With("@id", accountId) .ExecuteNonQuery(); ExportStore.RelinkOrphanCopies(w, accountId, instagramId, name); }, ct); } public Task AddNoticesAsync(long accountId, AccountNotices notices, DateTimeOffset at, CancellationToken ct = default) => db.WriteAsync( w => RequireOne( w.Command(""" UPDATE account SET notices = notices | @n, format_unrecognized_at = CASE WHEN (@n & @uf) <> 0 THEN @at ELSE format_unrecognized_at END, renamed_at = CASE WHEN (@n & @rn) <> 0 THEN @at ELSE renamed_at END WHERE id = @id """) .With("@n", (long)notices) .With("@uf", (long)AccountNotices.UnrecognizedFormat) .With("@rn", (long)AccountNotices.Renamed) .With("@at", Sql.Time(at)) .With("@id", accountId) .ExecuteNonQuery(), accountId), ct); public Task ClearNoticesAsync(long accountId, AccountNotices notices, CancellationToken ct = default) => db.WriteAsync( w => RequireOne( w.Command("UPDATE account SET notices = notices & ~@n WHERE id = @id") .With("@n", (long)notices) .With("@id", accountId) .ExecuteNonQuery(), accountId), ct); public Task DeleteAsync(long accountId, CancellationToken ct = default) => db.WriteAsync( w => { // Its export destinations stay, disabled (spec §4.10): «Automatica» goes off and forgets «Solo i nuovi», so // attaching the folder again never restarts it without asking; they keep the user name, then ON DELETE SET // NULL clears the link. CHECKs of export_destination make the delete fail if either is not written first. w.Command(""" UPDATE export_destination SET removed_account_username = (SELECT username FROM account WHERE id = @id), automatic = 0, automatic_since = NULL WHERE account_id = @id """).With("@id", accountId).ExecuteNonQuery(); // Its copies stay, in every destination and state, without account but with its Instagram id and user // name, so the account added again finds them (ExportStore.RelinkOrphanCopies): a Removed or Superseded // copy of the general folder has no file to adopt again. A CHECK allows them only without account, so // the link is cleared here, not by ON DELETE SET NULL. Job items keep only the SET NULL: they are not // what «già copiato» reads. w.Command(""" UPDATE export_copy SET account_id = NULL, removed_account_instagram_id = (SELECT instagram_id FROM account WHERE id = @id), removed_account_username = (SELECT username FROM account WHERE id = @id) WHERE account_id = @id """).With("@id", accountId).ExecuteNonQuery(); w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery(); }, ct); private static Account? ReadOne(SqliteCommand command) { using var r = command.ExecuteReader(); return r.Read() ? Read(r) : null; } private static void RequireOne(int rows, long accountId) { if (rows == 0) { throw new KeyNotFoundException($"Account {accountId} non trovato."); } } }