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);
}