// SPDX-License-Identifier: GPL-3.0-or-later using System.Collections.Concurrent; using System.Net.Http.Json; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Session; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Jellyfin.Plugin.LightsOffTimer; public enum TimerMode { Off, EndOfItem, Minutes, } /// Sleep-timer state for one playback session (one device of one user). public sealed class SessionTimer { public TimerMode Mode { get; set; } public DateTime? Deadline { get; set; } public int? Minutes { get; set; } /// Set when the timed item finished: the next item that starts (autoplay) gets stopped. public DateTime? StopNextStartUntil { get; set; } /// Set while we are stopping playback ourselves, so the resulting stop is reported once. public bool StoppingByTimer { get; set; } } /// /// Tracks sleep timers per session, stops playback when they expire and tells Home Assistant /// ("started" cancels the lights-off countdown, "stopped" starts it). /// public sealed class TimerManager : IHostedService, IDisposable { private static readonly TimeSpan AutoplayWindow = TimeSpan.FromSeconds(45); private readonly ISessionManager _sessions; private readonly ILogger _log; private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(10) }; private readonly ConcurrentDictionary _timers = new(); private Timer? _tick; public TimerManager(ISessionManager sessions, ILogger log) { _sessions = sessions; _log = log; } public SessionTimer Get(string sessionId) => _timers.GetOrAdd(sessionId, _ => new SessionTimer()); public void Set(string sessionId, TimerMode mode, int? minutes) { var t = Get(sessionId); t.Mode = mode; t.Minutes = mode == TimerMode.Minutes ? minutes : null; t.Deadline = mode == TimerMode.Minutes && minutes > 0 ? DateTime.UtcNow.AddMinutes(minutes.Value) : null; t.StopNextStartUntil = null; t.StoppingByTimer = false; _log.LogInformation("Sleep timer for session {Session}: {Mode} {Minutes}", sessionId, mode, minutes); } public Task StartAsync(CancellationToken cancellationToken) { _sessions.PlaybackStart += OnPlaybackStart; _sessions.PlaybackStopped += OnPlaybackStopped; _sessions.SessionEnded += OnSessionEnded; _tick = new Timer(_ => CheckDeadlines(), null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _sessions.PlaybackStart -= OnPlaybackStart; _sessions.PlaybackStopped -= OnPlaybackStopped; _sessions.SessionEnded -= OnSessionEnded; _tick?.Change(Timeout.Infinite, Timeout.Infinite); return Task.CompletedTask; } public void Dispose() { _tick?.Dispose(); _http.Dispose(); } private void OnPlaybackStart(object? sender, PlaybackProgressEventArgs e) { var id = e.Session?.Id; if (id is null) { return; } var t = Get(id); if (t.StopNextStartUntil is { } until && DateTime.UtcNow <= until) { // The timed episode finished and the client autoplayed the next one: stop it, // and don't tell Home Assistant "started" (that would cancel the lights-off countdown). _log.LogInformation("Sleep timer: stopping autoplayed '{Item}' in session {Session}", e.Item?.Name, id); t.StopNextStartUntil = null; t.StoppingByTimer = true; _ = StopSessionAsync(id); return; } _ = NotifyAsync("started", e); } private void OnPlaybackStopped(object? sender, PlaybackStopEventArgs e) { var id = e.Session?.Id; if (id is null) { return; } var t = Get(id); var config = Plugin.Instance?.Configuration; if (t.StoppingByTimer) { // Our own stop (minutes elapsed, or the autoplayed next episode): countdown already reported/needed. t.StoppingByTimer = false; Disarm(t); _ = NotifyAsync("stopped", e); return; } if (t.Mode == TimerMode.EndOfItem && FinishedItem(e)) { // Episode/movie ended: kill whatever autoplays next, and start the lights-off countdown now. Disarm(t); t.StopNextStartUntil = DateTime.UtcNow + AutoplayWindow; _ = NotifyAsync("stopped", e); return; } if (t.Mode != TimerMode.Off) { // Stopped by hand while the sleep timer was on. Disarm(t); _ = NotifyAsync("stopped", e); return; } if (config?.CountdownOnEveryStop == true) { _ = NotifyAsync("stopped", e); } } private void OnSessionEnded(object? sender, SessionEventArgs e) { if (e.SessionInfo?.Id is { } id && _timers.TryRemove(id, out var t) && t.Mode != TimerMode.Off) { _log.LogInformation("Sleep timer: session {Session} ended with the timer on", id); _ = NotifyAsync("stopped", null); } } private void CheckDeadlines() { var now = DateTime.UtcNow; foreach (var (id, t) in _timers) { if (t.Mode == TimerMode.Minutes && t.Deadline is { } d && now >= d) { _log.LogInformation("Sleep timer: {Minutes} min elapsed in session {Session}, stopping playback", t.Minutes, id); t.Deadline = null; t.StoppingByTimer = true; _ = StopSessionAsync(id); } } } private static bool FinishedItem(PlaybackStopEventArgs e) { if (e.PlayedToCompletion) { return true; } // Some clients report the end without PlayedToCompletion: treat the last 2% (or 30 s) as finished. var runtime = e.Item?.RunTimeTicks; var pos = e.PlaybackPositionTicks; if (runtime is > 0 && pos is { } p) { var margin = Math.Max(runtime.Value / 50, TimeSpan.FromSeconds(30).Ticks); return p >= runtime.Value - margin; } return false; } private static void Disarm(SessionTimer t) { t.Mode = TimerMode.Off; t.Deadline = null; t.Minutes = null; } private async Task StopSessionAsync(string sessionId) { try { await _sessions.SendPlaystateCommand(sessionId, sessionId, new PlaystateRequest { Command = PlaystateCommand.Stop }, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { _log.LogWarning(ex, "Sleep timer: could not stop session {Session}", sessionId); if (_timers.TryGetValue(sessionId, out var t)) { t.StoppingByTimer = false; } } } private async Task NotifyAsync(string evt, PlaybackProgressEventArgs? e) { var config = Plugin.Instance?.Configuration; if (config is null || string.IsNullOrWhiteSpace(config.WebhookUrl)) { return; } var payload = new { @event = evt, cooldown_minutes = config.CooldownMinutes, user = e?.Session?.UserName, device = e?.Session?.DeviceName, item = e?.Item?.Name, }; try { using var resp = await _http.PostAsJsonAsync(config.WebhookUrl, payload).ConfigureAwait(false); _log.LogInformation("Sleep timer: told Home Assistant '{Event}' ({Status})", evt, (int)resp.StatusCode); } catch (Exception ex) { _log.LogWarning(ex, "Sleep timer: webhook '{Event}' failed", evt); } } }