feat: store notices in sqlite with versioned migrations
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Value conversions shared by the stores.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Owns the plugin's SQLite file: connections, schema and write serialization.
|
||||
/// </summary>
|
||||
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<HeraldDatabase> _logger;
|
||||
private readonly Lock _writeLock = new();
|
||||
private bool _initialized;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HeraldDatabase"/> class.
|
||||
/// </summary>
|
||||
/// <param name="databasePath">Full path of the database file.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public HeraldDatabase(string databasePath, ILogger<HeraldDatabase> logger)
|
||||
{
|
||||
DatabasePath = databasePath;
|
||||
_logger = logger;
|
||||
_connectionString = new SqliteConnectionStringBuilder
|
||||
{
|
||||
DataSource = databasePath,
|
||||
Mode = SqliteOpenMode.ReadWriteCreate,
|
||||
DefaultTimeout = 30
|
||||
}.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the full path of the database file.
|
||||
/// </summary>
|
||||
public string DatabasePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of schema migrations known to this build.
|
||||
/// </summary>
|
||||
public static int SchemaVersion => _migrations.Length;
|
||||
|
||||
/// <summary>
|
||||
/// Runs a read-only operation.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The result type.</typeparam>
|
||||
/// <param name="operation">The operation.</param>
|
||||
/// <returns>The operation result.</returns>
|
||||
public T Read<T>(Func<SqliteConnection, T> operation)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
|
||||
using var connection = Open();
|
||||
return operation(connection);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a write operation inside a transaction. Writes never run concurrently.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The result type.</typeparam>
|
||||
/// <param name="operation">The operation.</param>
|
||||
/// <returns>The operation result.</returns>
|
||||
public T Write<T>(Func<SqliteConnection, SqliteTransaction, T> operation)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
|
||||
using var connection = Open();
|
||||
lock (_writeLock)
|
||||
{
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var result = operation(connection, transaction);
|
||||
transaction.Commit();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the database file if needed and applies outstanding migrations.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// SQLite backed <see cref="INoticeStore"/>.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SqliteNoticeStore"/> class.
|
||||
/// </summary>
|
||||
/// <param name="database">The database.</param>
|
||||
public SqliteNoticeStore(HeraldDatabase database)
|
||||
{
|
||||
_database = database;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<Notice> 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<Notice>();
|
||||
while (reader.Read())
|
||||
{
|
||||
notices.Add(ReadNotice(reader));
|
||||
}
|
||||
|
||||
return notices;
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<NoticeAck> 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);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<NoticeAck> 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);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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<NoticeAck> ReadAcks(SqliteCommand command)
|
||||
{
|
||||
using var reader = command.ExecuteReader();
|
||||
var acks = new List<NoticeAck>();
|
||||
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<List<string>>(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))
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user