using System; using System.Globalization; using System.IO; using System.Threading; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Logging; namespace Jellyfin.Plugin.Herald.Storage; /// /// Owns the plugin's SQLite file: connections, schema and write serialization. /// public class HeraldDatabase { private static readonly string[] _migrations = [ // 1: notices and acknowledgements """ CREATE TABLE notices ( id TEXT NOT NULL PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL, require_accept INTEGER NOT NULL, enabled INTEGER NOT NULL, target_all INTEGER NOT NULL, target_users TEXT NOT NULL, revision INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE notice_acks ( notice_id TEXT NOT NULL, revision INTEGER NOT NULL, user_id TEXT NOT NULL, action INTEGER NOT NULL, timestamp TEXT NOT NULL, PRIMARY KEY (notice_id, revision, user_id) ); CREATE INDEX ix_notice_acks_user ON notice_acks (user_id); """, // 2: daily watch-time aggregates """ CREATE TABLE watch_daily ( user_id TEXT NOT NULL, date TEXT NOT NULL, watched_seconds REAL NOT NULL, play_count INTEGER NOT NULL, last_activity TEXT NOT NULL, PRIMARY KEY (user_id, date) ); CREATE INDEX ix_watch_daily_date ON watch_daily (date); """ ]; private readonly string _connectionString; private readonly ILogger _logger; private readonly Lock _writeLock = new(); private bool _initialized; /// /// Initializes a new instance of the class. /// /// Full path of the database file. /// The logger. public HeraldDatabase(string databasePath, ILogger logger) { DatabasePath = databasePath; _logger = logger; _connectionString = new SqliteConnectionStringBuilder { DataSource = databasePath, Mode = SqliteOpenMode.ReadWriteCreate, DefaultTimeout = 30 }.ToString(); } /// /// Gets the full path of the database file. /// public string DatabasePath { get; } /// /// Gets the number of schema migrations known to this build. /// public static int SchemaVersion => _migrations.Length; /// /// Runs a read-only operation. /// /// The result type. /// The operation. /// The operation result. public T Read(Func operation) { ArgumentNullException.ThrowIfNull(operation); using var connection = Open(); return operation(connection); } /// /// Runs a write operation inside a transaction. Writes never run concurrently. /// /// The result type. /// The operation. /// The operation result. public T Write(Func operation) { ArgumentNullException.ThrowIfNull(operation); using var connection = Open(); lock (_writeLock) { using var transaction = connection.BeginTransaction(); var result = operation(connection, transaction); transaction.Commit(); return result; } } /// /// Creates the database file if needed and applies outstanding migrations. /// public void EnsureCreated() { lock (_writeLock) { if (_initialized) { return; } var directory = Path.GetDirectoryName(DatabasePath); if (!string.IsNullOrEmpty(directory)) { Directory.CreateDirectory(directory); } using var connection = new SqliteConnection(_connectionString); connection.Open(); Execute(connection, null, "PRAGMA journal_mode = WAL;"); var current = Convert.ToInt32(Scalar(connection, "PRAGMA user_version;"), CultureInfo.InvariantCulture); if (current > _migrations.Length) { throw new InvalidOperationException( $"The Herald database is at schema version {current}, but this plugin build only knows version {_migrations.Length}."); } for (var version = current + 1; version <= _migrations.Length; version++) { using var transaction = connection.BeginTransaction(); Execute(connection, transaction, _migrations[version - 1]); Execute(connection, transaction, "PRAGMA user_version = " + version.ToString(CultureInfo.InvariantCulture) + ";"); transaction.Commit(); _logger.LogInformation("Herald database migrated to schema version {Version}", version); } _initialized = true; } } private static void Execute(SqliteConnection connection, SqliteTransaction? transaction, string sql) { using var command = connection.CreateCommand(); command.Transaction = transaction; #pragma warning disable CA2100 // only called with the constant statements above command.CommandText = sql; #pragma warning restore CA2100 command.ExecuteNonQuery(); } private static object? Scalar(SqliteConnection connection, string sql) { using var command = connection.CreateCommand(); #pragma warning disable CA2100 // only called with constant statements command.CommandText = sql; #pragma warning restore CA2100 return command.ExecuteScalar(); } private SqliteConnection Open() { EnsureCreated(); var connection = new SqliteConnection(_connectionString); connection.Open(); return connection; } }