Repository navigation
Added Moonfin/Time: the server's clock and time zone #364
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f08efa8
Added Moonfin/Time: the server's clock and time zone, for access sche…
benklop 52aab6d
Added the server's next offset change to Moonfin/Time, so a client ca…
benklop 57c125c
Let Moonfin/Time and Ping skip the access-schedule check
benklop 804c132
Said the next offset change is left out of Moonfin/Time when there is…
benklop f115146
Said the next offset from Moonfin/Time holds only until the change af…
benklop File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| using System.Globalization; | ||
| using System.Net.Mime; | ||
| using System.Text.Json.Serialization; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace Moonfin.Server.Api; | ||
|
|
||
| /// <summary> | ||
| /// The server's clock and time zone. Jellyfin judges a user's access schedule against the server's | ||
| /// local time, which no stock endpoint reports, so a client in another zone can't work out when | ||
| /// the account is open or next opens without it. | ||
| /// </summary> | ||
| [ApiController] | ||
| [Route("Moonfin")] | ||
| [Produces(MediaTypeNames.Application.Json)] | ||
| public class ServerTimeController : ControllerBase | ||
| { | ||
| /// <summary>The server's current time, its UTC offset and its time zone.</summary> | ||
| /// <remarks> | ||
| /// Skips the access-schedule check: a user outside their hours is exactly the one whose client | ||
| /// needs the server clock to say when the account next opens. | ||
| /// </remarks> | ||
| [HttpGet("Time")] | ||
| [Authorize(Policy = "IgnoreParentalControl")] | ||
| [ProducesResponseType(StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
| public ActionResult<ServerTimeResponse> GetTime() | ||
| { | ||
| return Ok(Describe(DateTimeOffset.UtcNow, TimeZoneInfo.Local)); | ||
| } | ||
|
|
||
| /// <summary>Builds the response for an instant and zone, so it can be checked without a clock.</summary> | ||
| internal static ServerTimeResponse Describe(DateTimeOffset now, TimeZoneInfo zone) | ||
| { | ||
| var utc = now.ToUniversalTime(); | ||
| var local = TimeZoneInfo.ConvertTime(utc, zone); | ||
|
|
||
| var time = new ServerTimeResponse | ||
| { | ||
| UtcTime = utc.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture), | ||
| LocalTime = local.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture), | ||
| UtcOffsetSeconds = (int)zone.GetUtcOffset(utc).TotalSeconds, | ||
| TimeZoneId = zone.Id, | ||
| IsDaylightSavingTime = zone.IsDaylightSavingTime(utc), | ||
| }; | ||
|
|
||
| var change = NextOffsetChange(utc, zone); | ||
| if (change is { } next) | ||
| { | ||
| time.NextOffsetChangeUtc = next.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture); | ||
| time.NextUtcOffsetSeconds = (int)zone.GetUtcOffset(next).TotalSeconds; | ||
| } | ||
|
|
||
| return time; | ||
| } | ||
|
|
||
| // Far enough to find the next change in any zone that has them, which come at most a year apart | ||
| private const int LookAheadDays = 400; | ||
|
|
||
| /// <summary> | ||
| /// The first instant after <paramref name="utc"/> at which the zone's offset differs from its | ||
| /// offset now, to the second, or null when it doesn't change within the look-ahead. Found by | ||
| /// stepping a day at a time and then halving the day, so it relies only on GetUtcOffset and | ||
| /// not on how the zone's adjustment rules are written. | ||
| /// </summary> | ||
| internal static DateTimeOffset? NextOffsetChange(DateTimeOffset utc, TimeZoneInfo zone) | ||
| { | ||
| var start = utc.ToUniversalTime(); | ||
| var offset = zone.GetUtcOffset(start); | ||
| var before = start; | ||
| DateTimeOffset? after = null; | ||
|
|
||
| for (var day = 1; day <= LookAheadDays; day++) | ||
| { | ||
| var probe = start.AddDays(day); | ||
| if (zone.GetUtcOffset(probe) != offset) | ||
| { | ||
| after = probe; | ||
| break; | ||
| } | ||
|
|
||
| before = probe; | ||
| } | ||
|
|
||
| if (after is not { } high) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| // The offset is the old one at before and the new one at high; close in to the second | ||
| var low = before; | ||
| while ((high - low).TotalSeconds > 1) | ||
| { | ||
| var middle = low.AddTicks((high - low).Ticks / 2); | ||
| if (zone.GetUtcOffset(middle) == offset) | ||
| { | ||
| low = middle; | ||
| } | ||
| else | ||
| { | ||
| high = middle; | ||
| } | ||
| } | ||
|
|
||
| return new DateTimeOffset(high.UtcTicks - (high.UtcTicks % TimeSpan.TicksPerSecond), TimeSpan.Zero); | ||
| } | ||
| } | ||
|
|
||
| public class ServerTimeResponse | ||
| { | ||
| /// <summary>The instant, as ISO 8601 UTC with a trailing Z.</summary> | ||
| [JsonPropertyName("utcTime")] | ||
| public string UtcTime { get; set; } = string.Empty; | ||
|
|
||
| /// <summary>The same instant on the server's wall clock, with no offset. This is what an access schedule is judged against.</summary> | ||
| [JsonPropertyName("localTime")] | ||
| public string LocalTime { get; set; } = string.Empty; | ||
|
|
||
| /// <summary>The server's offset from UTC right now, in seconds, east positive.</summary> | ||
| [JsonPropertyName("utcOffsetSeconds")] | ||
| public int UtcOffsetSeconds { get; set; } | ||
|
|
||
| /// <summary>The server's time zone id as the host names it.</summary> | ||
| [JsonPropertyName("timeZoneId")] | ||
| public string TimeZoneId { get; set; } = string.Empty; | ||
|
|
||
| [JsonPropertyName("isDaylightSavingTime")] | ||
| public bool IsDaylightSavingTime { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// When the server's offset next changes, as ISO 8601 UTC with a trailing Z. Left out of the | ||
| /// response when it doesn't change within about a year, as it is by plugins that predate it, so | ||
| /// clients treat a missing key as no change. A client turning a future time on the server's | ||
| /// wall clock into an instant uses <see cref="NextUtcOffsetSeconds"/> from this change until | ||
| /// the one after it, which this response doesn't describe: for times past that, ask again | ||
| /// after this change. | ||
| /// </summary> | ||
| [JsonPropertyName("nextOffsetChangeUtc")] | ||
| public string? NextOffsetChangeUtc { get; set; } | ||
|
|
||
| /// <summary>The server's offset from UTC after that change, in seconds, east positive, until the change after it. Left out along with it.</summary> | ||
| [JsonPropertyName("nextUtcOffsetSeconds")] | ||
| public int? NextUtcOffsetSeconds { get; set; } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| using System.Reflection; | ||
| using System.Text.Json; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Moonfin.Server.Api; | ||
| using Xunit; | ||
|
|
||
| namespace Moonfin.Server.Tests; | ||
|
|
||
| public sealed class ServerTimeTests | ||
| { | ||
| private static TimeZoneInfo Zone(string offset) => | ||
| TimeZoneInfo.CreateCustomTimeZone("Test/Zone", TimeSpan.Parse(offset), "Test", "Test"); | ||
|
|
||
| [Fact] | ||
| public void Describe_ReportsUtcAndTheServerWallClock() | ||
| { | ||
| var time = ServerTimeController.Describe(new DateTimeOffset(2026, 3, 1, 23, 30, 0, TimeSpan.Zero), Zone("05:30")); | ||
|
|
||
| Assert.Equal("2026-03-01T23:30:00Z", time.UtcTime); | ||
| Assert.Equal("2026-03-02T05:00:00", time.LocalTime); | ||
| Assert.Equal(19800, time.UtcOffsetSeconds); | ||
| Assert.Equal("Test/Zone", time.TimeZoneId); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void Describe_NegativeOffsetRollsTheDayBack() | ||
| { | ||
| var time = ServerTimeController.Describe(new DateTimeOffset(2026, 3, 1, 2, 0, 0, TimeSpan.FromHours(3)), Zone("-08:00")); | ||
|
|
||
| Assert.Equal("2026-02-28T23:00:00Z", time.UtcTime); | ||
| Assert.Equal("2026-02-28T15:00:00", time.LocalTime); | ||
| Assert.Equal(-28800, time.UtcOffsetSeconds); | ||
| } | ||
|
|
||
| // Skipped quietly on a host with no tz database, where the zone can't be looked up. | ||
| [Fact] | ||
| public void Describe_FollowsDaylightSavingTransitions() | ||
| { | ||
| TimeZoneInfo zone; | ||
| try | ||
| { | ||
| zone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); | ||
| } | ||
| catch (TimeZoneNotFoundException) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var winter = ServerTimeController.Describe(new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero), zone); | ||
| var summer = ServerTimeController.Describe(new DateTimeOffset(2026, 7, 15, 12, 0, 0, TimeSpan.Zero), zone); | ||
|
|
||
| Assert.Equal(-18000, winter.UtcOffsetSeconds); | ||
| Assert.False(winter.IsDaylightSavingTime); | ||
| Assert.Equal(-14400, summer.UtcOffsetSeconds); | ||
| Assert.True(summer.IsDaylightSavingTime); | ||
| } | ||
|
|
||
| // Clients read these exact keys, so a rename would leave them on the device clock unnoticed. | ||
| [Fact] | ||
| public void Response_UsesTheKeysClientsRead() | ||
| { | ||
| var json = JsonSerializer.Serialize(ServerTimeController.Describe(DateTimeOffset.UtcNow, TimeZoneInfo.Utc)); | ||
|
|
||
| foreach (var key in new[] { "utcTime", "localTime", "utcOffsetSeconds", "timeZoneId", "isDaylightSavingTime", "nextOffsetChangeUtc", "nextUtcOffsetSeconds" }) | ||
| { | ||
| Assert.Contains($"\"{key}\"", json); | ||
| } | ||
| } | ||
|
|
||
| private static TimeZoneInfo? Named(string id) | ||
| { | ||
| try | ||
| { | ||
| return TimeZoneInfo.FindSystemTimeZoneById(id); | ||
| } | ||
| catch (TimeZoneNotFoundException) | ||
| { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public void Describe_AFixedOffsetHasNoNextChange() | ||
| { | ||
| var time = ServerTimeController.Describe(new DateTimeOffset(2026, 3, 1, 12, 0, 0, TimeSpan.Zero), Zone("05:30")); | ||
|
|
||
| Assert.Null(time.NextOffsetChangeUtc); | ||
| Assert.Null(time.NextUtcOffsetSeconds); | ||
| } | ||
|
|
||
| // The night US daylight saving ended in 2026: 02:00 EDT became 01:00 EST at 06:00 UTC | ||
| [Fact] | ||
| public void Describe_NamesTheNextChangeToTheSecond() | ||
| { | ||
| if (Named("America/New_York") is not { } zone) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var time = ServerTimeController.Describe(new DateTimeOffset(2026, 11, 1, 5, 16, 4, TimeSpan.Zero), zone); | ||
|
|
||
| Assert.Equal(-14400, time.UtcOffsetSeconds); | ||
| Assert.Equal("2026-11-01T06:00:00Z", time.NextOffsetChangeUtc); | ||
| Assert.Equal(-18000, time.NextUtcOffsetSeconds); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void Describe_LooksMonthsAhead() | ||
| { | ||
| if (Named("America/New_York") is not { } zone) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var summer = ServerTimeController.Describe(new DateTimeOffset(2026, 7, 15, 12, 0, 0, TimeSpan.Zero), zone); | ||
| var winter = ServerTimeController.Describe(new DateTimeOffset(2026, 12, 15, 12, 0, 0, TimeSpan.Zero), zone); | ||
|
|
||
| Assert.Equal("2026-11-01T06:00:00Z", summer.NextOffsetChangeUtc); | ||
| Assert.Equal(-18000, summer.NextUtcOffsetSeconds); | ||
| Assert.Equal("2027-03-14T07:00:00Z", winter.NextOffsetChangeUtc); | ||
| Assert.Equal(-14400, winter.NextUtcOffsetSeconds); | ||
| } | ||
|
|
||
| // Southern hemisphere: Sydney leaves daylight saving in April, 03:00 AEDT back to 02:00 AEST | ||
| [Fact] | ||
| public void Describe_FollowsASouthernZone() | ||
| { | ||
| if (Named("Australia/Sydney") is not { } zone) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var time = ServerTimeController.Describe(new DateTimeOffset(2027, 1, 10, 0, 0, 0, TimeSpan.Zero), zone); | ||
|
|
||
| Assert.Equal(39600, time.UtcOffsetSeconds); | ||
| Assert.Equal("2027-04-03T16:00:00Z", time.NextOffsetChangeUtc); | ||
| Assert.Equal(36000, time.NextUtcOffsetSeconds); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void NextOffsetChange_IsNullWithoutChanges() | ||
| { | ||
| Assert.Null(ServerTimeController.NextOffsetChange(DateTimeOffset.UtcNow, TimeZoneInfo.Utc)); | ||
| } | ||
|
|
||
| // Jellyfin's default policy refuses a user outside their access schedule, which is when the | ||
| // client most needs the server clock and the Ping flag that says it can ask for it. | ||
| [Theory] | ||
| [InlineData(typeof(ServerTimeController), nameof(ServerTimeController.GetTime))] | ||
| [InlineData(typeof(MoonfinController), nameof(MoonfinController.Ping))] | ||
| public void Endpoint_IsReachableOutsideTheAccessSchedule(Type controller, string action) | ||
| { | ||
| var authorize = controller.GetMethod(action)!.GetCustomAttribute<AuthorizeAttribute>(); | ||
|
|
||
| Assert.NotNull(authorize); | ||
| Assert.Equal("IgnoreParentalControl", authorize!.Policy); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.