196 lines
6.4 KiB
C#
196 lines
6.4 KiB
C#
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);
|
|
""",
|
|
|
|
// 3: wait before a notice can be accepted
|
|
"""
|
|
ALTER TABLE notices ADD COLUMN accept_delay INTEGER NOT NULL DEFAULT 0;
|
|
"""
|
|
];
|
|
|
|
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;
|
|
}
|
|
}
|