diff --git a/Jellyfin.Plugin.Herald/Stats/DailyWatchStat.cs b/Jellyfin.Plugin.Herald/Stats/DailyWatchStat.cs new file mode 100644 index 0000000..0058373 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/DailyWatchStat.cs @@ -0,0 +1,34 @@ +using System; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// Watch activity of one user on one server-local day. +/// +public class DailyWatchStat +{ + /// + /// Gets or sets the user id. + /// + public Guid UserId { get; set; } + + /// + /// Gets or sets the server-local day. + /// + public DateOnly Date { get; set; } + + /// + /// Gets or sets the watched seconds. + /// + public double WatchedSeconds { get; set; } + + /// + /// Gets or sets the number of started plays. + /// + public int PlayCount { get; set; } + + /// + /// Gets or sets the last playback activity on that day (UTC). + /// + public DateTime LastActivity { get; set; } +} diff --git a/Jellyfin.Plugin.Herald/Stats/IWatchStatsStore.cs b/Jellyfin.Plugin.Herald/Stats/IWatchStatsStore.cs new file mode 100644 index 0000000..c372e4b --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/IWatchStatsStore.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// Persistence for daily watch-time aggregates. +/// +public interface IWatchStatsStore +{ + /// + /// Adds increments to the daily aggregates. + /// + /// The increments. + void Add(IReadOnlyCollection increments); + + /// + /// Gets the aggregates from a day onwards. + /// + /// The first day to include. + /// The aggregates. + IReadOnlyList GetSince(DateOnly from); + + /// + /// Deletes aggregates older than a day. + /// + /// The first day to keep. + /// The number of deleted rows. + int DeleteBefore(DateOnly cutoff); +} diff --git a/Jellyfin.Plugin.Herald/Stats/PlaybackTrackingService.cs b/Jellyfin.Plugin.Herald/Stats/PlaybackTrackingService.cs new file mode 100644 index 0000000..7645a26 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/PlaybackTrackingService.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Session; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// Feeds playback events of the session manager into the watch-time tracker. +/// +public sealed class PlaybackTrackingService : IHostedService, IDisposable +{ + private static readonly TimeSpan _sweepInterval = TimeSpan.FromMinutes(1); + + private readonly ISessionManager _sessionManager; + private readonly WatchTimeTracker _tracker; + private readonly IWatchStatsStore _store; + private readonly TimeProvider _timeProvider; + private readonly ILogger _logger; + private ITimer? _sweepTimer; + + /// + /// Initializes a new instance of the class. + /// + /// The session manager. + /// The watch-time tracker. + /// The stats store. + /// The time provider. + /// The logger. + public PlaybackTrackingService( + ISessionManager sessionManager, + WatchTimeTracker tracker, + IWatchStatsStore store, + TimeProvider timeProvider, + ILogger logger) + { + _sessionManager = sessionManager; + _tracker = tracker; + _store = store; + _timeProvider = timeProvider; + _logger = logger; + } + + /// + public Task StartAsync(CancellationToken cancellationToken) + { + _sessionManager.PlaybackStart += OnPlaybackStart; + _sessionManager.PlaybackProgress += OnPlaybackProgress; + _sessionManager.PlaybackStopped += OnPlaybackStopped; + _sweepTimer = _timeProvider.CreateTimer(_ => Sweep(), null, _sweepInterval, _sweepInterval); + + _logger.LogInformation("Herald watch-time tracking started"); + return Task.CompletedTask; + } + + /// + public Task StopAsync(CancellationToken cancellationToken) + { + _sessionManager.PlaybackStart -= OnPlaybackStart; + _sessionManager.PlaybackProgress -= OnPlaybackProgress; + _sessionManager.PlaybackStopped -= OnPlaybackStopped; + _sweepTimer?.Dispose(); + _sweepTimer = null; + return Task.CompletedTask; + } + + /// + public void Dispose() + { + _sweepTimer?.Dispose(); + } + + private static string Key(PlaybackProgressEventArgs e) + { + var session = e.Session?.Id ?? e.DeviceId ?? string.Empty; + var item = e.Item?.Id.ToString("N", CultureInfo.InvariantCulture) ?? e.MediaSourceId ?? string.Empty; + return session + "|" + item; + } + + private static List UserIds(PlaybackProgressEventArgs e) + { + return e.Users is null ? [] : e.Users.Select(u => u.Id).Distinct().ToList(); + } + + private void OnPlaybackStart(object? sender, PlaybackProgressEventArgs e) + { + Handle(e, "start", (key, users, now) => _tracker.Start(key, users, now)); + } + + private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e) + { + // The server repeats the last client report on a timer while a client is quiet. + // Those repeats say nothing about whether somebody is still watching. + if (e.IsAutomated) + { + return; + } + + Handle(e, "progress", (key, users, now) => _tracker.Progress(key, users, e.IsPaused, now)); + } + + private void OnPlaybackStopped(object? sender, PlaybackStopEventArgs e) + { + Handle(e, "stop", (key, users, now) => _tracker.Stop(key, users, now)); + } + + private void Handle( + PlaybackProgressEventArgs e, + string kind, + Func, DateTimeOffset, IReadOnlyList> report) + { + try + { + var users = UserIds(e); + if (users.Count == 0) + { + return; + } + + _store.Add(report(Key(e), users, _timeProvider.GetUtcNow())); + } + catch (Exception ex) + { + // Never let stats break playback reporting for the rest of the server. + _logger.LogError(ex, "Failed to record playback {Kind} for watch-time stats", kind); + } + } + + private void Sweep() + { + try + { + var closed = _tracker.CloseStale(_timeProvider.GetUtcNow()); + if (closed > 0) + { + _logger.LogDebug("Closed {Count} playback(s) without progress reports for over {Minutes} minutes", closed, WatchTimeTracker.StaleAfter.TotalMinutes); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to close stale playbacks"); + } + } +} diff --git a/Jellyfin.Plugin.Herald/Stats/StatsCleanupTask.cs b/Jellyfin.Plugin.Herald/Stats/StatsCleanupTask.cs new file mode 100644 index 0000000..e76da48 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/StatsCleanupTask.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Tasks; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// Daily task that removes watch-time aggregates past the retention window. +/// +public class StatsCleanupTask : IScheduledTask +{ + private readonly StatsService _stats; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The stats service. + /// The logger. + public StatsCleanupTask(StatsService stats, ILogger logger) + { + _stats = stats; + _logger = logger; + } + + /// + public string Name => "Clean up Herald watch-time stats"; + + /// + public string Key => "HeraldStatsCleanup"; + + /// + public string Description => "Deletes daily watch-time aggregates older than 90 days."; + + /// + public string Category => "Herald"; + + /// + public Task ExecuteAsync(IProgress progress, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(progress); + + var deleted = _stats.Cleanup(); + _logger.LogInformation("Removed {Count} watch-time rows older than {Days} days", deleted, StatsService.RetentionDays); + progress.Report(100); + return Task.CompletedTask; + } + + /// + public IEnumerable GetDefaultTriggers() + { + return + [ + new TaskTriggerInfo + { + Type = TaskTriggerInfoType.DailyTrigger, + TimeOfDayTicks = TimeSpan.FromHours(3.5).Ticks + } + ]; + } +} diff --git a/Jellyfin.Plugin.Herald/Stats/StatsService.cs b/Jellyfin.Plugin.Herald/Stats/StatsService.cs new file mode 100644 index 0000000..2531708 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/StatsService.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// Builds per-user summaries from the daily aggregates. +/// +public class StatsService +{ + /// + /// How many days of aggregates are kept. + /// + public const int RetentionDays = 90; + + private readonly IWatchStatsStore _store; + private readonly TimeProvider _timeProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The stats store. + /// The time provider. + public StatsService(IWatchStatsStore store, TimeProvider timeProvider) + { + _store = store; + _timeProvider = timeProvider; + } + + /// + /// Gets the current server-local day. + /// + public DateOnly Today => DateOnly.FromDateTime(_timeProvider.GetLocalNow().DateTime); + + /// + /// Summarizes the last days (today included) per user. + /// + /// The number of days, clamped to 1... + /// All existing users by id. Users without activity are listed with zeros. + /// One summary per user, ordered by name. + public IReadOnlyList GetSummary(int days, IReadOnlyDictionary userNames) + { + ArgumentNullException.ThrowIfNull(userNames); + + days = Math.Clamp(days, 1, RetentionDays); + var byUser = _store.GetSince(Today.AddDays(1 - days)).ToLookup(s => s.UserId); + + return userNames.Keys + .Union(byUser.Select(g => g.Key)) + .Select(userId => + { + var rows = byUser[userId].ToList(); + var seconds = rows.Sum(r => r.WatchedSeconds); + return new UserWatchSummary + { + UserId = userId, + UserName = userNames.GetValueOrDefault(userId), + WatchedSeconds = (long)Math.Round(seconds), + WatchedHours = Math.Round(seconds / 3600d, 2), + PlayCount = rows.Sum(r => r.PlayCount), + LastActivity = rows.Count == 0 ? null : rows.Max(r => r.LastActivity) + }; + }) + .OrderBy(s => s.UserName is null) + .ThenBy(s => s.UserName, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + /// + /// Deletes aggregates that fell out of the retention window. + /// + /// The number of deleted rows. + public int Cleanup() => _store.DeleteBefore(Today.AddDays(-RetentionDays)); +} diff --git a/Jellyfin.Plugin.Herald/Stats/UserWatchSummary.cs b/Jellyfin.Plugin.Herald/Stats/UserWatchSummary.cs new file mode 100644 index 0000000..1fab327 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/UserWatchSummary.cs @@ -0,0 +1,39 @@ +using System; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// Watch activity of one user over a range of days. +/// +public class UserWatchSummary +{ + /// + /// Gets or sets the user id. + /// + public Guid UserId { get; set; } + + /// + /// Gets or sets the user name. null if the user no longer exists. + /// + public string? UserName { get; set; } + + /// + /// Gets or sets the watched seconds in the range. + /// + public long WatchedSeconds { get; set; } + + /// + /// Gets or sets the watched hours in the range, rounded to two decimals. + /// + public double WatchedHours { get; set; } + + /// + /// Gets or sets the number of started plays in the range. + /// + public int PlayCount { get; set; } + + /// + /// Gets or sets the last playback activity in the range (UTC), if any. + /// + public DateTime? LastActivity { get; set; } +} diff --git a/Jellyfin.Plugin.Herald/Stats/WatchIncrement.cs b/Jellyfin.Plugin.Herald/Stats/WatchIncrement.cs new file mode 100644 index 0000000..60c3172 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/WatchIncrement.cs @@ -0,0 +1,13 @@ +using System; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// An amount of watch time to add to one user's daily aggregate. +/// +/// The user id. +/// The server-local day the time belongs to. +/// Watched seconds to add. +/// Started plays to add. +/// When the activity happened (UTC). +public record WatchIncrement(Guid UserId, DateOnly Date, double Seconds, int Plays, DateTime Activity); diff --git a/Jellyfin.Plugin.Herald/Stats/WatchTimeTracker.cs b/Jellyfin.Plugin.Herald/Stats/WatchTimeTracker.cs new file mode 100644 index 0000000..8bb3aa9 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Stats/WatchTimeTracker.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Jellyfin.Plugin.Herald.Stats; + +/// +/// Turns playback reports into watch-time increments. +/// Time is measured on the server clock between two reports of the same playback, so seeking never adds time. +/// +public class WatchTimeTracker +{ + /// + /// The most time a single report can add. + /// + public static readonly TimeSpan MaxDelta = TimeSpan.FromSeconds(60); + + /// + /// A playback without reports for this long counts as closed. + /// + public static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(5); + + private readonly Dictionary _playbacks = new(StringComparer.Ordinal); + private readonly Lock _lock = new(); + private readonly TimeZoneInfo _timeZone; + + /// + /// Initializes a new instance of the class. + /// + /// The zone used to assign time to days. + public WatchTimeTracker(TimeZoneInfo timeZone) + { + _timeZone = timeZone; + } + + /// + /// Gets the number of playbacks currently tracked. + /// + public int ActiveCount + { + get + { + lock (_lock) + { + return _playbacks.Count; + } + } + } + + /// + /// Handles the start of a playback. + /// + /// Identifies the playback. + /// The watching users. + /// The time of the report. + /// The increments to store. + public IReadOnlyList Start(string key, IReadOnlyCollection userIds, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(userIds); + + lock (_lock) + { + _playbacks[key] = new Playback(now, false); + } + + var date = LocalDate(now); + return userIds.Select(id => new WatchIncrement(id, date, 0, 1, now.UtcDateTime)).ToList(); + } + + /// + /// Handles a progress report. + /// + /// Identifies the playback. + /// The watching users. + /// Whether playback is paused as of this report. + /// The time of the report. + /// The increments to store. + public IReadOnlyList Progress(string key, IReadOnlyCollection userIds, bool isPaused, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(userIds); + + TimeSpan watched; + lock (_lock) + { + watched = _playbacks.TryGetValue(key, out var playback) ? Elapsed(playback, now) : TimeSpan.Zero; + _playbacks[key] = new Playback(now, isPaused); + } + + return Split(userIds, watched, now); + } + + /// + /// Handles the end of a playback. + /// + /// Identifies the playback. + /// The watching users. + /// The time of the report. + /// The increments to store. + public IReadOnlyList Stop(string key, IReadOnlyCollection userIds, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(userIds); + + TimeSpan watched; + lock (_lock) + { + watched = _playbacks.Remove(key, out var playback) ? Elapsed(playback, now) : TimeSpan.Zero; + } + + return Split(userIds, watched, now); + } + + /// + /// Forgets playbacks that stopped reporting. + /// + /// The current time. + /// The number of closed playbacks. + public int CloseStale(DateTimeOffset now) + { + lock (_lock) + { + var stale = _playbacks.Where(p => now - p.Value.LastReport > StaleAfter).Select(p => p.Key).ToList(); + foreach (var key in stale) + { + _playbacks.Remove(key); + } + + return stale.Count; + } + } + + private static TimeSpan Elapsed(Playback playback, DateTimeOffset now) + { + var elapsed = now - playback.LastReport; + + // Paused stretches, clock jumps and playbacks that went silent add nothing. + if (playback.Paused || elapsed <= TimeSpan.Zero || elapsed > StaleAfter) + { + return TimeSpan.Zero; + } + + return elapsed > MaxDelta ? MaxDelta : elapsed; + } + + private List Split(IReadOnlyCollection userIds, TimeSpan watched, DateTimeOffset now) + { + var increments = new List(); + if (watched <= TimeSpan.Zero) + { + return increments; + } + + var localEnd = TimeZoneInfo.ConvertTime(now, _timeZone); + var localStart = TimeZoneInfo.ConvertTime(now - watched, _timeZone); + var endDate = DateOnly.FromDateTime(localEnd.DateTime); + var startDate = DateOnly.FromDateTime(localStart.DateTime); + + // A delta is at most a minute long, so it touches two days at most. + var secondsToday = startDate == endDate ? watched.TotalSeconds : Math.Min(watched.TotalSeconds, localEnd.TimeOfDay.TotalSeconds); + var secondsYesterday = watched.TotalSeconds - secondsToday; + + foreach (var userId in userIds) + { + if (secondsYesterday > 0) + { + increments.Add(new WatchIncrement(userId, startDate, secondsYesterday, 0, (now - TimeSpan.FromSeconds(secondsToday)).UtcDateTime)); + } + + if (secondsToday > 0) + { + increments.Add(new WatchIncrement(userId, endDate, secondsToday, 0, now.UtcDateTime)); + } + } + + return increments; + } + + private DateOnly LocalDate(DateTimeOffset time) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(time, _timeZone).DateTime); + + private readonly record struct Playback(DateTimeOffset LastReport, bool Paused); +} diff --git a/Jellyfin.Plugin.Herald/Storage/SqliteWatchStatsStore.cs b/Jellyfin.Plugin.Herald/Storage/SqliteWatchStatsStore.cs new file mode 100644 index 0000000..197f0c6 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Storage/SqliteWatchStatsStore.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using Jellyfin.Plugin.Herald.Stats; + +namespace Jellyfin.Plugin.Herald.Storage; + +/// +/// SQLite backed . +/// +public class SqliteWatchStatsStore : IWatchStatsStore +{ + private readonly HeraldDatabase _database; + + /// + /// Initializes a new instance of the class. + /// + /// The database. + public SqliteWatchStatsStore(HeraldDatabase database) + { + _database = database; + } + + /// + public void Add(IReadOnlyCollection increments) + { + ArgumentNullException.ThrowIfNull(increments); + if (increments.Count == 0) + { + return; + } + + _database.Write((connection, transaction) => + { + using var command = Db.Command( + connection, + transaction, + """ + INSERT INTO watch_daily (user_id, date, watched_seconds, play_count, last_activity) + VALUES ($userId, $date, $seconds, $plays, $activity) + ON CONFLICT (user_id, date) DO UPDATE SET + watched_seconds = watched_seconds + excluded.watched_seconds, + play_count = play_count + excluded.play_count, + last_activity = max(last_activity, excluded.last_activity); + """); + var userId = command.Parameters.Add("$userId", Microsoft.Data.Sqlite.SqliteType.Text); + var date = command.Parameters.Add("$date", Microsoft.Data.Sqlite.SqliteType.Text); + var seconds = command.Parameters.Add("$seconds", Microsoft.Data.Sqlite.SqliteType.Real); + var plays = command.Parameters.Add("$plays", Microsoft.Data.Sqlite.SqliteType.Integer); + var activity = command.Parameters.Add("$activity", Microsoft.Data.Sqlite.SqliteType.Text); + + foreach (var increment in increments) + { + userId.Value = Db.Id(increment.UserId); + date.Value = Db.Date(increment.Date); + seconds.Value = increment.Seconds; + plays.Value = increment.Plays; + activity.Value = Db.Time(increment.Activity); + command.ExecuteNonQuery(); + } + + return increments.Count; + }); + } + + /// + public IReadOnlyList GetSince(DateOnly from) + { + return _database.Read(connection => + { + using var command = Db.Command( + connection, + null, + "SELECT user_id, date, watched_seconds, play_count, last_activity FROM watch_daily WHERE date >= $from ORDER BY date, user_id;"); + command.Parameters.AddWithValue("$from", Db.Date(from)); + using var reader = command.ExecuteReader(); + var stats = new List(); + while (reader.Read()) + { + stats.Add(new DailyWatchStat + { + UserId = Db.Id(reader.GetString(0)), + Date = Db.Date(reader.GetString(1)), + WatchedSeconds = reader.GetDouble(2), + PlayCount = reader.GetInt32(3), + LastActivity = Db.Time(reader.GetString(4)) + }); + } + + return stats; + }); + } + + /// + public int DeleteBefore(DateOnly cutoff) + { + return _database.Write((connection, transaction) => + { + using var command = Db.Command(connection, transaction, "DELETE FROM watch_daily WHERE date < $cutoff;"); + command.Parameters.AddWithValue("$cutoff", Db.Date(cutoff)); + return command.ExecuteNonQuery(); + }); + } +}