From 8d456442e6c7b9e166a98e8b1867b1108f012341 Mon Sep 17 00:00:00 2001 From: Nik Rozman Date: Fri, 30 Oct 2026 00:22:48 +0100 Subject: [PATCH] Lights Off Timer: Jellyfin sleep timer that turns off Home Assistant lights Jellyfin 12.2 plugin that adds a sleep-timer button next to the volume control in the web player (end of this episode/movie, or N minutes). When playback stops with the timer on, it calls a Home Assistant webhook that turns the lights off after a cooldown; starting playback cancels it. The repository doubles as a Jellyfin plugin repository: manifest.json at the root points at the release zips in dist/. build.sh builds in the .NET 10 SDK container and adds new versions to the manifest. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 5 + README.md | 73 +++++ build.sh | 52 ++++ dist/lightsofftimer_1.0.2.0.zip | Bin 0 -> 19089 bytes home-assistant/jellyfin_lights.yaml | 56 ++++ manifest.json | 20 ++ .../Configuration/PluginConfiguration.cs | 18 ++ .../Configuration/configPage.html | 73 +++++ .../Jellyfin.Plugin.LightsOffTimer.csproj | 24 ++ .../LightsOffTimerController.cs | 93 +++++++ src/Jellyfin.Plugin.LightsOffTimer/Plugin.cs | 36 +++ .../ScriptInjection.cs | 70 +++++ .../ServiceRegistrator.cs | 17 ++ .../TimerManager.cs | 250 ++++++++++++++++++ .../Web/client.js | 147 ++++++++++ 15 files changed, 934 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 build.sh create mode 100644 dist/lightsofftimer_1.0.2.0.zip create mode 100644 home-assistant/jellyfin_lights.yaml create mode 100644 manifest.json create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/Configuration/PluginConfiguration.cs create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/Configuration/configPage.html create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/Jellyfin.Plugin.LightsOffTimer.csproj create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/LightsOffTimerController.cs create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/Plugin.cs create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/ScriptInjection.cs create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/ServiceRegistrator.cs create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/TimerManager.cs create mode 100644 src/Jellyfin.Plugin.LightsOffTimer/Web/client.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bec9690 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +bin/ +obj/ +.build/ +*.user +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..680202b --- /dev/null +++ b/README.md @@ -0,0 +1,73 @@ +# Lights Off Timer — Jellyfin sleep timer that turns off your Home Assistant lights + +A Jellyfin plugin that adds a **sleep-timer button next to the volume control** in the web player. +Pick *End of this episode/movie* (the default) or a number of minutes; when playback stops, +the plugin tells **Home Assistant**, which turns the lights off after a cooldown (15 minutes by default). +Starting playback again cancels the countdown. + +- **End of this episode/movie** — when the item finishes, the next autoplayed episode is stopped. +- **15 / 30 / 45 / 60 / 90 minutes** (configurable) — playback is stopped when the time is up. +- **Lights off** — on that stop (or when you stop playback yourself while the timer is on), + Home Assistant starts its countdown and turns the lights off when it runs out. + +Built for **Jellyfin 12.2** (`targetAbi 12.2.0.0`). + +## Install + +1. In Jellyfin: **Dashboard → Plugins → Repositories → +** + - Name: `Lights Off Timer` + - URL: `https://git.piskot.si/nikrozman/jellyfin-lights-out-ha/raw/branch/master/manifest.json` +2. **Catalog → Lights Off Timer → Install**, then restart Jellyfin. +3. **Plugins → Lights Off Timer → Settings**: + - **Home Assistant webhook URL** — `https:///api/webhook/` + - **Lights off after (minutes)** — the cooldown, default 15 + - **Timer presets** — minutes shown in the menu, default `15,30,45,60,90` + - **Start the countdown on every playback stop** — off by default (only when the sleep timer was on) +4. Reload the Jellyfin web page. The moon button appears next to the volume slider while a video plays. + +## Home Assistant + +Copy [`home-assistant/jellyfin_lights.yaml`](home-assistant/jellyfin_lights.yaml) into a package, +set a long random `webhook_id`, reload **Timers** and **Automations**, and put the matching URL in the plugin settings. +It creates `timer.movie_lights_off`, which you can show on a dashboard. + +The plugin sends: + +| When | Payload | +|---|---| +| Playback starts (any item) | `{"event": "started"}` | +| Playback stops with the sleep timer on (or every stop, if enabled) | `{"event": "stopped", "cooldown_minutes": 15, "user": "…", "device": "…", "item": "…"}` | + +The webhook id is the only secret: anyone who knows it can trigger the automation. + +## Limitations + +- The button only exists in **Jellyfin Web** (browser and Jellyfin Media Player). Native apps + (Swiftfin, Android TV, Apple TV…) can't be extended by plugins. +- Stopping playback uses Jellyfin's remote-control command, so the client must support remote control + (Jellyfin Web does). +- Timers live in memory: restarting Jellyfin clears them. + +## How it works + +- `TimerManager` keeps a timer per playback session and listens to Jellyfin's `PlaybackStart` / + `PlaybackStopped` events. It stops playback with `SendPlaystateCommand(Stop)` and posts to the webhook. +- `ScriptInjection` adds ` + + + diff --git a/src/Jellyfin.Plugin.LightsOffTimer/Jellyfin.Plugin.LightsOffTimer.csproj b/src/Jellyfin.Plugin.LightsOffTimer/Jellyfin.Plugin.LightsOffTimer.csproj new file mode 100644 index 0000000..c5f36ab --- /dev/null +++ b/src/Jellyfin.Plugin.LightsOffTimer/Jellyfin.Plugin.LightsOffTimer.csproj @@ -0,0 +1,24 @@ + + + net10.0 + Jellyfin.Plugin.LightsOffTimer + 1.0.2.0 + 1.0.2.0 + enable + enable + false + false + + + + + + + + + + + + + + diff --git a/src/Jellyfin.Plugin.LightsOffTimer/LightsOffTimerController.cs b/src/Jellyfin.Plugin.LightsOffTimer/LightsOffTimerController.cs new file mode 100644 index 0000000..97c928f --- /dev/null +++ b/src/Jellyfin.Plugin.LightsOffTimer/LightsOffTimerController.cs @@ -0,0 +1,93 @@ +using System.Reflection; +using MediaBrowser.Controller.Session; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Plugin.LightsOffTimer; + +[ApiController] +[Route("LightsOffTimer")] +public class LightsOffTimerController : ControllerBase +{ + private readonly TimerManager _timers; + private readonly ISessionManager _sessions; + + public LightsOffTimerController(TimerManager timers, ISessionManager sessions) + { + _timers = timers; + _sessions = sessions; + } + + public record SetRequest(string Mode, int? Minutes); + + /// The player-button script (public: it contains no secrets and is loaded before login). + [HttpGet("client.js")] + [AllowAnonymous] + public ActionResult ClientScript() + { + // A client.js in the plugin's data folder overrides the built-in one (tweaks without a rebuild/restart). + var overridePath = Plugin.Instance is { } p ? Path.Combine(p.DataFolderPath, "client.js") : null; + if (overridePath is not null && System.IO.File.Exists(overridePath)) + { + return PhysicalFile(overridePath, "application/javascript; charset=utf-8"); + } + + var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Jellyfin.Plugin.LightsOffTimer.Web.client.js"); + return stream is null ? NotFound() : File(stream, "application/javascript; charset=utf-8"); + } + + /// Sleep-timer state for the caller's own playback session. + [HttpGet("State")] + [Authorize] + public ActionResult GetState() => CurrentSession() is { } s ? Ok(Describe(s)) : NotFound("No active session for this device."); + + [HttpPost("Set")] + [Authorize] + public ActionResult Set([FromBody] SetRequest req) + { + var s = CurrentSession(); + if (s is null) + { + return NotFound("No active session for this device."); + } + + var mode = req.Mode?.ToLowerInvariant() switch + { + "end" => TimerMode.EndOfItem, + "minutes" when req.Minutes is > 0 and <= 600 => TimerMode.Minutes, + "off" => TimerMode.Off, + _ => (TimerMode?)null, + }; + if (mode is null) + { + return BadRequest("mode must be 'end', 'off' or 'minutes' (1-600)."); + } + + _timers.Set(s.Id, mode.Value, req.Minutes); + return Ok(Describe(s)); + } + + private SessionInfo? CurrentSession() + { + // Jellyfin's auth handler puts these on the request principal (Jellyfin.Api InternalClaimTypes). + var userId = Guid.TryParse(User.FindFirst("Jellyfin-UserId")?.Value, out var u) ? u : Guid.Empty; + var deviceId = User.FindFirst("Jellyfin-DeviceId")?.Value; + return _sessions.Sessions.FirstOrDefault(x => x.UserId == userId && x.DeviceId == deviceId); + } + + private object Describe(SessionInfo s) + { + var t = _timers.Get(s.Id); + var config = Plugin.Instance?.Configuration; + return new + { + mode = t.Mode switch { TimerMode.EndOfItem => "end", TimerMode.Minutes => "minutes", _ => "off" }, + minutes = t.Minutes, + remainingSeconds = t.Deadline is { } d ? Math.Max(0, (int)(d - DateTime.UtcNow).TotalSeconds) : (int?)null, + itemType = s.NowPlayingItem?.Type.ToString(), + presets = (config?.MinutePresets ?? "15,30,45,60,90").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(x => int.TryParse(x, out var m) ? m : 0).Where(m => m > 0).ToArray(), + cooldownMinutes = config?.CooldownMinutes ?? 15, + }; + } +} diff --git a/src/Jellyfin.Plugin.LightsOffTimer/Plugin.cs b/src/Jellyfin.Plugin.LightsOffTimer/Plugin.cs new file mode 100644 index 0000000..5bcf969 --- /dev/null +++ b/src/Jellyfin.Plugin.LightsOffTimer/Plugin.cs @@ -0,0 +1,36 @@ +using Jellyfin.Plugin.LightsOffTimer.Configuration; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Serialization; + +namespace Jellyfin.Plugin.LightsOffTimer; + +/// Sleep timer in the player that also turns the house lights off (via a Home Assistant webhook). +public class Plugin : BasePlugin, IHasWebPages +{ + public static readonly Guid PluginId = Guid.Parse("6b1c3f0e-6f2a-4c55-9d1e-4a7e2c9b5d31"); + + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + } + + public static Plugin? Instance { get; private set; } + + public override string Name => "Lights Off Timer"; + + public override Guid Id => PluginId; + + public override string Description => "Sleep timer in the player (default: end of this episode/movie) that tells Home Assistant to turn the lights off after playback stops."; + + public IEnumerable GetPages() => new[] + { + new PluginPageInfo + { + Name = "LightsOffTimer", + EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.html", + }, + }; +} diff --git a/src/Jellyfin.Plugin.LightsOffTimer/ScriptInjection.cs b/src/Jellyfin.Plugin.LightsOffTimer/ScriptInjection.cs new file mode 100644 index 0000000..5971fff --- /dev/null +++ b/src/Jellyfin.Plugin.LightsOffTimer/ScriptInjection.cs @@ -0,0 +1,70 @@ +using System.Text; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; + +namespace Jellyfin.Plugin.LightsOffTimer; + +/// Adds the player-button script to Jellyfin Web's index.html as it is served (nothing on disk changes). +public class ScriptInjectionStartupFilter : IStartupFilter +{ + private const string Tag = ""; + + public Action Configure(Action next) => app => + { + app.Use(async (ctx, nextMiddleware) => + { + var path = ctx.Request.Path.Value ?? string.Empty; + var isIndex = HttpMethods.IsGet(ctx.Request.Method) + && (path.EndsWith("/web/", StringComparison.OrdinalIgnoreCase) + || path.EndsWith("/web/index.html", StringComparison.OrdinalIgnoreCase)); + if (!isIndex) + { + await nextMiddleware().ConfigureAwait(false); + return; + } + + // Ask for the plain file (Jellyfin serves a pre-compressed copy otherwise) and skip 304s. + ctx.Request.Headers.Remove("Accept-Encoding"); + ctx.Request.Headers.Remove("If-None-Match"); + ctx.Request.Headers.Remove("If-Modified-Since"); + + var original = ctx.Response.Body; + await using var buffer = new MemoryStream(); + ctx.Response.Body = buffer; + try + { + await nextMiddleware().ConfigureAwait(false); + } + finally + { + ctx.Response.Body = original; + } + + buffer.Position = 0; + var isHtml = ctx.Response.StatusCode == 200 + && (ctx.Response.ContentType?.StartsWith("text/html", StringComparison.OrdinalIgnoreCase) ?? false) + && !ctx.Response.Headers.ContainsKey("Content-Encoding"); + if (!isHtml) + { + await buffer.CopyToAsync(original).ConfigureAwait(false); + return; + } + + var html = Encoding.UTF8.GetString(buffer.ToArray()); + if (!html.Contains("LightsOffTimer/client.js", StringComparison.Ordinal)) + { + var at = html.LastIndexOf("", StringComparison.OrdinalIgnoreCase); + html = at >= 0 ? html.Insert(at, Tag) : html + Tag; + } + + var bytes = Encoding.UTF8.GetBytes(html); + ctx.Response.ContentLength = bytes.Length; + ctx.Response.Headers.Remove("ETag"); + ctx.Response.Headers.CacheControl = "no-cache"; + await original.WriteAsync(bytes).ConfigureAwait(false); + }); + + next(app); + }; +} diff --git a/src/Jellyfin.Plugin.LightsOffTimer/ServiceRegistrator.cs b/src/Jellyfin.Plugin.LightsOffTimer/ServiceRegistrator.cs new file mode 100644 index 0000000..9e3b93a --- /dev/null +++ b/src/Jellyfin.Plugin.LightsOffTimer/ServiceRegistrator.cs @@ -0,0 +1,17 @@ +using MediaBrowser.Controller; +using MediaBrowser.Controller.Plugins; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Jellyfin.Plugin.LightsOffTimer; + +public class ServiceRegistrator : IPluginServiceRegistrator +{ + public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost) + { + serviceCollection.AddSingleton(); + serviceCollection.AddHostedService(sp => sp.GetRequiredService()); + serviceCollection.AddTransient(); + } +} diff --git a/src/Jellyfin.Plugin.LightsOffTimer/TimerManager.cs b/src/Jellyfin.Plugin.LightsOffTimer/TimerManager.cs new file mode 100644 index 0000000..c437625 --- /dev/null +++ b/src/Jellyfin.Plugin.LightsOffTimer/TimerManager.cs @@ -0,0 +1,250 @@ +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); + } + } +} diff --git a/src/Jellyfin.Plugin.LightsOffTimer/Web/client.js b/src/Jellyfin.Plugin.LightsOffTimer/Web/client.js new file mode 100644 index 0000000..f5d0887 --- /dev/null +++ b/src/Jellyfin.Plugin.LightsOffTimer/Web/client.js @@ -0,0 +1,147 @@ +// Lights Off Timer: sleep-timer button in the Jellyfin Web video player, next to the volume control. +(function () { + 'use strict'; + if (window.__lightsOffTimer) { return; } + window.__lightsOffTimer = true; + + const ICON = ''; + + const css = document.createElement('style'); + css.textContent = ` + .btnLightsOffTimer { position: relative; margin-left: .8em; overflow: visible !important; } + .btnLightsOffTimer .lotIcon { font-size: 1.66em; display: inline-flex; } + .btnLightsOffTimer.lotActive { color: #ffcc66; } + .btnLightsOffTimer .lotBadge { position: absolute; left: 50%; bottom: -0.15em; transform: translateX(-50%); font-size: 0.55em; font-weight: 700; + letter-spacing: .02em; white-space: nowrap; background: #ffcc66; color: #111; border-radius: 0.6em; padding: 0 0.4em; line-height: 1.45em; pointer-events: none; } + .lotMenu { position: fixed; z-index: 99999; min-width: 17em; white-space: nowrap; background: rgba(20,20,20,.97); color: #fff; + border-radius: .5em; box-shadow: 0 .4em 1.6em rgba(0,0,0,.6); padding: .4em 0; font-size: .95em; } + .lotMenu .lotHead { padding: .35em 1em .45em; opacity: .7; font-size: .85em; } + .lotMenu button { display: flex; justify-content: space-between; width: 100%; padding: .55em 1em; border: 0; + background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; } + .lotMenu button:hover, .lotMenu button:focus { background: rgba(255,255,255,.12); outline: none; } + .lotMenu button.lotOn { color: #ffcc66; } + .lotMenu .lotHint { opacity: .55; font-size: .85em; margin-left: 1em; } + `; + document.head.appendChild(css); + + let state = null; + let menu = null; + + function api(method, path, body) { + const client = window.ApiClient; + if (!client) { return Promise.reject(new Error('ApiClient not ready')); } + const opts = { type: method, url: client.getUrl('LightsOffTimer/' + path), dataType: 'json' }; + if (body) { opts.data = JSON.stringify(body); opts.contentType = 'application/json'; } + return client.ajax(opts); + } + + function endLabel() { + return state && state.itemType === 'Episode' ? 'End of this episode' : (state && state.itemType === 'Movie' ? 'End of this movie' : 'End of this episode/movie'); + } + + function badgeText() { + if (!state || state.mode === 'off') { return ''; } + if (state.mode === 'end') { return 'END'; } + return state.remainingSeconds != null ? Math.ceil(state.remainingSeconds / 60) + 'm' : ''; + } + + function render() { + document.querySelectorAll('.btnLightsOffTimer').forEach(btn => { + const on = state && state.mode !== 'off'; + btn.classList.toggle('lotActive', !!on); + btn.title = on ? (state.mode === 'end' ? 'Sleep timer: ' + endLabel().toLowerCase() : 'Sleep timer: ' + badgeText() + ' left') : 'Sleep timer'; + let badge = btn.querySelector('.lotBadge'); + const text = badgeText(); + if (text && !badge) { badge = document.createElement('span'); badge.className = 'lotBadge'; btn.appendChild(badge); } + if (badge) { badge.textContent = text; badge.style.display = text ? '' : 'none'; } + }); + } + + function refresh() { + return api('GET', 'State').then(s => { state = s; render(); }).catch(() => { /* no session yet */ }); + } + + function set(mode, minutes) { + closeMenu(); + return api('POST', 'Set', { mode: mode, minutes: minutes || null }).then(s => { state = s; render(); }).catch(err => { + console.warn('[LightsOffTimer] set failed', err); + }); + } + + function closeMenu() { + if (menu) { menu.remove(); menu = null; document.removeEventListener('pointerdown', outside, true); } + } + + function outside(e) { + if (menu && !menu.contains(e.target) && !e.target.closest('.btnLightsOffTimer')) { closeMenu(); } + } + + function openMenu(btn) { + closeMenu(); + const cool = state ? state.cooldownMinutes : 15; + menu = document.createElement('div'); + menu.className = 'lotMenu'; + const head = document.createElement('div'); + head.className = 'lotHead'; + head.textContent = 'Stop playback, then lights off ' + cool + ' min later'; + menu.appendChild(head); + + const items = [{ mode: 'end', label: endLabel(), hint: 'default' }]; + ((state && state.presets) || [15, 30, 45, 60, 90]).forEach(m => items.push({ mode: 'minutes', minutes: m, label: m + ' minutes' })); + items.push({ mode: 'off', label: 'Off' }); + + items.forEach(it => { + const b = document.createElement('button'); + const active = state && state.mode === it.mode && (it.mode !== 'minutes' || state.minutes === it.minutes); + if (active && it.mode !== 'off') { b.classList.add('lotOn'); } + b.innerHTML = ''; + b.firstChild.textContent = (active && it.mode !== 'off' ? '✓ ' : '') + it.label; + b.lastChild.textContent = active && it.mode === 'minutes' && state.remainingSeconds != null + ? Math.ceil(state.remainingSeconds / 60) + ' min left' : (it.hint || ''); + b.addEventListener('click', e => { e.stopPropagation(); set(it.mode, it.minutes); }); + menu.appendChild(b); + }); + + document.body.appendChild(menu); + const r = btn.getBoundingClientRect(); + const w = menu.offsetWidth, h = menu.offsetHeight; + menu.style.left = Math.max(8, Math.min(window.innerWidth - w - 8, r.left + r.width / 2 - w / 2)) + 'px'; + menu.style.top = Math.max(8, r.top - h - 8) + 'px'; + document.addEventListener('pointerdown', outside, true); + (menu.querySelector('.lotOn') || menu.querySelector('button')).focus(); + } + + function addButton(osd) { + if (osd.querySelector('.btnLightsOffTimer')) { return; } + const volume = osd.querySelector('.osdVolumeSliderContainer'); + const mute = osd.querySelector('.buttonMute'); + const anchor = volume || mute || osd.querySelector('.btnVideoOsdSettings'); + if (!anchor) { return; } + + const btn = document.createElement('button'); + btn.type = 'button'; + btn.setAttribute('is', 'paper-icon-button-light'); + btn.className = ((mute && mute.className) || 'autoSize paper-icon-button-light').replace(/\bbuttonMute\b/, '') + ' btnLightsOffTimer'; + btn.innerHTML = '' + ICON + ''; + btn.addEventListener('click', e => { + e.preventDefault(); + e.stopPropagation(); + if (menu) { closeMenu(); return; } + refresh().then(() => openMenu(btn)); + }); + + if (volume) { volume.insertAdjacentElement('afterend', btn); } else { anchor.insertAdjacentElement('beforebegin', btn); } + refresh(); + } + + function scan() { + document.querySelectorAll('.videoOsdBottom-maincontrols, .videoOsdBottom .buttons').forEach(addButton); + } + + new MutationObserver(scan).observe(document.documentElement, { childList: true, subtree: true }); + scan(); + + // Keep the badge current while a player is open. + setInterval(() => { if (document.querySelector('.btnLightsOffTimer')) { refresh(); } }, 15000); +})();