From e79def9f71f83c716059f2a5d0453ac0b46e1047 Mon Sep 17 00:00:00 2001 From: Ben Date: Mon, 16 Nov 2026 14:03:31 -0500 Subject: [PATCH 1/9] Added Moonfin/AccessWindow: the user's access schedule judged on the server's clock Jellyfin judges an access schedule against the server's local time, so a client in another time zone can't tell when the account closes or next opens. GET Moonfin/AccessWindow answers that with Jellyfin's own rule: { allowed, secondsUntilClose, secondsUntilOpen }, the durations rounded up so a timer set from them never fires early. Adjacent entries run together and the server's daylight saving changes are counted, so clients need no clock or zone handling. It skips the schedule check, as does Ping, which gains accessWindowSupported. Co-Authored-By: Claude Opus 5.5 --- .../backend/Api/AccessWindowController.cs | 307 ++++++++++++++++++ Jellyfin/backend/Api/MoonfinController.cs | 14 +- .../Moonfin.Server.Tests/AccessWindowTests.cs | 289 +++++++++++++++++ 3 files changed, 609 insertions(+), 1 deletion(-) create mode 100644 Jellyfin/backend/Api/AccessWindowController.cs create mode 100644 Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs diff --git a/Jellyfin/backend/Api/AccessWindowController.cs b/Jellyfin/backend/Api/AccessWindowController.cs new file mode 100644 index 00000000..bc33c53a --- /dev/null +++ b/Jellyfin/backend/Api/AccessWindowController.cs @@ -0,0 +1,307 @@ +using System.Collections; +using System.Net.Mime; +using System.Text.Json.Serialization; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Moonfin.Server.Helpers; + +namespace Moonfin.Server.Api; + +/// +/// Whether the signed in user's access schedule lets them in right now, and how long until that +/// changes. Jellyfin judges the schedule against the server's local time, so a client in another +/// time zone can't work this out itself; this answers it with the same rule Jellyfin enforces, +/// as relative durations a client can set a timer from without knowing the server's clock. +/// +[ApiController] +[Route("Moonfin")] +[Produces(MediaTypeNames.Application.Json)] +public class AccessWindowController : ControllerBase +{ + private readonly IServiceProvider _services; + + public AccessWindowController(IServiceProvider services) + { + _services = services; + } + + /// The user's access window: allowed now, and seconds until it closes or next opens. + /// + /// Skips the access-schedule check: a user outside their hours is exactly the one whose client + /// needs to know when the account next opens. + /// + [HttpGet("AccessWindow")] + [Authorize(Policy = "IgnoreParentalControl")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public ActionResult GetAccessWindow() + { + // Jellyfin doesn't hold administrators to a schedule + if (this.IsAdminFromClaims()) + { + return Ok(new AccessWindowResponse { Allowed = true }); + } + + var userId = this.GetUserIdFromClaims(); + if (userId is not { } id || id == Guid.Empty) + { + return BadRequest(); + } + + var user = UserReflection.ResolveUser(_services, id); + var entries = user == null ? null : ReadSchedule(user); + if (entries == null) + { + return Problem("The user's access schedule couldn't be read on this server version."); + } + + return Ok(Evaluate(entries, DateTimeOffset.UtcNow, TimeZoneInfo.Local)); + } + + /// + /// The user's access schedule entries, read by name because Jellyfin's User and AccessSchedule + /// types moved between 10.10 and 10.11. Null when they can't be read. + /// + internal static List? ReadSchedule(object user) + { + try + { + if (user.GetType().GetProperty("AccessSchedules")?.GetValue(user) is not IEnumerable schedules) + { + return null; + } + + var entries = new List(); + foreach (var schedule in schedules) + { + var type = schedule.GetType(); + var day = type.GetProperty("DayOfWeek")?.GetValue(schedule)?.ToString(); + var start = type.GetProperty("StartHour")?.GetValue(schedule); + var end = type.GetProperty("EndHour")?.GetValue(schedule); + if (day == null || start == null || end == null) + { + return null; + } + + entries.Add(new ScheduleEntry(day, Convert.ToDouble(start), Convert.ToDouble(end))); + } + + return entries; + } + catch + { + return null; + } + } + + // The schedule repeats every week, so a change that ever comes comes within this + private static readonly TimeSpan LookAhead = TimeSpan.FromDays(8); + + /// + /// The access window at for a server in , judged + /// the way Jellyfin judges it: allowed when no entries, or when any entry's day matches the + /// server's local day and the local hour is between its start and end, both included. Adjacent + /// and overlapping entries run together, so the durations are to the real change, and the + /// server's daylight saving changes are counted. + /// + internal static AccessWindowResponse Evaluate(IReadOnlyList entries, DateTimeOffset now, TimeZoneInfo zone) + { + var start = now.ToUniversalTime(); + var allowed = IsAllowed(entries, start, zone); + var response = new AccessWindowResponse { Allowed = allowed }; + if (entries.Count == 0) + { + return response; + } + + var change = NextChange(entries, start, zone, allowed); + if (change is { } at) + { + // Rounded up, so a timer set from it never fires before the change + var seconds = (long)Math.Ceiling((at - start).TotalSeconds); + if (allowed) + { + response.SecondsUntilClose = seconds; + } + else + { + response.SecondsUntilOpen = seconds; + } + } + + return response; + } + + /// Jellyfin's own rule (UserEntityExtensions.IsParentalScheduleAllowed), on . + internal static bool IsAllowed(IReadOnlyList entries, DateTimeOffset instant, TimeZoneInfo zone) + { + if (entries.Count == 0) + { + return true; + } + + var local = TimeZoneInfo.ConvertTime(instant, zone).DateTime; + var hour = local.TimeOfDay.TotalHours; + foreach (var entry in entries) + { + if (entry.Covers(local.DayOfWeek) && hour >= entry.StartHour && hour <= entry.EndHour) + { + return true; + } + } + + return false; + } + + /// + /// The first instant after at which stops + /// being , or null when it doesn't within the look-ahead. The answer + /// can only change at an entry's start, just after an entry's end, or where the server's offset + /// changes, so only those instants are tried. + /// + private static DateTimeOffset? NextChange(IReadOnlyList entries, DateTimeOffset start, TimeZoneInfo zone, bool allowed) + { + var limit = start + LookAhead; + var candidates = new List(); + + var today = TimeZoneInfo.ConvertTime(start, zone).DateTime.Date; + for (var date = today.AddDays(-1); date <= today.Add(LookAhead).AddDays(1); date = date.AddDays(1)) + { + foreach (var entry in entries) + { + if (!entry.Covers(date.DayOfWeek)) + { + continue; + } + + AddInstants(candidates, date.AddTicks(HourTicks(entry.StartHour)), zone); + AddInstants(candidates, date.AddTicks(HourTicks(entry.EndHour)), zone); + } + } + + AddOffsetChanges(candidates, start, limit, zone); + + candidates.Sort(); + foreach (var candidate in candidates) + { + if (candidate < start || candidate > limit) + { + continue; + } + + // An opening happens at the start itself; a closing a moment after the end + if (IsAllowed(entries, candidate, zone) != allowed) + { + return candidate; + } + + var after = candidate.AddTicks(1); + if (IsAllowed(entries, after, zone) != allowed) + { + return after; + } + } + + return null; + } + + private static long HourTicks(double hours) => + (long)Math.Ceiling(Math.Clamp(hours, 0, 48) * TimeSpan.TicksPerHour); + + /// + /// The instants at which the server's wall clock reads : none in an + /// hour skipped by daylight saving, two in an hour repeated by it. + /// + private static void AddInstants(List into, DateTime local, TimeZoneInfo zone) + { + var wall = DateTime.SpecifyKind(local, DateTimeKind.Unspecified); + var nominal = new DateTimeOffset(wall, TimeSpan.Zero); + var offsets = new HashSet + { + zone.GetUtcOffset(nominal.AddDays(-1)), + zone.GetUtcOffset(nominal), + zone.GetUtcOffset(nominal.AddDays(1)), + }; + + foreach (var offset in offsets) + { + var instant = new DateTimeOffset(wall.Ticks - offset.Ticks, TimeSpan.Zero); + if (TimeZoneInfo.ConvertTime(instant, zone).DateTime == wall) + { + into.Add(instant); + } + } + } + + /// Every instant between the two at which the zone's offset changes, to the tick. + private static void AddOffsetChanges(List into, DateTimeOffset from, DateTimeOffset to, TimeZoneInfo zone) + { + var previous = from; + var offset = zone.GetUtcOffset(from); + for (var probe = from.AddHours(1); previous < to; probe = probe.AddHours(1)) + { + var next = zone.GetUtcOffset(probe); + if (next != offset) + { + var low = previous; + var high = probe; + while (high.UtcTicks - low.UtcTicks > 1) + { + var middle = low.AddTicks((high.UtcTicks - low.UtcTicks) / 2); + if (zone.GetUtcOffset(middle) == offset) + { + low = middle; + } + else + { + high = middle; + } + } + + into.Add(high); + offset = next; + } + + previous = probe; + } + } +} + +/// One access schedule entry: a day name as Jellyfin's DynamicDayOfWeek writes it, and the hours. +internal readonly record struct ScheduleEntry(string Day, double StartHour, double EndHour) +{ + /// Jellyfin's DayOfWeekHelper.Contains. + public bool Covers(DayOfWeek day) => Day switch + { + "Everyday" => true, + "Weekday" => day is >= DayOfWeek.Monday and <= DayOfWeek.Friday, + "Weekend" => day is DayOfWeek.Saturday or DayOfWeek.Sunday, + _ => Enum.TryParse(Day, out var named) && named == day, + }; +} + +public class AccessWindowResponse +{ + /// True when the user's schedule lets them in now. Always true for an administrator or a user with no schedule. + [JsonPropertyName("allowed")] + public bool Allowed { get; set; } + + /// + /// When allowed, seconds until the schedule closes, rounded up. Left out when allowed with no + /// schedule, or when it doesn't close within a week. + /// + [JsonPropertyName("secondsUntilClose")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? SecondsUntilClose { get; set; } + + /// + /// When not allowed, seconds until the schedule next opens, rounded up. Left out when it + /// doesn't open within a week. + /// + [JsonPropertyName("secondsUntilOpen")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? SecondsUntilOpen { get; set; } +} diff --git a/Jellyfin/backend/Api/MoonfinController.cs b/Jellyfin/backend/Api/MoonfinController.cs index c198bdbe..f463ec6f 100644 --- a/Jellyfin/backend/Api/MoonfinController.cs +++ b/Jellyfin/backend/Api/MoonfinController.cs @@ -118,8 +118,12 @@ public ActionResult RestoreConfigFromBackup() /// Ping endpoint to check if Moonfin plugin is installed. /// /// Plugin status information including admin defaults. + /// + /// Skips the access-schedule check so a client outside its user's hours can still find out + /// the plugin is there and whether it can ask for the access window. + /// [HttpGet("Ping")] - [Authorize] + [Authorize(Policy = "IgnoreParentalControl")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult Ping([FromQuery] string? profile = null) { @@ -144,6 +148,7 @@ public ActionResult Ping([FromQuery] string? profile = null DiscoverChartsSupported = true, MessagesSupported = true, PinSupported = true, + AccessWindowSupported = true, IncompleteRecordingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true, ExtendedCompleteShowingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true, RecommendationsSupported = config?.RecommendationsProviderEnabled ?? true, @@ -1872,6 +1877,13 @@ public class MoonfinPingResponse [JsonPropertyName("pinSupported")] public bool? PinSupported { get; set; } + /// + /// True when this plugin answers Moonfin/AccessWindow, which judges the user's access schedule + /// on the server's clock. Older plugins leave it out, so the app judges it on the device clock. + /// + [JsonPropertyName("accessWindowSupported")] + public bool? AccessWindowSupported { get; set; } + /// /// True when the admin turned on smart search, so clients can call /Moonfin/SmartSearch. /// diff --git a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs new file mode 100644 index 00000000..f1378417 --- /dev/null +++ b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs @@ -0,0 +1,289 @@ +using System.Reflection; +using System.Text.Json; +using Microsoft.AspNetCore.Authorization; +using Moonfin.Server.Api; +using Xunit; + +namespace Moonfin.Server.Tests; + +public sealed class AccessWindowTests +{ + private static readonly TimeZoneInfo Utc = TimeZoneInfo.Utc; + + private static TimeZoneInfo Fixed(string offset) => + TimeZoneInfo.CreateCustomTimeZone("Test/Zone", TimeSpan.Parse(offset), "Test", "Test"); + + // Null on a host with no tz database, where the test is skipped quietly + private static TimeZoneInfo? Named(string id) + { + try + { + return TimeZoneInfo.FindSystemTimeZoneById(id); + } + catch (TimeZoneNotFoundException) + { + return null; + } + } + + private static ScheduleEntry Entry(string day, double start, double end) => new(day, start, end); + + private static DateTimeOffset At(int year, int month, int day, int hour, int minute = 0) => + new(year, month, day, hour, minute, 0, TimeSpan.Zero); + + [Fact] + public void NoSchedule_IsAllowedWithNoClosing() + { + var window = AccessWindowController.Evaluate([], At(2026, 11, 16, 12), Utc); + + Assert.True(window.Allowed); + Assert.Null(window.SecondsUntilClose); + Assert.Null(window.SecondsUntilOpen); + } + + [Fact] + public void EveryHourOfEveryDay_NeverCloses() + { + var window = AccessWindowController.Evaluate([Entry("Everyday", 0, 24)], At(2026, 11, 16, 12), Utc); + + Assert.True(window.Allowed); + Assert.Null(window.SecondsUntilClose); + } + + [Fact] + public void Allowed_ClosesTheSecondAfterTheEndHour() + { + // Monday 2026-11-16 19:00; Jellyfin still allows 20:00:00 itself + var window = AccessWindowController.Evaluate([Entry("Weekday", 8, 20)], At(2026, 11, 16, 19), Utc); + + Assert.True(window.Allowed); + Assert.Equal(3601, window.SecondsUntilClose); + Assert.Null(window.SecondsUntilOpen); + } + + [Fact] + public void Blocked_OpensAtTheStartHour() + { + // Monday 21:00, next opening Tuesday 08:00 + var window = AccessWindowController.Evaluate([Entry("Weekday", 8, 20)], At(2026, 11, 16, 21), Utc); + + Assert.False(window.Allowed); + Assert.Equal(11 * 3600, window.SecondsUntilOpen); + Assert.Null(window.SecondsUntilClose); + } + + [Fact] + public void Blocked_OverTheWeekendOpensMonday() + { + // Friday 2026-11-20 21:00 to Monday 08:00 + var window = AccessWindowController.Evaluate([Entry("Weekday", 8, 20)], At(2026, 11, 20, 21), Utc); + + Assert.Equal((3 + 2 * 24 + 8) * 3600, window.SecondsUntilOpen); + } + + [Fact] + public void AdjacentEntries_RunTogether() + { + // Monday 20:00-24:00 then Tuesday 00:00-08:00 is one spell, closing after Tuesday 08:00 + var entries = new[] { Entry("Monday", 20, 24), Entry("Tuesday", 0, 8) }; + var window = AccessWindowController.Evaluate(entries, At(2026, 11, 16, 21), Utc); + + Assert.True(window.Allowed); + Assert.Equal(11 * 3600 + 1, window.SecondsUntilClose); + } + + [Fact] + public void HalfHours_AreHonoured() + { + var window = AccessWindowController.Evaluate([Entry("Everyday", 7.5, 21.5)], At(2026, 11, 16, 6), Utc); + + Assert.False(window.Allowed); + Assert.Equal(5400, window.SecondsUntilOpen); + } + + [Fact] + public void JudgedOnTheServersZone() + { + // 19:00Z is 00:30 Tuesday in India: closed for a Monday-only schedule, open for Tuesday + var india = Fixed("05:30"); + Assert.False(AccessWindowController.Evaluate([Entry("Monday", 0, 24)], At(2026, 11, 16, 19), india).Allowed); + Assert.True(AccessWindowController.Evaluate([Entry("Tuesday", 0, 1)], At(2026, 11, 16, 19), india).Allowed); + } + + [Fact] + public void AnEntryThatNeverOpens_GivesNoOpening() + { + var window = AccessWindowController.Evaluate([Entry("Everyday", 20, 8)], At(2026, 11, 16, 12), Utc); + + Assert.False(window.Allowed); + Assert.Null(window.SecondsUntilOpen); + } + + [Fact] + public void FallBack_CountsTheRepeatedHour() + { + var newYork = Named("America/New_York"); + if (newYork == null) + { + return; + } + + // Sunday 2026-11-01 00:30 EDT (04:30Z); 03:00 EST is 08:00Z, three and a half hours on + var window = AccessWindowController.Evaluate([Entry("Sunday", 3, 12)], At(2026, 11, 1, 4, 30), newYork); + + Assert.False(window.Allowed); + Assert.Equal(12600, window.SecondsUntilOpen); + } + + [Fact] + public void SpringForward_OpensWhenTheClockJumpsIntoTheWindow() + { + var newYork = Named("America/New_York"); + if (newYork == null) + { + return; + } + + // Sunday 2026-03-08 01:00 EST (06:00Z). 02:30 never happens; at 07:00Z the clock jumps + // from 02:00 EST to 03:00 EDT, inside 02:30-04:00 + var window = AccessWindowController.Evaluate([Entry("Sunday", 2.5, 4)], At(2026, 3, 8, 6), newYork); + + Assert.False(window.Allowed); + Assert.Equal(3600, window.SecondsUntilOpen); + } + + public static IEnumerable Zones() => + new[] { "America/New_York", "Australia/Sydney", "Europe/London", "Asia/Kolkata", "Pacific/Chatham" } + .Select(id => new object[] { id }); + + private static readonly ScheduleEntry[][] Schedules = + [ + [Entry("Weekday", 8, 20)], + [Entry("Everyday", 7.5, 21.5)], + [Entry("Monday", 20, 24), Entry("Tuesday", 0, 8)], + [Entry("Saturday", 1.5, 3), Entry("Sunday", 1.5, 3), Entry("Weekend", 2, 2.5)], + [Entry("Sunday", 0, 24), Entry("Wednesday", 2, 3)], + [Entry("Everyday", 0, 24)], + ]; + + /// + /// Evaluate agrees with a scan of Jellyfin's rule a minute at a time, refined to the tick, + /// over weeks that hold each zone's daylight saving changes. + /// + [Theory] + [MemberData(nameof(Zones))] + public void AgreesWithAScan(string zoneId) + { + var zone = Named(zoneId); + if (zone == null) + { + return; + } + + var starts = new[] { At(2026, 3, 7, 0), At(2026, 3, 28, 0), At(2026, 4, 4, 0), At(2026, 9, 26, 0), At(2026, 10, 24, 0), At(2026, 10, 31, 0) }; + foreach (var entries in Schedules) + { + foreach (var weekStart in starts) + { + for (var now = weekStart; now < weekStart.AddDays(2); now = now.AddMinutes(97)) + { + var window = AccessWindowController.Evaluate(entries, now, zone); + var allowed = AccessWindowController.IsAllowed(entries, now, zone); + var expected = Scan(entries, now, zone, allowed); + + Assert.Equal(allowed, window.Allowed); + Assert.Equal(allowed ? expected : null, window.SecondsUntilClose); + Assert.Equal(allowed ? null : expected, window.SecondsUntilOpen); + } + } + } + } + + private static long? Scan(IReadOnlyList entries, DateTimeOffset now, TimeZoneInfo zone, bool allowed) + { + for (var minute = 1; minute <= 8 * 24 * 60; minute++) + { + var probe = now.AddMinutes(minute); + if (AccessWindowController.IsAllowed(entries, probe, zone) == allowed) + { + continue; + } + + var low = probe.AddMinutes(-1); + var high = probe; + while (high.UtcTicks - low.UtcTicks > 1) + { + var middle = low.AddTicks((high.UtcTicks - low.UtcTicks) / 2); + if (AccessWindowController.IsAllowed(entries, middle, zone) == allowed) + { + low = middle; + } + else + { + high = middle; + } + } + + return (long)Math.Ceiling((high - now).TotalSeconds); + } + + return null; + } + + private enum FakeDay + { + Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Everyday, Weekday, Weekend, + } + + private sealed class FakeSchedule + { + public FakeDay DayOfWeek { get; set; } + + public double StartHour { get; set; } + + public double EndHour { get; set; } + } + + private sealed class FakeUser + { + public ICollection AccessSchedules { get; set; } = new List(); + } + + [Fact] + public void ReadSchedule_ReadsJellyfinsShapeByName() + { + var user = new FakeUser(); + user.AccessSchedules.Add(new FakeSchedule { DayOfWeek = FakeDay.Weekday, StartHour = 8, EndHour = 20.5 }); + user.AccessSchedules.Add(new FakeSchedule { DayOfWeek = FakeDay.Sunday, StartHour = 0, EndHour = 24 }); + + var entries = AccessWindowController.ReadSchedule(user); + + Assert.Equal([Entry("Weekday", 8, 20.5), Entry("Sunday", 0, 24)], entries); + } + + [Fact] + public void ReadSchedule_IsNullForAnotherShape() + { + Assert.Null(AccessWindowController.ReadSchedule(new object())); + } + + [Fact] + public void Response_UsesTheKeysClientsRead() + { + var open = JsonSerializer.Serialize(new AccessWindowResponse { Allowed = true, SecondsUntilClose = 60 }); + var closed = JsonSerializer.Serialize(new AccessWindowResponse { Allowed = false }); + + Assert.Equal("{\"allowed\":true,\"secondsUntilClose\":60}", open); + Assert.Equal("{\"allowed\":false}", closed); + } + + [Theory] + [InlineData(typeof(AccessWindowController), nameof(AccessWindowController.GetAccessWindow))] + [InlineData(typeof(MoonfinController), nameof(MoonfinController.Ping))] + public void Endpoint_IsReachableOutsideTheAccessSchedule(Type controller, string action) + { + var authorize = controller.GetMethod(action)!.GetCustomAttribute(); + + Assert.Equal("IgnoreParentalControl", authorize!.Policy); + } +} From 63e153e530dccf7cc00a88156d6a0520b7b8c163 Mon Sep 17 00:00:00 2001 From: Ben Date: Mon, 16 Nov 2026 14:12:11 -0500 Subject: [PATCH 2/9] Answered 501 when the user's schedule can't be read, so clients judge it themselves Co-Authored-By: Claude Opus 5.5 --- Jellyfin/backend/Api/AccessWindowController.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin/backend/Api/AccessWindowController.cs b/Jellyfin/backend/Api/AccessWindowController.cs index bc33c53a..f09178e0 100644 --- a/Jellyfin/backend/Api/AccessWindowController.cs +++ b/Jellyfin/backend/Api/AccessWindowController.cs @@ -36,7 +36,7 @@ public AccessWindowController(IServiceProvider services) [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [ProducesResponseType(StatusCodes.Status501NotImplemented)] public ActionResult GetAccessWindow() { // Jellyfin doesn't hold administrators to a schedule @@ -55,7 +55,8 @@ public ActionResult GetAccessWindow() var entries = user == null ? null : ReadSchedule(user); if (entries == null) { - return Problem("The user's access schedule couldn't be read on this server version."); + // Not Implemented, like a plugin without the endpoint, so clients judge it themselves + return Problem("The user's access schedule couldn't be read on this server version.", statusCode: StatusCodes.Status501NotImplemented); } return Ok(Evaluate(entries, DateTimeOffset.UtcNow, TimeZoneInfo.Local)); From d03468a4a9f596814f5a4aece7e86e3a30f1d099 Mon Sep 17 00:00:00 2001 From: Ben Date: Mon, 16 Nov 2026 16:48:52 -0500 Subject: [PATCH 3/9] Clamped schedule boundaries to the local day and tested the rule against Jellyfin's own Jellyfin stores schedule hours as given and compares them with the hour of the local day, so an entry ending at 25:00 lasts to midnight and no later. The boundaries tried for the next change are now clamped to 0-24 to match, so Monday 08:00-25:00 at 19:00 closes in five hours, not six; IsAllowed keeps the stored hours. (CodeRabbit) The scan test checked the next-change search against IsAllowed itself, which can't catch IsAllowed differing from Jellyfin. IsAllowed is now compared with Jellyfin 10.10's own User.IsParentalScheduleAllowed on its own AccessSchedule type, every 7 minutes over a week and either side of each start and end, and ReadSchedule is checked on a real Jellyfin User. (Greptile) Co-Authored-By: Claude Opus 5.5 --- .../backend/Api/AccessWindowController.cs | 5 +- .../Moonfin.Server.Tests/AccessWindowTests.cs | 100 ++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) diff --git a/Jellyfin/backend/Api/AccessWindowController.cs b/Jellyfin/backend/Api/AccessWindowController.cs index f09178e0..0f218d16 100644 --- a/Jellyfin/backend/Api/AccessWindowController.cs +++ b/Jellyfin/backend/Api/AccessWindowController.cs @@ -209,8 +209,11 @@ internal static bool IsAllowed(IReadOnlyList entries, DateTimeOff return null; } + // Jellyfin compares the hour of the local day, which runs from 0 up to 24, with the stored hours as + // they are, so an end past 24 lasts to midnight and no later and a start below 0 is midnight. The + // boundaries are clamped to the day to match; IsAllowed keeps the stored hours. private static long HourTicks(double hours) => - (long)Math.Ceiling(Math.Clamp(hours, 0, 48) * TimeSpan.TicksPerHour); + (long)Math.Ceiling(Math.Clamp(hours, 0, 24) * TimeSpan.TicksPerHour); /// /// The instants at which the server's wall clock reads : none in an diff --git a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs index f1378417..575c26f6 100644 --- a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs +++ b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs @@ -119,6 +119,25 @@ public void AnEntryThatNeverOpens_GivesNoOpening() Assert.Null(window.SecondsUntilOpen); } + [Fact] + public void AnEndPastMidnight_ClosesAtMidnight() + { + // Jellyfin stores hours as given; Monday 08:00-25:00 ends when Monday does + var window = AccessWindowController.Evaluate([Entry("Monday", 8, 25)], At(2026, 11, 16, 19), Utc); + + Assert.True(window.Allowed); + Assert.Equal(5 * 3600, window.SecondsUntilClose); + } + + [Fact] + public void AStartBeforeMidnight_OpensAtMidnight() + { + var window = AccessWindowController.Evaluate([Entry("Tuesday", -2, 6)], At(2026, 11, 16, 19), Utc); + + Assert.False(window.Allowed); + Assert.Equal(5 * 3600, window.SecondsUntilOpen); + } + [Fact] public void FallBack_CountsTheRepeatedHour() { @@ -164,6 +183,7 @@ public static IEnumerable Zones() => [Entry("Saturday", 1.5, 3), Entry("Sunday", 1.5, 3), Entry("Weekend", 2, 2.5)], [Entry("Sunday", 0, 24), Entry("Wednesday", 2, 3)], [Entry("Everyday", 0, 24)], + [Entry("Monday", 8, 25), Entry("Friday", -1, 3)], ]; /// @@ -230,6 +250,86 @@ public void AgreesWithAScan(string zoneId) return null; } + // Jellyfin 10.10's own check of one entry, User.IsParentalScheduleAllowed(AccessSchedule, DateTime), + // on its own types. It reads date.ToLocalTime(), which leaves a DateTime of kind Local as it is, + // so it can be handed exact wall-clock times without touching this process's time zone. 10.11 + // moved the same check to UserEntityExtensions. + private static readonly MethodInfo JellyfinEntryCheck = typeof(Jellyfin.Data.Entities.User) + .GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) + .Single(m => m.Name == "IsParentalScheduleAllowed" && m.GetParameters().Length == 2); + + // The user-level rule around it: allowed with no entries, or when any entry allows + private static bool JellyfinAllows(IReadOnlyList entries, DateTime wallClock) + { + var local = DateTime.SpecifyKind(wallClock, DateTimeKind.Local); + return entries.Count == 0 || entries.Any(e => (bool)JellyfinEntryCheck.Invoke(null, [JellyfinSchedule(e), local])!); + } + + private static Jellyfin.Data.Entities.AccessSchedule JellyfinSchedule(ScheduleEntry entry) => + new(Enum.Parse(entry.Day), entry.StartHour, entry.EndHour, Guid.Empty); + + private static readonly ScheduleEntry[][] JellyfinCases = Schedules.Concat( + [ + [Entry("Sunday", 0, 0)], + [Entry("Saturday", 23.5, 24), Entry("Weekend", 12, 12.5)], + [Entry("Wednesday", 22, 6)], + [Entry("Thursday", 6.25, 18.75), Entry("Tuesday", 0, 24)], + [], + ]).ToArray(); + + public static IEnumerable JellyfinSchedules() => + Enumerable.Range(0, JellyfinCases.Length).Select(i => new object[] { i }); + + /// + /// IsAllowed agrees with Jellyfin's own check on every day of a week: every 7 minutes, and a + /// second either side of each entry's start and end. + /// + [Theory] + [MemberData(nameof(JellyfinSchedules))] + public void IsAllowed_AgreesWithJellyfin(int schedule) + { + var entries = JellyfinCases[schedule]; + var monday = new DateTime(2026, 11, 16); + var moments = new List(); + for (var minute = 0; minute < 7 * 24 * 60; minute += 7) + { + moments.Add(monday.AddMinutes(minute)); + } + + for (var day = 0; day < 7; day++) + { + foreach (var entry in entries) + { + foreach (var hour in new[] { entry.StartHour, entry.EndHour }) + { + if (hour is < 0 or > 24) + { + continue; + } + + var at = monday.AddDays(day).AddTicks((long)(hour * TimeSpan.TicksPerHour)); + moments.AddRange([at.AddSeconds(-1), at, at.AddSeconds(1)]); + } + } + } + + foreach (var moment in moments) + { + var ours = AccessWindowController.IsAllowed(entries, new DateTimeOffset(moment, TimeSpan.Zero), Utc); + Assert.True(JellyfinAllows(entries, moment) == ours, $"{moment:ddd HH:mm:ss}: Jellyfin and IsAllowed differ ({string.Join(", ", entries)})"); + } + } + + [Fact] + public void ReadSchedule_ReadsJellyfinsUser() + { + var user = new Jellyfin.Data.Entities.User("child", "auth", "reset"); + user.AccessSchedules.Add(new Jellyfin.Data.Entities.AccessSchedule(Jellyfin.Data.Enums.DynamicDayOfWeek.Weekday, 8, 20.5, Guid.Empty)); + user.AccessSchedules.Add(new Jellyfin.Data.Entities.AccessSchedule(Jellyfin.Data.Enums.DynamicDayOfWeek.Sunday, 0, 24, Guid.Empty)); + + Assert.Equal([Entry("Weekday", 8, 20.5), Entry("Sunday", 0, 24)], AccessWindowController.ReadSchedule(user)); + } + private enum FakeDay { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Everyday, Weekday, Weekend, From ec3aea6f7d6adc3ca71243b6df4a771bcf445a3a Mon Sep 17 00:00:00 2001 From: Ben Date: Wed, 18 Nov 2026 22:08:44 -0500 Subject: [PATCH 4/9] Remove access window checks from Ping endpoint and update tests accordingly --- Jellyfin/backend/Api/MoonfinController.cs | 14 +------------- .../Moonfin.Server.Tests/AccessWindowTests.cs | 1 - 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/Jellyfin/backend/Api/MoonfinController.cs b/Jellyfin/backend/Api/MoonfinController.cs index f463ec6f..c198bdbe 100644 --- a/Jellyfin/backend/Api/MoonfinController.cs +++ b/Jellyfin/backend/Api/MoonfinController.cs @@ -118,12 +118,8 @@ public ActionResult RestoreConfigFromBackup() /// Ping endpoint to check if Moonfin plugin is installed. /// /// Plugin status information including admin defaults. - /// - /// Skips the access-schedule check so a client outside its user's hours can still find out - /// the plugin is there and whether it can ask for the access window. - /// [HttpGet("Ping")] - [Authorize(Policy = "IgnoreParentalControl")] + [Authorize] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult Ping([FromQuery] string? profile = null) { @@ -148,7 +144,6 @@ public ActionResult Ping([FromQuery] string? profile = null DiscoverChartsSupported = true, MessagesSupported = true, PinSupported = true, - AccessWindowSupported = true, IncompleteRecordingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true, ExtendedCompleteShowingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true, RecommendationsSupported = config?.RecommendationsProviderEnabled ?? true, @@ -1877,13 +1872,6 @@ public class MoonfinPingResponse [JsonPropertyName("pinSupported")] public bool? PinSupported { get; set; } - /// - /// True when this plugin answers Moonfin/AccessWindow, which judges the user's access schedule - /// on the server's clock. Older plugins leave it out, so the app judges it on the device clock. - /// - [JsonPropertyName("accessWindowSupported")] - public bool? AccessWindowSupported { get; set; } - /// /// True when the admin turned on smart search, so clients can call /Moonfin/SmartSearch. /// diff --git a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs index 575c26f6..7aa239b8 100644 --- a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs +++ b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs @@ -379,7 +379,6 @@ public void Response_UsesTheKeysClientsRead() [Theory] [InlineData(typeof(AccessWindowController), nameof(AccessWindowController.GetAccessWindow))] - [InlineData(typeof(MoonfinController), nameof(MoonfinController.Ping))] public void Endpoint_IsReachableOutsideTheAccessSchedule(Type controller, string action) { var authorize = controller.GetMethod(action)!.GetCustomAttribute(); From 7e8e2e1ff31caec59b1570e19e3601392649b1b3 Mon Sep 17 00:00:00 2001 From: Ben Date: Thu, 19 Nov 2026 21:32:14 -0500 Subject: [PATCH 5/9] Modelled the access schedule as UTC periods instead of searching for the next change BuildPeriods turns the schedule entries into sorted, merged UTC AccessPeriods for any range. While the server's UTC offset holds, local time is UTC plus that offset, so each entry's hours are shifted by it and cut to that stretch: an hour skipped by daylight saving drops out and a repeated one counts twice. Evaluate finds the period holding now; its end is the close, else the next period's start is the opening. The look-ahead defaults to 8 days and can be passed in. Offset changes are found with a binary search over two-week pieces, which hold one change at most in today's rules (the closest are Morocco's, about five weeks apart). This replaces NextChange's candidate list and the hour-by-hour probing. IsAllowed is no longer used by the plugin and moves into the tests, which still tie it to Jellyfin's own check and compare Evaluate with a scan of it. New tests cover a period split by the fall-back hour, a range of two weeks, both changes in a year, and a shorter look-ahead. Co-Authored-By: Claude Opus 5.5 --- .../backend/Api/AccessWindowController.cs | 202 +++++++----------- .../Moonfin.Server.Tests/AccessWindowTests.cs | 80 ++++++- 2 files changed, 159 insertions(+), 123 deletions(-) diff --git a/Jellyfin/backend/Api/AccessWindowController.cs b/Jellyfin/backend/Api/AccessWindowController.cs index 0f218d16..2ad7c655 100644 --- a/Jellyfin/backend/Api/AccessWindowController.cs +++ b/Jellyfin/backend/Api/AccessWindowController.cs @@ -98,31 +98,37 @@ public ActionResult GetAccessWindow() } } - // The schedule repeats every week, so a change that ever comes comes within this - private static readonly TimeSpan LookAhead = TimeSpan.FromDays(8); + // Long enough to find any change. The schedule repeats every week, so if nothing changes within a + // week, nothing ever will. The extra day covers a daylight saving change moving the next change + // up to an hour past a week away. + internal static readonly TimeSpan DefaultLookAhead = TimeSpan.FromDays(8); /// - /// The access window at for a server in , judged - /// the way Jellyfin judges it: allowed when no entries, or when any entry's day matches the - /// server's local day and the local hour is between its start and end, both included. Adjacent - /// and overlapping entries run together, so the durations are to the real change, and the - /// server's daylight saving changes are counted. + /// The access window at for a server in : allowed + /// when there are no entries or falls in one of the schedule's periods, + /// with the time until that period ends or the next one starts. The time is left out when it's + /// not within . /// - internal static AccessWindowResponse Evaluate(IReadOnlyList entries, DateTimeOffset now, TimeZoneInfo zone) + internal static AccessWindowResponse Evaluate(IReadOnlyList entries, DateTimeOffset now, TimeZoneInfo zone, TimeSpan? lookAhead = null) { - var start = now.ToUniversalTime(); - var allowed = IsAllowed(entries, start, zone); - var response = new AccessWindowResponse { Allowed = allowed }; if (entries.Count == 0) { - return response; + return new AccessWindowResponse { Allowed = true }; } - var change = NextChange(entries, start, zone, allowed); - if (change is { } at) + now = now.ToUniversalTime(); + var limit = now + (lookAhead ?? DefaultLookAhead); + var periods = BuildPeriods(entries, now, limit, zone); + var current = periods.Find(p => p.Start <= now && now < p.End); + var allowed = current != default; + var change = allowed ? current.End : periods.Find(p => p.Start > now).Start; + + var response = new AccessWindowResponse { Allowed = allowed }; + // A period cut off at the limit doesn't end there, and no next period means no opening + if (change > now && change < limit) { // Rounded up, so a timer set from it never fires before the change - var seconds = (long)Math.Ceiling((at - start).TotalSeconds); + var seconds = (long)Math.Ceiling((change - now).TotalSeconds); if (allowed) { response.SecondsUntilClose = seconds; @@ -136,144 +142,102 @@ internal static AccessWindowResponse Evaluate(IReadOnlyList entri return response; } - /// Jellyfin's own rule (UserEntityExtensions.IsParentalScheduleAllowed), on . - internal static bool IsAllowed(IReadOnlyList entries, DateTimeOffset instant, TimeZoneInfo zone) - { - if (entries.Count == 0) - { - return true; - } - - var local = TimeZoneInfo.ConvertTime(instant, zone).DateTime; - var hour = local.TimeOfDay.TotalHours; - foreach (var entry in entries) - { - if (entry.Covers(local.DayOfWeek) && hour >= entry.StartHour && hour <= entry.EndHour) - { - return true; - } - } - - return false; - } - /// - /// The first instant after at which stops - /// being , or null when it doesn't within the look-ahead. The answer - /// can only change at an entry's start, just after an entry's end, or where the server's offset - /// changes, so only those instants are tried. + /// The schedule as UTC periods between and for a + /// server in , sorted, and merged where they overlap or touch, judged the + /// way Jellyfin judges it (UserEntityExtensions.IsParentalScheduleAllowed): an entry lets the + /// user in on its days while the server's local hour is between its start and end, both + /// included. While the zone's UTC offset holds, the local time is UTC plus that offset, so each + /// entry's hours are shifted by the offset and cut to that stretch. That way an hour skipped by + /// daylight saving drops out and a repeated one counts twice. /// - private static DateTimeOffset? NextChange(IReadOnlyList entries, DateTimeOffset start, TimeZoneInfo zone, bool allowed) + internal static List BuildPeriods(IReadOnlyList entries, DateTimeOffset from, DateTimeOffset to, TimeZoneInfo zone) { - var limit = start + LookAhead; - var candidates = new List(); - - var today = TimeZoneInfo.ConvertTime(start, zone).DateTime.Date; - for (var date = today.AddDays(-1); date <= today.Add(LookAhead).AddDays(1); date = date.AddDays(1)) + var periods = new List(); + foreach (var (start, end, offset) in OffsetStretches(from.ToUniversalTime(), to.ToUniversalTime(), zone)) { - foreach (var entry in entries) + for (var day = (start + offset).Date; day <= (end + offset).Date; day = day.AddDays(1)) { - if (!entry.Covers(date.DayOfWeek)) + foreach (var entry in entries.Where(e => e.Covers(day.DayOfWeek))) { - continue; + // Jellyfin compares the local hour of the day, 0 up to 24, with the hours as stored, + // so an end past 24 lasts to midnight and a start below 0 is midnight + var open = (long)Math.Ceiling(Math.Clamp(entry.StartHour, 0, 24) * TimeSpan.TicksPerHour); + var close = (long)Math.Min(Math.Floor(entry.EndHour * TimeSpan.TicksPerHour) + 1, TimeSpan.TicksPerDay); + var midnight = day.Ticks - offset.Ticks; + var period = new AccessPeriod( + Later(start, new DateTimeOffset(midnight + open, TimeSpan.Zero)), + Earlier(end, new DateTimeOffset(midnight + close, TimeSpan.Zero))); + if (period.Start < period.End) + { + periods.Add(period); + } } - - AddInstants(candidates, date.AddTicks(HourTicks(entry.StartHour)), zone); - AddInstants(candidates, date.AddTicks(HourTicks(entry.EndHour)), zone); } } - AddOffsetChanges(candidates, start, limit, zone); - - candidates.Sort(); - foreach (var candidate in candidates) + periods.Sort((a, b) => a.Start.CompareTo(b.Start)); + var merged = new List(); + foreach (var period in periods) { - if (candidate < start || candidate > limit) - { - continue; - } - - // An opening happens at the start itself; a closing a moment after the end - if (IsAllowed(entries, candidate, zone) != allowed) + if (merged.Count > 0 && period.Start <= merged[^1].End) { - return candidate; + merged[^1] = merged[^1] with { End = Later(merged[^1].End, period.End) }; } - - var after = candidate.AddTicks(1); - if (IsAllowed(entries, after, zone) != allowed) + else { - return after; + merged.Add(period); } } - return null; + return merged; } - // Jellyfin compares the hour of the local day, which runs from 0 up to 24, with the stored hours as - // they are, so an end past 24 lasts to midnight and no later and a start below 0 is midnight. The - // boundaries are clamped to the day to match; IsAllowed keeps the stored hours. - private static long HourTicks(double hours) => - (long)Math.Ceiling(Math.Clamp(hours, 0, 24) * TimeSpan.TicksPerHour); + // Offset changes are further apart than this in today's rules: the closest are Morocco's around + // Ramadan, about five weeks apart. Half that leaves room for a rule changed at short notice. + private static readonly TimeSpan OffsetChangeSpacing = TimeSpan.FromDays(14); /// - /// The instants at which the server's wall clock reads : none in an - /// hour skipped by daylight saving, two in an hour repeated by it. + /// The stretches between the two instants over which the zone's UTC offset holds, split where it + /// changes, found to the tick. .NET has no call for the next change, but a piece shorter than + /// holds one at most, so its ends show whether it does, and a + /// binary search finds it. The default look-ahead is one piece. /// - private static void AddInstants(List into, DateTime local, TimeZoneInfo zone) + private static IEnumerable<(DateTimeOffset Start, DateTimeOffset End, TimeSpan Offset)> OffsetStretches(DateTimeOffset from, DateTimeOffset to, TimeZoneInfo zone) { - var wall = DateTime.SpecifyKind(local, DateTimeKind.Unspecified); - var nominal = new DateTimeOffset(wall, TimeSpan.Zero); - var offsets = new HashSet - { - zone.GetUtcOffset(nominal.AddDays(-1)), - zone.GetUtcOffset(nominal), - zone.GetUtcOffset(nominal.AddDays(1)), - }; - - foreach (var offset in offsets) + var start = from; + var offset = zone.GetUtcOffset(from); + for (var piece = from; piece < to; piece += OffsetChangeSpacing) { - var instant = new DateTimeOffset(wall.Ticks - offset.Ticks, TimeSpan.Zero); - if (TimeZoneInfo.ConvertTime(instant, zone).DateTime == wall) + var low = piece; + var high = Earlier(piece + OffsetChangeSpacing, to); + if (zone.GetUtcOffset(high) == offset) { - into.Add(instant); + continue; } - } - } - /// Every instant between the two at which the zone's offset changes, to the tick. - private static void AddOffsetChanges(List into, DateTimeOffset from, DateTimeOffset to, TimeZoneInfo zone) - { - var previous = from; - var offset = zone.GetUtcOffset(from); - for (var probe = from.AddHours(1); previous < to; probe = probe.AddHours(1)) - { - var next = zone.GetUtcOffset(probe); - if (next != offset) + while (high.UtcTicks - low.UtcTicks > 1) { - var low = previous; - var high = probe; - while (high.UtcTicks - low.UtcTicks > 1) - { - var middle = low.AddTicks((high.UtcTicks - low.UtcTicks) / 2); - if (zone.GetUtcOffset(middle) == offset) - { - low = middle; - } - else - { - high = middle; - } - } - - into.Add(high); - offset = next; + var middle = low.AddTicks((high.UtcTicks - low.UtcTicks) / 2); + (low, high) = zone.GetUtcOffset(middle) == offset ? (middle, high) : (low, middle); } - previous = probe; + yield return (start, high, offset); + start = high; + offset = zone.GetUtcOffset(high); } + + yield return (start, to, offset); } + + private static DateTimeOffset Earlier(DateTimeOffset a, DateTimeOffset b) => a < b ? a : b; + + private static DateTimeOffset Later(DateTimeOffset a, DateTimeOffset b) => a > b ? a : b; } +/// A time in which the schedule lets the user in, from Start up to but not including End. +internal readonly record struct AccessPeriod(DateTimeOffset Start, DateTimeOffset End); + /// One access schedule entry: a day name as Jellyfin's DynamicDayOfWeek writes it, and the hours. internal readonly record struct ScheduleEntry(string Day, double StartHour, double EndHour) { diff --git a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs index 7aa239b8..c1ebc762 100644 --- a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs +++ b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs @@ -171,6 +171,68 @@ public void SpringForward_OpensWhenTheClockJumpsIntoTheWindow() Assert.Equal(3600, window.SecondsUntilOpen); } + [Fact] + public void FallBack_SplitsAPeriodEndingInTheRepeatedHour() + { + var newYork = Named("America/New_York"); + if (newYork == null) + { + return; + } + + // Sunday 2026-11-01 00:00-01:30: 04:00Z-05:30Z on EDT, then the clock goes back to 01:00 EST + // at 06:00Z and reads 01:00-01:30 again until 06:30Z + var periods = AccessWindowController.BuildPeriods([Entry("Sunday", 0, 1.5)], At(2026, 11, 1, 0), At(2026, 11, 2, 0), newYork); + + Assert.Equal( + [new AccessPeriod(At(2026, 11, 1, 4), At(2026, 11, 1, 5, 30).AddTicks(1)), new AccessPeriod(At(2026, 11, 1, 6), At(2026, 11, 1, 6, 30).AddTicks(1))], + periods); + } + + [Fact] + public void BuildPeriods_CoversTheRangeAskedFor() + { + // Two weeks from Monday 2026-11-16: ten weekdays, the last cut off at the range's end + var periods = AccessWindowController.BuildPeriods([Entry("Weekday", 8, 20)], At(2026, 11, 16, 0), At(2026, 11, 27, 12), Utc); + + Assert.Equal(10, periods.Count); + Assert.Equal(new AccessPeriod(At(2026, 11, 16, 8), At(2026, 11, 16, 20).AddTicks(1)), periods[0]); + Assert.Equal(new AccessPeriod(At(2026, 11, 27, 8), At(2026, 11, 27, 12)), periods[^1]); + } + + [Fact] + public void BuildPeriods_FindsBothChangesInAYear() + { + var newYork = Named("America/New_York"); + if (newYork == null) + { + return; + } + + // All of 2026, EST at both ends; Sundays 02:30-04:00 local + var periods = AccessWindowController.BuildPeriods([Entry("Sunday", 2.5, 4)], At(2026, 1, 1, 0), At(2027, 1, 1, 0), newYork); + + Assert.Equal(52, periods.Count); + // EST: 07:30Z-09:00Z + Assert.Contains(new AccessPeriod(At(2026, 3, 1, 7, 30), At(2026, 3, 1, 9).AddTicks(1)), periods); + // Spring forward: 02:30 never comes, the clock jumps to 03:00 EDT at 07:00Z + Assert.Contains(new AccessPeriod(At(2026, 3, 8, 7), At(2026, 3, 8, 8).AddTicks(1)), periods); + // EDT: 06:30Z-08:00Z + Assert.Contains(new AccessPeriod(At(2026, 7, 5, 6, 30), At(2026, 7, 5, 8).AddTicks(1)), periods); + // Fall back at 06:00Z: 02:30-04:00 EST + Assert.Contains(new AccessPeriod(At(2026, 11, 1, 7, 30), At(2026, 11, 1, 9).AddTicks(1)), periods); + } + + [Fact] + public void LookAhead_LeavesOutChangesBeyondIt() + { + // Friday 21:00, opens Monday 08:00: 59 hours on, past a two-day look-ahead + var window = AccessWindowController.Evaluate([Entry("Weekday", 8, 20)], At(2026, 11, 20, 21), Utc, TimeSpan.FromDays(2)); + + Assert.False(window.Allowed); + Assert.Null(window.SecondsUntilOpen); + } + public static IEnumerable Zones() => new[] { "America/New_York", "Australia/Sydney", "Europe/London", "Asia/Kolkata", "Pacific/Chatham" } .Select(id => new object[] { id }); @@ -184,6 +246,7 @@ public static IEnumerable Zones() => [Entry("Sunday", 0, 24), Entry("Wednesday", 2, 3)], [Entry("Everyday", 0, 24)], [Entry("Monday", 8, 25), Entry("Friday", -1, 3)], + [Entry("Sunday", 0, 1.5)], ]; /// @@ -208,7 +271,7 @@ public void AgreesWithAScan(string zoneId) for (var now = weekStart; now < weekStart.AddDays(2); now = now.AddMinutes(97)) { var window = AccessWindowController.Evaluate(entries, now, zone); - var allowed = AccessWindowController.IsAllowed(entries, now, zone); + var allowed = IsAllowed(entries, now, zone); var expected = Scan(entries, now, zone, allowed); Assert.Equal(allowed, window.Allowed); @@ -219,12 +282,21 @@ public void AgreesWithAScan(string zoneId) } } + // Jellyfin's rule (UserEntityExtensions.IsParentalScheduleAllowed) copied as written, in the + // server's zone; IsAllowed_AgreesWithJellyfin ties it to Jellyfin's own code + private static bool IsAllowed(IReadOnlyList entries, DateTimeOffset instant, TimeZoneInfo zone) + { + var local = TimeZoneInfo.ConvertTime(instant, zone).DateTime; + var hour = local.TimeOfDay.TotalHours; + return entries.Count == 0 || entries.Any(e => e.Covers(local.DayOfWeek) && hour >= e.StartHour && hour <= e.EndHour); + } + private static long? Scan(IReadOnlyList entries, DateTimeOffset now, TimeZoneInfo zone, bool allowed) { for (var minute = 1; minute <= 8 * 24 * 60; minute++) { var probe = now.AddMinutes(minute); - if (AccessWindowController.IsAllowed(entries, probe, zone) == allowed) + if (IsAllowed(entries, probe, zone) == allowed) { continue; } @@ -234,7 +306,7 @@ public void AgreesWithAScan(string zoneId) while (high.UtcTicks - low.UtcTicks > 1) { var middle = low.AddTicks((high.UtcTicks - low.UtcTicks) / 2); - if (AccessWindowController.IsAllowed(entries, middle, zone) == allowed) + if (IsAllowed(entries, middle, zone) == allowed) { low = middle; } @@ -315,7 +387,7 @@ public void IsAllowed_AgreesWithJellyfin(int schedule) foreach (var moment in moments) { - var ours = AccessWindowController.IsAllowed(entries, new DateTimeOffset(moment, TimeSpan.Zero), Utc); + var ours = IsAllowed(entries, new DateTimeOffset(moment, TimeSpan.Zero), Utc); Assert.True(JellyfinAllows(entries, moment) == ours, $"{moment:ddd HH:mm:ss}: Jellyfin and IsAllowed differ ({string.Join(", ", entries)})"); } } From 036076f9e25b46e7774977f2d491f5e308994fd4 Mon Sep 17 00:00:00 2001 From: Ben Date: Thu, 19 Nov 2026 23:37:16 -0500 Subject: [PATCH 6/9] Looked two weeks ahead, matched Jellyfin's hour comparison to the tick, and skipped absurd hours A daylight saving change can skip one week's window entirely (Sunday 02:30-02:45 never happens on New York's spring-forward night), so the next change can be nearly two weeks away. The default look-ahead is now 15 days, and the response docs say two weeks. The first and last tick of an entry are found with Jellyfin's own comparison (TimeOfDay.TotalHours against the stored hours). Hours times ticks per hour can round a tick short: an end of 8.04 still lets the user in at 08:02:24 exactly, and the period closed at that tick. The same search keeps every tick within the day, so hours far out of range (or NaN) give an empty period instead of throwing when the date is built, which answered 500 for the whole schedule. A look-ahead that isn't positive is refused rather than reporting the user as not allowed, and a change exactly at the look-ahead's end is left out, as the docs now say. Co-Authored-By: Claude Opus 5.5 --- .../backend/Api/AccessWindowController.cs | 48 +++++++++++++----- .../Moonfin.Server.Tests/AccessWindowTests.cs | 49 ++++++++++++++++++- 2 files changed, 85 insertions(+), 12 deletions(-) diff --git a/Jellyfin/backend/Api/AccessWindowController.cs b/Jellyfin/backend/Api/AccessWindowController.cs index 2ad7c655..799732f2 100644 --- a/Jellyfin/backend/Api/AccessWindowController.cs +++ b/Jellyfin/backend/Api/AccessWindowController.cs @@ -98,16 +98,17 @@ public ActionResult GetAccessWindow() } } - // Long enough to find any change. The schedule repeats every week, so if nothing changes within a - // week, nothing ever will. The extra day covers a daylight saving change moving the next change - // up to an hour past a week away. - internal static readonly TimeSpan DefaultLookAhead = TimeSpan.FromDays(8); + // Long enough to find any change. The schedule repeats every week, but a daylight saving change can + // skip one week's window entirely (Sunday 02:30-02:45 never happens on New York's spring-forward + // night), and no two such changes come in consecutive weeks. So the next change is at most two + // weeks and an hour away, and nothing changes ever if nothing changes in that time. + internal static readonly TimeSpan DefaultLookAhead = TimeSpan.FromDays(15); /// /// The access window at for a server in : allowed /// when there are no entries or falls in one of the schedule's periods, - /// with the time until that period ends or the next one starts. The time is left out when it's - /// not within . + /// with the time until that period ends or the next one starts. The time is left out unless it + /// comes before the end of , which must be positive. /// internal static AccessWindowResponse Evaluate(IReadOnlyList entries, DateTimeOffset now, TimeZoneInfo zone, TimeSpan? lookAhead = null) { @@ -116,8 +117,10 @@ internal static AccessWindowResponse Evaluate(IReadOnlyList entri return new AccessWindowResponse { Allowed = true }; } + var span = lookAhead ?? DefaultLookAhead; + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(span, TimeSpan.Zero, nameof(lookAhead)); now = now.ToUniversalTime(); - var limit = now + (lookAhead ?? DefaultLookAhead); + var limit = now + span; var periods = BuildPeriods(entries, now, limit, zone); var current = periods.Find(p => p.Start <= now && now < p.End); var allowed = current != default; @@ -162,8 +165,8 @@ internal static List BuildPeriods(IReadOnlyList ent { // Jellyfin compares the local hour of the day, 0 up to 24, with the hours as stored, // so an end past 24 lasts to midnight and a start below 0 is midnight - var open = (long)Math.Ceiling(Math.Clamp(entry.StartHour, 0, 24) * TimeSpan.TicksPerHour); - var close = (long)Math.Min(Math.Floor(entry.EndHour * TimeSpan.TicksPerHour) + 1, TimeSpan.TicksPerDay); + var open = FirstTick(entry.StartHour, hour => hour >= entry.StartHour); + var close = FirstTick(entry.EndHour, hour => hour > entry.EndHour); var midnight = day.Ticks - offset.Ticks; var period = new AccessPeriod( Later(start, new DateTimeOffset(midnight + open, TimeSpan.Zero)), @@ -230,6 +233,29 @@ internal static List BuildPeriods(IReadOnlyList ent yield return (start, to, offset); } + /// + /// The first tick of the day at which the hour as Jellyfin reads it (TimeOfDay.TotalHours) passes + /// , or the day's end when none does. The estimate from + /// can be a tick out from rounding (an end of 8.04 still lets the user in + /// at 08:02:24 exactly), so it's moved a tick at a time to where the comparison turns. + /// + private static long FirstTick(double hours, Func passes) + { + var estimate = Math.Clamp(Math.Ceiling(hours * TimeSpan.TicksPerHour), 0, TimeSpan.TicksPerDay); + var tick = double.IsNaN(estimate) ? TimeSpan.TicksPerDay : (long)estimate; + while (tick > 0 && passes(TimeSpan.FromTicks(tick - 1).TotalHours)) + { + tick--; + } + + while (tick < TimeSpan.TicksPerDay && !passes(TimeSpan.FromTicks(tick).TotalHours)) + { + tick++; + } + + return tick; + } + private static DateTimeOffset Earlier(DateTimeOffset a, DateTimeOffset b) => a < b ? a : b; private static DateTimeOffset Later(DateTimeOffset a, DateTimeOffset b) => a > b ? a : b; @@ -259,7 +285,7 @@ public class AccessWindowResponse /// /// When allowed, seconds until the schedule closes, rounded up. Left out when allowed with no - /// schedule, or when it doesn't close within a week. + /// schedule, or when it doesn't close within two weeks (open all week). /// [JsonPropertyName("secondsUntilClose")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -267,7 +293,7 @@ public class AccessWindowResponse /// /// When not allowed, seconds until the schedule next opens, rounded up. Left out when it - /// doesn't open within a week. + /// doesn't open within two weeks (an entry that never opens). /// [JsonPropertyName("secondsUntilOpen")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs index c1ebc762..3875f1d0 100644 --- a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs +++ b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs @@ -223,6 +223,53 @@ public void BuildPeriods_FindsBothChangesInAYear() Assert.Contains(new AccessPeriod(At(2026, 11, 1, 7, 30), At(2026, 11, 1, 9).AddTicks(1)), periods); } + [Fact] + public void SpringForward_SkippedWindow_NamesTheOneAfter() + { + var newYork = Named("America/New_York"); + if (newYork == null) + { + return; + } + + // Sunday 02:30-02:45 never happens on 2026-03-08. Just after the 2026-03-01 window (02:46 EST, + // 07:46Z) the next opening is 2026-03-15 02:30 EDT (06:30Z), 13 days 22:44 on + var window = AccessWindowController.Evaluate([Entry("Sunday", 2.5, 2.75)], At(2026, 3, 1, 7, 46), newYork); + + Assert.False(window.Allowed); + Assert.Equal(1205040, window.SecondsUntilOpen); + } + + [Fact] + public void AFractionalEnd_ClosesAtJellyfinsTick() + { + // Jellyfin still lets the user in at 08:02:24 exactly for an end of 8.04, where the hours times + // the ticks in an hour rounds to just below that tick + var monday = At(2026, 11, 16, 0); + var periods = AccessWindowController.BuildPeriods([Entry("Monday", 8, 8.04)], monday, monday.AddDays(1), Utc); + + Assert.Equal(new AccessPeriod(At(2026, 11, 16, 8), At(2026, 11, 16, 8, 2).AddSeconds(24).AddTicks(1)), Assert.Single(periods)); + Assert.Equal(2, AccessWindowController.Evaluate([Entry("Monday", 8, 8.04)], At(2026, 11, 16, 8, 2).AddSeconds(23), Utc).SecondsUntilClose); + } + + [Fact] + public void AbsurdHours_AreSkippedWithoutBreakingTheRest() + { + // Jellyfin stores the hours as given; these never let the user in, and mustn't stop the valid entry + var entries = new[] { Entry("Monday", 8, -100_000_000), Entry("Monday", 100_000_000, 200_000_000), Entry("Monday", double.NaN, 12), Entry("Monday", 9, 17) }; + var window = AccessWindowController.Evaluate(entries, At(2026, 11, 16, 12), Utc); + + Assert.True(window.Allowed); + // The end hour is included, so it closes a tick after 17:00, rounded up to the next second + Assert.Equal(5 * 3600 + 1, window.SecondsUntilClose); + } + + [Fact] + public void LookAhead_MustBePositive() + { + Assert.Throws(() => AccessWindowController.Evaluate([Entry("Weekday", 8, 20)], At(2026, 11, 16, 12), Utc, TimeSpan.Zero)); + } + [Fact] public void LookAhead_LeavesOutChangesBeyondIt() { @@ -293,7 +340,7 @@ private static bool IsAllowed(IReadOnlyList entries, DateTimeOffs private static long? Scan(IReadOnlyList entries, DateTimeOffset now, TimeZoneInfo zone, bool allowed) { - for (var minute = 1; minute <= 8 * 24 * 60; minute++) + for (var minute = 1; minute <= AccessWindowController.DefaultLookAhead.TotalMinutes; minute++) { var probe = now.AddMinutes(minute); if (IsAllowed(entries, probe, zone) == allowed) From 9773a84e0931b42122410453e93d4611a0680db0 Mon Sep 17 00:00:00 2001 From: Ben Date: Fri, 20 Nov 2026 00:03:23 -0500 Subject: [PATCH 7/9] Explained OffsetStretches plainly, and dropped its stale note that the look-ahead is one piece Co-Authored-By: Claude Opus 5.5 --- Jellyfin/backend/Api/AccessWindowController.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Jellyfin/backend/Api/AccessWindowController.cs b/Jellyfin/backend/Api/AccessWindowController.cs index 799732f2..db06b251 100644 --- a/Jellyfin/backend/Api/AccessWindowController.cs +++ b/Jellyfin/backend/Api/AccessWindowController.cs @@ -196,16 +196,20 @@ internal static List BuildPeriods(IReadOnlyList ent return merged; } - // Offset changes are further apart than this in today's rules: the closest are Morocco's around - // Ramadan, about five weeks apart. Half that leaves room for a rule changed at short notice. + // Clock changes are never closer together than this. The closest in today's rules are Morocco's + // around Ramadan, about five weeks apart; two weeks leaves room for a rule changed at short notice. private static readonly TimeSpan OffsetChangeSpacing = TimeSpan.FromDays(14); /// - /// The stretches between the two instants over which the zone's UTC offset holds, split where it - /// changes, found to the tick. .NET has no call for the next change, but a piece shorter than - /// holds one at most, so its ends show whether it does, and a - /// binary search finds it. The default look-ahead is one piece. + /// Splits the time from to into stretches with one UTC + /// offset each, cut wherever the server's clock goes forward or back. /// + /// + /// .NET can't tell us when the next clock change is, so this searches for it. It steps through the + /// time in pieces of . A piece that short holds one change at most, + /// so if the offset at its end differs from its start there is exactly one change in it, and a + /// binary search finds the tick it happens at. + /// private static IEnumerable<(DateTimeOffset Start, DateTimeOffset End, TimeSpan Offset)> OffsetStretches(DateTimeOffset from, DateTimeOffset to, TimeZoneInfo zone) { var start = from; @@ -216,9 +220,11 @@ internal static List BuildPeriods(IReadOnlyList ent var high = Earlier(piece + OffsetChangeSpacing, to); if (zone.GetUtcOffset(high) == offset) { + // Same offset at both ends: no change in this piece continue; } + // Narrow down to the first tick with the new offset while (high.UtcTicks - low.UtcTicks > 1) { var middle = low.AddTicks((high.UtcTicks - low.UtcTicks) / 2); From c8ba32b00a22dc65d1959a1dccab894dd7582c89 Mon Sep 17 00:00:00 2001 From: Ben Date: Fri, 20 Nov 2026 00:44:09 -0500 Subject: [PATCH 8/9] Skipped entries with a NaN hour, which Jellyfin never lets in Jellyfin allows a moment while hour >= StartHour and hour <= EndHour, and both are false for NaN, so such an entry never lets the user in. The close search asked hour > EndHour, also false for NaN, so it found no close and ran the period to midnight: Monday 08:00-NaN was reported open from 08:00. Without the check FirstTick's loops don't finish for a NaN end either. Co-Authored-By: Claude Opus 5.5 --- Jellyfin/backend/Api/AccessWindowController.cs | 9 +++++++-- Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs | 6 +++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Jellyfin/backend/Api/AccessWindowController.cs b/Jellyfin/backend/Api/AccessWindowController.cs index db06b251..62f304af 100644 --- a/Jellyfin/backend/Api/AccessWindowController.cs +++ b/Jellyfin/backend/Api/AccessWindowController.cs @@ -163,6 +163,12 @@ internal static List BuildPeriods(IReadOnlyList ent { foreach (var entry in entries.Where(e => e.Covers(day.DayOfWeek))) { + // Jellyfin's comparisons with a NaN hour are always false, so the entry never lets them in + if (double.IsNaN(entry.StartHour) || double.IsNaN(entry.EndHour)) + { + continue; + } + // Jellyfin compares the local hour of the day, 0 up to 24, with the hours as stored, // so an end past 24 lasts to midnight and a start below 0 is midnight var open = FirstTick(entry.StartHour, hour => hour >= entry.StartHour); @@ -247,8 +253,7 @@ internal static List BuildPeriods(IReadOnlyList ent /// private static long FirstTick(double hours, Func passes) { - var estimate = Math.Clamp(Math.Ceiling(hours * TimeSpan.TicksPerHour), 0, TimeSpan.TicksPerDay); - var tick = double.IsNaN(estimate) ? TimeSpan.TicksPerDay : (long)estimate; + var tick = (long)Math.Clamp(Math.Ceiling(hours * TimeSpan.TicksPerHour), 0, TimeSpan.TicksPerDay); while (tick > 0 && passes(TimeSpan.FromTicks(tick - 1).TotalHours)) { tick--; diff --git a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs index 3875f1d0..504b6b5d 100644 --- a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs +++ b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs @@ -256,7 +256,11 @@ public void AFractionalEnd_ClosesAtJellyfinsTick() public void AbsurdHours_AreSkippedWithoutBreakingTheRest() { // Jellyfin stores the hours as given; these never let the user in, and mustn't stop the valid entry - var entries = new[] { Entry("Monday", 8, -100_000_000), Entry("Monday", 100_000_000, 200_000_000), Entry("Monday", double.NaN, 12), Entry("Monday", 9, 17) }; + var entries = new[] + { + Entry("Monday", 8, -100_000_000), Entry("Monday", 100_000_000, 200_000_000), + Entry("Monday", double.NaN, 12), Entry("Monday", 8, double.NaN), Entry("Monday", 9, 17), + }; var window = AccessWindowController.Evaluate(entries, At(2026, 11, 16, 12), Utc); Assert.True(window.Allowed); From 0d226b858fd355f135f87893a93046eccf2480b4 Mon Sep 17 00:00:00 2001 From: Ben Date: Fri, 20 Nov 2026 00:48:13 -0500 Subject: [PATCH 9/9] Tested a change exactly at the look-ahead's end: left out, and given a tick later Co-Authored-By: Claude Opus 5.5 --- .../tests/Moonfin.Server.Tests/AccessWindowTests.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs index 504b6b5d..7ed3f2ed 100644 --- a/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs +++ b/Jellyfin/tests/Moonfin.Server.Tests/AccessWindowTests.cs @@ -284,6 +284,17 @@ public void LookAhead_LeavesOutChangesBeyondIt() Assert.Null(window.SecondsUntilOpen); } + [Fact] + public void LookAhead_LeavesOutAChangeExactlyAtItsEnd() + { + // Friday 21:00, opens Monday 08:00, exactly 59 hours on: left out at 59 hours, given a tick later + var friday = At(2026, 11, 20, 21); + var entries = new[] { Entry("Weekday", 8, 20) }; + + Assert.Null(AccessWindowController.Evaluate(entries, friday, Utc, TimeSpan.FromHours(59)).SecondsUntilOpen); + Assert.Equal(59 * 3600, AccessWindowController.Evaluate(entries, friday, Utc, TimeSpan.FromHours(59).Add(TimeSpan.FromTicks(1))).SecondsUntilOpen); + } + public static IEnumerable Zones() => new[] { "America/New_York", "Australia/Sydney", "Europe/London", "Asia/Kolkata", "Pacific/Chatham" } .Select(id => new object[] { id });