diff --git a/Jellyfin.Plugin.Herald/Storage/Db.cs b/Jellyfin.Plugin.Herald/Storage/Db.cs new file mode 100644 index 0000000..600765d --- /dev/null +++ b/Jellyfin.Plugin.Herald/Storage/Db.cs @@ -0,0 +1,35 @@ +using System; +using System.Globalization; +using Microsoft.Data.Sqlite; + +namespace Jellyfin.Plugin.Herald.Storage; + +/// +/// Value conversions shared by the stores. +/// +internal static class Db +{ + public const string DateFormat = "yyyy-MM-dd"; + + public static string Id(Guid value) => value.ToString("N", CultureInfo.InvariantCulture); + + public static Guid Id(string value) => Guid.ParseExact(value, "N"); + + public static string Time(DateTime value) => value.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture); + + public static DateTime Time(string value) => DateTime.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind).ToUniversalTime(); + + public static string Date(DateOnly value) => value.ToString(DateFormat, CultureInfo.InvariantCulture); + + public static DateOnly Date(string value) => DateOnly.ParseExact(value, DateFormat, CultureInfo.InvariantCulture); + + public static SqliteCommand Command(SqliteConnection connection, SqliteTransaction? transaction, string sql) + { + var command = connection.CreateCommand(); + command.Transaction = transaction; +#pragma warning disable CA2100 // statements are constants, values are always bound as parameters + command.CommandText = sql; +#pragma warning restore CA2100 + return command; + } +} diff --git a/Jellyfin.Plugin.Herald/Storage/HeraldDatabase.cs b/Jellyfin.Plugin.Herald/Storage/HeraldDatabase.cs new file mode 100644 index 0000000..13bcd2e --- /dev/null +++ b/Jellyfin.Plugin.Herald/Storage/HeraldDatabase.cs @@ -0,0 +1,190 @@ +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; + } +} diff --git a/Jellyfin.Plugin.Herald/Storage/SqliteNoticeStore.cs b/Jellyfin.Plugin.Herald/Storage/SqliteNoticeStore.cs new file mode 100644 index 0000000..5afca79 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Storage/SqliteNoticeStore.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using Jellyfin.Plugin.Herald.Notices; +using Microsoft.Data.Sqlite; + +namespace Jellyfin.Plugin.Herald.Storage; + +/// +/// SQLite backed . +/// +public class SqliteNoticeStore : INoticeStore +{ + private const string NoticeColumns = "id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at"; + private const string AckColumns = "notice_id, revision, user_id, action, timestamp"; + + private readonly HeraldDatabase _database; + + /// + /// Initializes a new instance of the class. + /// + /// The database. + public SqliteNoticeStore(HeraldDatabase database) + { + _database = database; + } + + /// + public IReadOnlyList GetNotices() + { + return _database.Read(connection => + { + using var command = Db.Command(connection, null, "SELECT " + NoticeColumns + " FROM notices ORDER BY created_at, id;"); + using var reader = command.ExecuteReader(); + var notices = new List(); + while (reader.Read()) + { + notices.Add(ReadNotice(reader)); + } + + return notices; + }); + } + + /// + public Notice? GetNotice(Guid id) + { + return _database.Read(connection => + { + using var command = Db.Command(connection, null, "SELECT " + NoticeColumns + " FROM notices WHERE id = $id;"); + command.Parameters.AddWithValue("$id", Db.Id(id)); + using var reader = command.ExecuteReader(); + return reader.Read() ? ReadNotice(reader) : null; + }); + } + + /// + public void SaveNotice(Notice notice) + { + ArgumentNullException.ThrowIfNull(notice); + + _database.Write((connection, transaction) => + { + using var command = Db.Command( + connection, + transaction, + """ + INSERT INTO notices (id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at) + VALUES ($id, $title, $body, $requireAccept, $enabled, $targetAll, $targetUsers, $revision, $createdAt, $updatedAt) + ON CONFLICT (id) DO UPDATE SET + title = excluded.title, + body = excluded.body, + require_accept = excluded.require_accept, + enabled = excluded.enabled, + target_all = excluded.target_all, + target_users = excluded.target_users, + revision = excluded.revision, + updated_at = excluded.updated_at; + """); + command.Parameters.AddWithValue("$id", Db.Id(notice.Id)); + command.Parameters.AddWithValue("$title", notice.Title); + command.Parameters.AddWithValue("$body", notice.Body); + command.Parameters.AddWithValue("$requireAccept", notice.RequireAccept); + command.Parameters.AddWithValue("$enabled", notice.Enabled); + command.Parameters.AddWithValue("$targetAll", notice.Target.AllUsers); + command.Parameters.AddWithValue("$targetUsers", JsonSerializer.Serialize(notice.Target.UserIds.Select(Db.Id))); + command.Parameters.AddWithValue("$revision", notice.Revision); + command.Parameters.AddWithValue("$createdAt", Db.Time(notice.CreatedAt)); + command.Parameters.AddWithValue("$updatedAt", Db.Time(notice.UpdatedAt)); + return command.ExecuteNonQuery(); + }); + } + + /// + public bool DeleteNotice(Guid id) + { + return _database.Write((connection, transaction) => + { + using var acks = Db.Command(connection, transaction, "DELETE FROM notice_acks WHERE notice_id = $id;"); + acks.Parameters.AddWithValue("$id", Db.Id(id)); + acks.ExecuteNonQuery(); + + using var notice = Db.Command(connection, transaction, "DELETE FROM notices WHERE id = $id;"); + notice.Parameters.AddWithValue("$id", Db.Id(id)); + return notice.ExecuteNonQuery() > 0; + }); + } + + /// + public IReadOnlyList GetAcksByUser(Guid userId) + { + return _database.Read(connection => + { + using var command = Db.Command(connection, null, "SELECT " + AckColumns + " FROM notice_acks WHERE user_id = $userId;"); + command.Parameters.AddWithValue("$userId", Db.Id(userId)); + return ReadAcks(command); + }); + } + + /// + public IReadOnlyList GetAcks(Guid noticeId, int revision) + { + return _database.Read(connection => + { + using var command = Db.Command( + connection, + null, + "SELECT " + AckColumns + " FROM notice_acks WHERE notice_id = $noticeId AND revision = $revision ORDER BY timestamp;"); + command.Parameters.AddWithValue("$noticeId", Db.Id(noticeId)); + command.Parameters.AddWithValue("$revision", revision); + return ReadAcks(command); + }); + } + + /// + public void AddAck(NoticeAck ack) + { + ArgumentNullException.ThrowIfNull(ack); + + _database.Write((connection, transaction) => + { + using var command = Db.Command( + connection, + transaction, + """ + INSERT OR IGNORE INTO notice_acks (notice_id, revision, user_id, action, timestamp) + VALUES ($noticeId, $revision, $userId, $action, $timestamp); + """); + command.Parameters.AddWithValue("$noticeId", Db.Id(ack.NoticeId)); + command.Parameters.AddWithValue("$revision", ack.Revision); + command.Parameters.AddWithValue("$userId", Db.Id(ack.UserId)); + command.Parameters.AddWithValue("$action", (int)ack.Action); + command.Parameters.AddWithValue("$timestamp", Db.Time(ack.Timestamp)); + return command.ExecuteNonQuery(); + }); + } + + private static List ReadAcks(SqliteCommand command) + { + using var reader = command.ExecuteReader(); + var acks = new List(); + while (reader.Read()) + { + acks.Add(new NoticeAck + { + NoticeId = Db.Id(reader.GetString(0)), + Revision = reader.GetInt32(1), + UserId = Db.Id(reader.GetString(2)), + Action = (AckAction)reader.GetInt32(3), + Timestamp = Db.Time(reader.GetString(4)) + }); + } + + return acks; + } + + private static Notice ReadNotice(SqliteDataReader reader) + { + var userIds = JsonSerializer.Deserialize>(reader.GetString(6)) ?? []; + return new Notice + { + Id = Db.Id(reader.GetString(0)), + Title = reader.GetString(1), + Body = reader.GetString(2), + RequireAccept = reader.GetBoolean(3), + Enabled = reader.GetBoolean(4), + Target = new NoticeTarget + { + AllUsers = reader.GetBoolean(5), + UserIds = userIds.Select(Db.Id).ToList() + }, + Revision = reader.GetInt32(7), + CreatedAt = Db.Time(reader.GetString(8)), + UpdatedAt = Db.Time(reader.GetString(9)) + }; + } +}