Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion Jellyfin/backend/Api/MoonfinController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,12 @@ public ActionResult RestoreConfigFromBackup()
/// Ping endpoint to check if Moonfin plugin is installed.
/// </summary>
/// <returns>Plugin status information including admin defaults.</returns>
/// <remarks>
/// 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 server time.
/// </remarks>
[HttpGet("Ping")]
[Authorize]
[Authorize(Policy = "IgnoreParentalControl")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<MoonfinPingResponse> Ping()
{
Expand All @@ -143,6 +147,7 @@ public ActionResult<MoonfinPingResponse> Ping()
PinSupported = true,
IncompleteRecordingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true,
ExtendedCompleteShowingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true,
TimeSupported = true,
RecommendationsSupported = config?.RecommendationsProviderEnabled ?? true,
DefaultSettings = config?.DefaultUserSettings
});
Expand Down Expand Up @@ -1605,6 +1610,13 @@ public class MoonfinPingResponse
[JsonPropertyName("extendedCompleteShowingsSupported")]
public bool? ExtendedCompleteShowingsSupported { get; set; }

/// <summary>
/// True when this plugin reports the server's clock and time zone at Moonfin/Time. Older
/// plugins leave it out, so the app falls back to the device clock.
/// </summary>
[JsonPropertyName("timeSupported")]
public bool? TimeSupported { get; set; }

/// <summary>
/// True when this plugin supports server-side recommendations scoring.
/// </summary>
Expand Down
146 changes: 146 additions & 0 deletions Jellyfin/backend/Api/ServerTimeController.cs
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")]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
[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; }
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
158 changes: 158 additions & 0 deletions Jellyfin/tests/Moonfin.Server.Tests/ServerTimeTests.cs
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);
}
}
Loading