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 <noreply@anthropic.com>
This commit is contained in:
commit
8d456442e6
15 files changed
+934
No files matched your search
@@ -0,0 +1,18 @@
|
||||
using MediaBrowser.Model.Plugins;
|
||||
|
||||
namespace Jellyfin.Plugin.LightsOffTimer.Configuration;
|
||||
|
||||
public class PluginConfiguration : BasePluginConfiguration
|
||||
{
|
||||
/// <summary>Home Assistant webhook, e.g. https://ha.example/api/webhook/secret-id.</summary>
|
||||
public string WebhookUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Minutes Home Assistant waits after playback stops before turning the lights off.</summary>
|
||||
public int CooldownMinutes { get; set; } = 15;
|
||||
|
||||
/// <summary>Also start the lights-off countdown on every playback stop, not only when the sleep timer is on.</summary>
|
||||
public bool CountdownOnEveryStop { get; set; }
|
||||
|
||||
/// <summary>Comma-separated minute presets shown in the player menu.</summary>
|
||||
public string MinutePresets { get; set; } = "15,30,45,60,90";
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Lights Off Timer</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="LightsOffTimerConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-checkbox">
|
||||
<div data-role="content">
|
||||
<div class="content-primary">
|
||||
<form id="LightsOffTimerConfigForm">
|
||||
<h2>Lights Off Timer</h2>
|
||||
<p>Adds a sleep-timer button next to the volume control in the web player. When playback stops with the
|
||||
timer on, Home Assistant is told, and it turns the lights off after the cooldown below. Starting
|
||||
playback again cancels it.</p>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="WebhookUrl">Home Assistant webhook URL</label>
|
||||
<input id="WebhookUrl" name="WebhookUrl" type="url" is="emby-input" />
|
||||
<div class="fieldDescription">https://your-home-assistant/api/webhook/<webhook id>. Keep it secret.</div>
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="CooldownMinutes">Lights off after (minutes)</label>
|
||||
<input id="CooldownMinutes" name="CooldownMinutes" type="number" min="1" max="240" is="emby-input" />
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="MinutePresets">Timer presets (minutes, comma separated)</label>
|
||||
<input id="MinutePresets" name="MinutePresets" type="text" is="emby-input" />
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="CountdownOnEveryStop" name="CountdownOnEveryStop" type="checkbox" is="emby-checkbox" />
|
||||
<span>Start the lights-off countdown on every playback stop</span>
|
||||
</label>
|
||||
<div class="fieldDescription checkboxFieldDescription">Off: only when the sleep timer was on for that playback.</div>
|
||||
</div>
|
||||
<div>
|
||||
<button is="emby-button" type="submit" class="raised button-submit block emby-button"><span>Save</span></button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
var LightsOffTimerConfig = { pluginUniqueId: '6b1c3f0e-6f2a-4c55-9d1e-4a7e2c9b5d31' };
|
||||
|
||||
document.querySelector('#LightsOffTimerConfigPage').addEventListener('pageshow', function () {
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.getPluginConfiguration(LightsOffTimerConfig.pluginUniqueId).then(function (config) {
|
||||
document.querySelector('#WebhookUrl').value = config.WebhookUrl || '';
|
||||
document.querySelector('#CooldownMinutes').value = config.CooldownMinutes || 15;
|
||||
document.querySelector('#MinutePresets').value = config.MinutePresets || '15,30,45,60,90';
|
||||
document.querySelector('#CountdownOnEveryStop').checked = !!config.CountdownOnEveryStop;
|
||||
Dashboard.hideLoadingMsg();
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelector('#LightsOffTimerConfigForm').addEventListener('submit', function (e) {
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.getPluginConfiguration(LightsOffTimerConfig.pluginUniqueId).then(function (config) {
|
||||
config.WebhookUrl = document.querySelector('#WebhookUrl').value.trim();
|
||||
config.CooldownMinutes = parseInt(document.querySelector('#CooldownMinutes').value, 10) || 15;
|
||||
config.MinutePresets = document.querySelector('#MinutePresets').value.trim();
|
||||
config.CountdownOnEveryStop = document.querySelector('#CountdownOnEveryStop').checked;
|
||||
ApiClient.updatePluginConfiguration(LightsOffTimerConfig.pluginUniqueId, config).then(function (result) {
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
});
|
||||
});
|
||||
e.preventDefault();
|
||||
return false;
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Jellyfin.Plugin.LightsOffTimer</RootNamespace>
|
||||
<AssemblyVersion>1.0.2.0</AssemblyVersion>
|
||||
<FileVersion>1.0.2.0</FileVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Compile-time only: Jellyfin provides these at runtime. Keep the version at the targetAbi. -->
|
||||
<PackageReference Include="Jellyfin.Controller" Version="12.2.0" ExcludeAssets="runtime" />
|
||||
<PackageReference Include="Jellyfin.Model" Version="12.2.0" ExcludeAssets="runtime" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Configuration\configPage.html" />
|
||||
<EmbeddedResource Include="Web\client.js" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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);
|
||||
|
||||
/// <summary>The player-button script (public: it contains no secrets and is loaded before login).</summary>
|
||||
[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");
|
||||
}
|
||||
|
||||
/// <summary>Sleep-timer state for the caller's own playback session.</summary>
|
||||
[HttpGet("State")]
|
||||
[Authorize]
|
||||
public ActionResult<object> GetState() => CurrentSession() is { } s ? Ok(Describe(s)) : NotFound("No active session for this device.");
|
||||
|
||||
[HttpPost("Set")]
|
||||
[Authorize]
|
||||
public ActionResult<object> 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Sleep timer in the player that also turns the house lights off (via a Home Assistant webhook).</summary>
|
||||
public class Plugin : BasePlugin<PluginConfiguration>, 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<PluginPageInfo> GetPages() => new[]
|
||||
{
|
||||
new PluginPageInfo
|
||||
{
|
||||
Name = "LightsOffTimer",
|
||||
EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.html",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Jellyfin.Plugin.LightsOffTimer;
|
||||
|
||||
/// <summary>Adds the player-button script to Jellyfin Web's index.html as it is served (nothing on disk changes).</summary>
|
||||
public class ScriptInjectionStartupFilter : IStartupFilter
|
||||
{
|
||||
private const string Tag = "<script defer src=\"../LightsOffTimer/client.js\"></script>";
|
||||
|
||||
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> 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("</body>", 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);
|
||||
};
|
||||
}
|
||||
@@ -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<TimerManager>();
|
||||
serviceCollection.AddHostedService(sp => sp.GetRequiredService<TimerManager>());
|
||||
serviceCollection.AddTransient<IStartupFilter, ScriptInjectionStartupFilter>();
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
/// <summary>Sleep-timer state for one playback session (one device of one user).</summary>
|
||||
public sealed class SessionTimer
|
||||
{
|
||||
public TimerMode Mode { get; set; }
|
||||
|
||||
public DateTime? Deadline { get; set; }
|
||||
|
||||
public int? Minutes { get; set; }
|
||||
|
||||
/// <summary>Set when the timed item finished: the next item that starts (autoplay) gets stopped.</summary>
|
||||
public DateTime? StopNextStartUntil { get; set; }
|
||||
|
||||
/// <summary>Set while we are stopping playback ourselves, so the resulting stop is reported once.</summary>
|
||||
public bool StoppingByTimer { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tracks sleep timers per session, stops playback when they expire and tells Home Assistant
|
||||
/// ("started" cancels the lights-off countdown, "stopped" starts it).
|
||||
/// </summary>
|
||||
public sealed class TimerManager : IHostedService, IDisposable
|
||||
{
|
||||
private static readonly TimeSpan AutoplayWindow = TimeSpan.FromSeconds(45);
|
||||
|
||||
private readonly ISessionManager _sessions;
|
||||
private readonly ILogger<TimerManager> _log;
|
||||
private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(10) };
|
||||
private readonly ConcurrentDictionary<string, SessionTimer> _timers = new();
|
||||
private Timer? _tick;
|
||||
|
||||
public TimerManager(ISessionManager sessions, ILogger<TimerManager> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 = '<svg viewBox="0 0 24 24" width="1em" height="1em" aria-hidden="true" style="fill:currentColor;vertical-align:middle">'
|
||||
+ '<path d="M17.75,4.09L15.22,6.03L16.13,9.09L13.5,7.28L10.87,9.09L11.78,6.03L9.25,4.09L12.44,4L13.5,1L14.56,4L17.75,4.09M21.25,11L19.61,12.25L20.2,14.23L18.5,13.06L16.8,14.23L17.39,12.25L15.75,11L17.81,10.95L18.5,9L19.19,10.95L21.25,11M18.97,15.95C19.8,15.87 20.69,17.05 20.16,17.8C19.84,18.25 19.5,18.67 19.08,19.07C15.17,23 8.84,23 4.94,19.07C1.03,15.17 1.03,8.83 4.94,4.93C5.34,4.53 5.76,4.17 6.21,3.85C6.96,3.32 8.14,4.21 8.06,5.04C7.79,7.9 8.75,10.87 10.95,13.06C13.14,15.26 16.1,16.22 18.97,15.95M17.33,17.97C14.5,17.81 11.7,16.64 9.53,14.5C7.36,12.31 6.2,9.5 6.04,6.68C3.23,9.82 3.34,14.64 6.35,17.66C9.37,20.67 14.19,20.78 17.33,17.97Z"/></svg>';
|
||||
|
||||
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 = '<span></span><span class="lotHint"></span>';
|
||||
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 = '<span class="lotIcon">' + ICON + '</span>';
|
||||
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);
|
||||
})();
|
||||
Reference in new issue
Block a user