feat: track watch time from playback events

Daily per-user aggregates, counted on the server clock between progress
reports. Includes the cleanup task for rows past 90 days.
This commit is contained in:
2026-11-13 18:10:41 +01:00
parent 94f5f4bbb3
commit d1ee91b965
9 changed files with 689 additions and 0 deletions
@@ -0,0 +1,34 @@
using System;
namespace Jellyfin.Plugin.Herald.Stats;
/// <summary>
/// Watch activity of one user on one server-local day.
/// </summary>
public class DailyWatchStat
{
/// <summary>
/// Gets or sets the user id.
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// Gets or sets the server-local day.
/// </summary>
public DateOnly Date { get; set; }
/// <summary>
/// Gets or sets the watched seconds.
/// </summary>
public double WatchedSeconds { get; set; }
/// <summary>
/// Gets or sets the number of started plays.
/// </summary>
public int PlayCount { get; set; }
/// <summary>
/// Gets or sets the last playback activity on that day (UTC).
/// </summary>
public DateTime LastActivity { get; set; }
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.Herald.Stats;
/// <summary>
/// Persistence for daily watch-time aggregates.
/// </summary>
public interface IWatchStatsStore
{
/// <summary>
/// Adds increments to the daily aggregates.
/// </summary>
/// <param name="increments">The increments.</param>
void Add(IReadOnlyCollection<WatchIncrement> increments);
/// <summary>
/// Gets the aggregates from a day onwards.
/// </summary>
/// <param name="from">The first day to include.</param>
/// <returns>The aggregates.</returns>
IReadOnlyList<DailyWatchStat> GetSince(DateOnly from);
/// <summary>
/// Deletes aggregates older than a day.
/// </summary>
/// <param name="cutoff">The first day to keep.</param>
/// <returns>The number of deleted rows.</returns>
int DeleteBefore(DateOnly cutoff);
}
@@ -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;
/// <summary>
/// Feeds playback events of the session manager into the watch-time tracker.
/// </summary>
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<PlaybackTrackingService> _logger;
private ITimer? _sweepTimer;
/// <summary>
/// Initializes a new instance of the <see cref="PlaybackTrackingService"/> class.
/// </summary>
/// <param name="sessionManager">The session manager.</param>
/// <param name="tracker">The watch-time tracker.</param>
/// <param name="store">The stats store.</param>
/// <param name="timeProvider">The time provider.</param>
/// <param name="logger">The logger.</param>
public PlaybackTrackingService(
ISessionManager sessionManager,
WatchTimeTracker tracker,
IWatchStatsStore store,
TimeProvider timeProvider,
ILogger<PlaybackTrackingService> logger)
{
_sessionManager = sessionManager;
_tracker = tracker;
_store = store;
_timeProvider = timeProvider;
_logger = logger;
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
_sessionManager.PlaybackStart -= OnPlaybackStart;
_sessionManager.PlaybackProgress -= OnPlaybackProgress;
_sessionManager.PlaybackStopped -= OnPlaybackStopped;
_sweepTimer?.Dispose();
_sweepTimer = null;
return Task.CompletedTask;
}
/// <inheritdoc />
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<Guid> 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<string, IReadOnlyCollection<Guid>, DateTimeOffset, IReadOnlyList<WatchIncrement>> 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");
}
}
}
@@ -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;
/// <summary>
/// Daily task that removes watch-time aggregates past the retention window.
/// </summary>
public class StatsCleanupTask : IScheduledTask
{
private readonly StatsService _stats;
private readonly ILogger<StatsCleanupTask> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="StatsCleanupTask"/> class.
/// </summary>
/// <param name="stats">The stats service.</param>
/// <param name="logger">The logger.</param>
public StatsCleanupTask(StatsService stats, ILogger<StatsCleanupTask> logger)
{
_stats = stats;
_logger = logger;
}
/// <inheritdoc />
public string Name => "Clean up Herald watch-time stats";
/// <inheritdoc />
public string Key => "HeraldStatsCleanup";
/// <inheritdoc />
public string Description => "Deletes daily watch-time aggregates older than 90 days.";
/// <inheritdoc />
public string Category => "Herald";
/// <inheritdoc />
public Task ExecuteAsync(IProgress<double> 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;
}
/// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
return
[
new TaskTriggerInfo
{
Type = TaskTriggerInfoType.DailyTrigger,
TimeOfDayTicks = TimeSpan.FromHours(3.5).Ticks
}
];
}
}
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Jellyfin.Plugin.Herald.Stats;
/// <summary>
/// Builds per-user summaries from the daily aggregates.
/// </summary>
public class StatsService
{
/// <summary>
/// How many days of aggregates are kept.
/// </summary>
public const int RetentionDays = 90;
private readonly IWatchStatsStore _store;
private readonly TimeProvider _timeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="StatsService"/> class.
/// </summary>
/// <param name="store">The stats store.</param>
/// <param name="timeProvider">The time provider.</param>
public StatsService(IWatchStatsStore store, TimeProvider timeProvider)
{
_store = store;
_timeProvider = timeProvider;
}
/// <summary>
/// Gets the current server-local day.
/// </summary>
public DateOnly Today => DateOnly.FromDateTime(_timeProvider.GetLocalNow().DateTime);
/// <summary>
/// Summarizes the last <paramref name="days"/> days (today included) per user.
/// </summary>
/// <param name="days">The number of days, clamped to 1..<see cref="RetentionDays"/>.</param>
/// <param name="userNames">All existing users by id. Users without activity are listed with zeros.</param>
/// <returns>One summary per user, ordered by name.</returns>
public IReadOnlyList<UserWatchSummary> GetSummary(int days, IReadOnlyDictionary<Guid, string> 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();
}
/// <summary>
/// Deletes aggregates that fell out of the retention window.
/// </summary>
/// <returns>The number of deleted rows.</returns>
public int Cleanup() => _store.DeleteBefore(Today.AddDays(-RetentionDays));
}
@@ -0,0 +1,39 @@
using System;
namespace Jellyfin.Plugin.Herald.Stats;
/// <summary>
/// Watch activity of one user over a range of days.
/// </summary>
public class UserWatchSummary
{
/// <summary>
/// Gets or sets the user id.
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// Gets or sets the user name. <c>null</c> if the user no longer exists.
/// </summary>
public string? UserName { get; set; }
/// <summary>
/// Gets or sets the watched seconds in the range.
/// </summary>
public long WatchedSeconds { get; set; }
/// <summary>
/// Gets or sets the watched hours in the range, rounded to two decimals.
/// </summary>
public double WatchedHours { get; set; }
/// <summary>
/// Gets or sets the number of started plays in the range.
/// </summary>
public int PlayCount { get; set; }
/// <summary>
/// Gets or sets the last playback activity in the range (UTC), if any.
/// </summary>
public DateTime? LastActivity { get; set; }
}
@@ -0,0 +1,13 @@
using System;
namespace Jellyfin.Plugin.Herald.Stats;
/// <summary>
/// An amount of watch time to add to one user's daily aggregate.
/// </summary>
/// <param name="UserId">The user id.</param>
/// <param name="Date">The server-local day the time belongs to.</param>
/// <param name="Seconds">Watched seconds to add.</param>
/// <param name="Plays">Started plays to add.</param>
/// <param name="Activity">When the activity happened (UTC).</param>
public record WatchIncrement(Guid UserId, DateOnly Date, double Seconds, int Plays, DateTime Activity);
@@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Jellyfin.Plugin.Herald.Stats;
/// <summary>
/// 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.
/// </summary>
public class WatchTimeTracker
{
/// <summary>
/// The most time a single report can add.
/// </summary>
public static readonly TimeSpan MaxDelta = TimeSpan.FromSeconds(60);
/// <summary>
/// A playback without reports for this long counts as closed.
/// </summary>
public static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(5);
private readonly Dictionary<string, Playback> _playbacks = new(StringComparer.Ordinal);
private readonly Lock _lock = new();
private readonly TimeZoneInfo _timeZone;
/// <summary>
/// Initializes a new instance of the <see cref="WatchTimeTracker"/> class.
/// </summary>
/// <param name="timeZone">The zone used to assign time to days.</param>
public WatchTimeTracker(TimeZoneInfo timeZone)
{
_timeZone = timeZone;
}
/// <summary>
/// Gets the number of playbacks currently tracked.
/// </summary>
public int ActiveCount
{
get
{
lock (_lock)
{
return _playbacks.Count;
}
}
}
/// <summary>
/// Handles the start of a playback.
/// </summary>
/// <param name="key">Identifies the playback.</param>
/// <param name="userIds">The watching users.</param>
/// <param name="now">The time of the report.</param>
/// <returns>The increments to store.</returns>
public IReadOnlyList<WatchIncrement> Start(string key, IReadOnlyCollection<Guid> 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();
}
/// <summary>
/// Handles a progress report.
/// </summary>
/// <param name="key">Identifies the playback.</param>
/// <param name="userIds">The watching users.</param>
/// <param name="isPaused">Whether playback is paused as of this report.</param>
/// <param name="now">The time of the report.</param>
/// <returns>The increments to store.</returns>
public IReadOnlyList<WatchIncrement> Progress(string key, IReadOnlyCollection<Guid> 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);
}
/// <summary>
/// Handles the end of a playback.
/// </summary>
/// <param name="key">Identifies the playback.</param>
/// <param name="userIds">The watching users.</param>
/// <param name="now">The time of the report.</param>
/// <returns>The increments to store.</returns>
public IReadOnlyList<WatchIncrement> Stop(string key, IReadOnlyCollection<Guid> 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);
}
/// <summary>
/// Forgets playbacks that stopped reporting.
/// </summary>
/// <param name="now">The current time.</param>
/// <returns>The number of closed playbacks.</returns>
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<WatchIncrement> Split(IReadOnlyCollection<Guid> userIds, TimeSpan watched, DateTimeOffset now)
{
var increments = new List<WatchIncrement>();
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);
}