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