fix(jellyfin): harden player-owned playback probe

Pin discovery/open to a short schedule-identity snapshot without sharing mutable Jellyfin media sources, gate the authorization-incomplete lab probe behind an explicit opt-in, and add focused plugin tests to the main solution. Redact remote URLs and serialize OpenAPI ApiKey requirements correctly.

Refs #357

Co-Authored-By: OpenAI Codex <codex@openai.com>
This commit is contained in:
2026-07-15 19:07:55 +02:00
co-authored by OpenAI Codex
parent dd4ce6f378
commit 63f72c7c50
21 changed files with 1584 additions and 313 deletions
@@ -137,10 +137,7 @@ public class GetChannelPlaybackSourceHandler(IDbContextFactory<TvContext> dbCont
PlexOtherVideo video => Reference(ChannelPlaybackSourceKind.PlexItem, itemId: video.Key),
EmbyMovie movie => Reference(ChannelPlaybackSourceKind.EmbyItem, itemId: movie.ItemId),
EmbyEpisode episode => Reference(ChannelPlaybackSourceKind.EmbyItem, itemId: episode.ItemId),
RemoteStream stream => Reference(
ChannelPlaybackSourceKind.RemoteUrl,
url: stream.Url,
isLive: stream.IsLive),
RemoteStream stream => Reference(ChannelPlaybackSourceKind.RemoteUrl, isLive: stream.IsLive),
Movie movie => LocalFile(movie.MediaVersions),
Episode episode => LocalFile(episode.MediaVersions),
MusicVideo video => LocalFile(video.MediaVersions),
@@ -162,7 +159,6 @@ public class GetChannelPlaybackSourceHandler(IDbContextFactory<TvContext> dbCont
ChannelPlaybackSourceKind kind,
string? itemId = null,
string? path = null,
string? url = null,
bool isLive = false) =>
new(kind, itemId, path, url, isLive);
new(kind, itemId, path, isLive);
}
@@ -19,7 +19,6 @@ public record ChannelPlaybackSourceReferenceResponseModel(
ChannelPlaybackSourceKind Kind,
string? ItemId,
string? Path,
string? Url,
bool IsLive);
/// <summary>The physical playout item covering the requested channel time.</summary>
@@ -176,26 +176,73 @@ public class GetChannelPlaybackSourceHandlerTests
result.Active.ShouldNotBeNull();
result.Active.Start.ShouldBe(new DateTimeOffset(sourceStart + offset, TimeSpan.Zero));
result.Active.Finish.ShouldBe(new DateTimeOffset(sourceFinish + offset, TimeSpan.Zero));
result.NextTransitionAt.ShouldBe(new DateTimeOffset(sourceFinish + offset, TimeSpan.Zero));
result.Active.CurrentOffsetTicks.ShouldBe(TimeSpan.FromMinutes(5).Ticks);
result.Active.Source.Kind.ShouldBe(ChannelPlaybackSourceKind.RemoteUrl);
result.Active.Source.IsLive.ShouldBeTrue();
}
[Test]
public async Task Handle_Should_Use_Half_Open_Boundary_And_Return_Next_Start_During_Gap()
public async Task Handle_Should_Select_Item_At_Start_And_Exclude_Item_At_Finish()
{
await using (TvContext context = _db.CreateContext())
{
Channel channel = MakeChannel(11, "11");
var movie = new Movie { Id = 110, MovieMetadata = [], MediaVersions = [] };
var playout = new Playout { Id = 111, Channel = channel, ChannelId = channel.Id, Items = [] };
var first = new Movie { Id = 110, MovieMetadata = [], MediaVersions = [] };
var second = new Movie { Id = 111, MovieMetadata = [], MediaVersions = [] };
var playout = new Playout { Id = 112, Channel = channel, ChannelId = channel.Id, Items = [] };
context.Channels.Add(channel);
context.Movies.AddRange(first, second);
context.Playouts.Add(playout);
context.PlayoutItems.AddRange(
new PlayoutItem
{
Id = 113,
MediaItem = first,
MediaItemId = first.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = Now.UtcDateTime.AddMinutes(-30),
Finish = Now.UtcDateTime
},
new PlayoutItem
{
Id = 114,
MediaItem = second,
MediaItemId = second.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = Now.UtcDateTime,
Finish = Now.UtcDateTime.AddMinutes(30)
});
await context.SaveChangesAsync();
}
ChannelPlaybackSourceResponseModel result = await GetResult(11, Now);
result.Active.ShouldNotBeNull();
result.Active.PlayoutItemId.ShouldBe(114);
result.Active.MediaItemId.ShouldBe(111);
result.Active.Start.ShouldBe(Now);
result.Active.CurrentOffsetTicks.ShouldBe(TimeSpan.Zero.Ticks);
result.NextTransitionAt.ShouldBe(Now.AddMinutes(30));
}
[Test]
public async Task Handle_Should_Return_Next_Start_During_Gap()
{
await using (TvContext context = _db.CreateContext())
{
Channel channel = MakeChannel(12, "12");
var movie = new Movie { Id = 120, MovieMetadata = [], MediaVersions = [] };
var playout = new Playout { Id = 121, Channel = channel, ChannelId = channel.Id, Items = [] };
context.Channels.Add(channel);
context.Movies.Add(movie);
context.Playouts.Add(playout);
context.PlayoutItems.AddRange(
new PlayoutItem
{
Id = 112,
Id = 122,
MediaItem = movie,
MediaItemId = movie.Id,
Playout = playout,
@@ -205,7 +252,7 @@ public class GetChannelPlaybackSourceHandlerTests
},
new PlayoutItem
{
Id = 113,
Id = 123,
MediaItem = movie,
MediaItemId = movie.Id,
Playout = playout,
@@ -216,12 +263,103 @@ public class GetChannelPlaybackSourceHandlerTests
await context.SaveChangesAsync();
}
ChannelPlaybackSourceResponseModel result = await GetResult(11, Now);
ChannelPlaybackSourceResponseModel result = await GetResult(12, Now);
result.Active.ShouldBeNull();
result.NextTransitionAt.ShouldBe(Now.AddMinutes(10));
}
[Test]
public async Task Handle_Should_Return_No_Next_Transition_During_Terminal_Gap()
{
await using (TvContext context = _db.CreateContext())
{
Channel channel = MakeChannel(13, "13");
var movie = new Movie { Id = 130, MovieMetadata = [], MediaVersions = [] };
var playout = new Playout { Id = 131, Channel = channel, ChannelId = channel.Id, Items = [] };
var finishedItem = new PlayoutItem
{
Id = 132,
MediaItem = movie,
MediaItemId = movie.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = Now.UtcDateTime.AddHours(-1),
Finish = Now.UtcDateTime.AddMinutes(-30)
};
context.Channels.Add(channel);
context.Movies.Add(movie);
context.Playouts.Add(playout);
context.PlayoutItems.Add(finishedItem);
await context.SaveChangesAsync();
}
ChannelPlaybackSourceResponseModel result = await GetResult(13, Now);
result.Active.ShouldBeNull();
result.NextTransitionAt.ShouldBeNull();
}
[Test]
public async Task Handle_Should_Map_Server_Items_And_Unsupported_Empty_Local_Media()
{
const string jellyfinItemId = "jellyfin-episode";
const string plexKey = "/library/metadata/123";
const string embyItemId = "emby-movie";
await using (TvContext context = _db.CreateContext())
{
var jellyfinEpisode = new JellyfinEpisode
{
Id = 140,
ItemId = jellyfinItemId,
Etag = string.Empty,
EpisodeMetadata = [],
MediaVersions = []
};
var plexMovie = new PlexMovie
{
Id = 150,
Key = plexKey,
Etag = string.Empty,
MovieMetadata = [],
MediaVersions = []
};
var embyMovie = new EmbyMovie
{
Id = 160,
ItemId = embyItemId,
Etag = string.Empty,
MovieMetadata = [],
MediaVersions = []
};
var emptyLocalMovie = new Movie { Id = 170, MovieMetadata = [], MediaVersions = [] };
AddActiveItem(context, MakeChannel(14, "14"), jellyfinEpisode, 141, 142);
AddActiveItem(context, MakeChannel(15, "15"), plexMovie, 151, 152);
AddActiveItem(context, MakeChannel(16, "16"), embyMovie, 161, 162);
AddActiveItem(context, MakeChannel(17, "17"), emptyLocalMovie, 171, 172);
await context.SaveChangesAsync();
}
ChannelPlaybackSourceReferenceResponseModel jellyfin = (await GetResult(14, Now)).Active!.Source;
ChannelPlaybackSourceReferenceResponseModel plex = (await GetResult(15, Now)).Active!.Source;
ChannelPlaybackSourceReferenceResponseModel emby = (await GetResult(16, Now)).Active!.Source;
ChannelPlaybackSourceReferenceResponseModel unsupported = (await GetResult(17, Now)).Active!.Source;
jellyfin.Kind.ShouldBe(ChannelPlaybackSourceKind.JellyfinItem);
jellyfin.ItemId.ShouldBe(jellyfinItemId);
plex.Kind.ShouldBe(ChannelPlaybackSourceKind.PlexItem);
plex.ItemId.ShouldBe(plexKey);
emby.Kind.ShouldBe(ChannelPlaybackSourceKind.EmbyItem);
emby.ItemId.ShouldBe(embyItemId);
unsupported.Kind.ShouldBe(ChannelPlaybackSourceKind.Unsupported);
unsupported.ItemId.ShouldBeNull();
unsupported.Path.ShouldBeNull();
unsupported.IsLive.ShouldBeFalse();
}
[Test]
public async Task Handle_Should_Return_None_For_Missing_Channel()
{
@@ -245,6 +383,31 @@ public class GetChannelPlaybackSourceHandlerTests
None: () => throw new AssertionException("Expected a playback-source response"));
}
private static void AddActiveItem(
TvContext context,
Channel channel,
MediaItem mediaItem,
int playoutId,
int playoutItemId)
{
var playout = new Playout { Id = playoutId, Channel = channel, ChannelId = channel.Id, Items = [] };
var item = new PlayoutItem
{
Id = playoutItemId,
MediaItem = mediaItem,
MediaItemId = mediaItem.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = Now.UtcDateTime.AddMinutes(-1),
Finish = Now.UtcDateTime.AddMinutes(1)
};
context.Channels.Add(channel);
context.MediaItems.Add(mediaItem);
context.Playouts.Add(playout);
context.PlayoutItems.Add(item);
}
private static Channel MakeChannel(int id, string number) =>
new(Guid.NewGuid())
{
@@ -1,3 +1,4 @@
using System.Text.Json;
using ErsatzTV.Serialization;
using ErsatzTV.Tests.Support;
using Microsoft.OpenApi;
@@ -71,6 +72,32 @@ public class OpenApiContractHonestyTests
}
}
[Test]
public async Task Serialized_Gated_Operations_Should_Name_The_ApiKey_Scheme()
{
string json = await _document.SerializeAsJsonAsync(
OpenApiSpecVersion.OpenApi3_1,
CancellationToken.None);
using JsonDocument serialized = JsonDocument.Parse(json);
foreach (JsonProperty path in serialized.RootElement.GetProperty("paths").EnumerateObject())
{
foreach (JsonProperty operation in path.Value.EnumerateObject())
{
if (operation.NameEquals("parameters"))
{
continue;
}
JsonElement security = operation.Value.GetProperty("security");
security.GetArrayLength().ShouldBeGreaterThan(0, $"{operation.Name} {path.Name} should declare security");
security[0].TryGetProperty(ApiSecurityOperationTransformer.SchemeName, out JsonElement scopes)
.ShouldBeTrue($"{operation.Name} {path.Name} should name the ApiKey scheme after serialization");
scopes.ValueKind.ShouldBe(JsonValueKind.Array);
}
}
}
[Test]
public void Troubleshoot_Playback_Actions_Should_Carry_Stable_Explicit_OperationIds()
{
+47
View File
@@ -32,6 +32,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ErsatzTV.Tests", "ErsatzTV.
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ErsatzTV.Architecture.Tests", "ErsatzTV.Architecture.Tests\ErsatzTV.Architecture.Tests.csproj", "{49123AF1-38FE-4546-9DBD-8B7F1B4CFC7F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "integrations", "integrations", "{4958D7D8-4791-2CCE-6FFA-082B65933577}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "jellyfin", "jellyfin", "{65793B68-0114-8A23-3D53-9EDEAEBFFD0F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.ChicoryTV", "integrations\jellyfin\Jellyfin.Plugin.ChicoryTV\Jellyfin.Plugin.ChicoryTV.csproj", "{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.ChicoryTV.Tests", "integrations\jellyfin\Jellyfin.Plugin.ChicoryTV.Tests\Jellyfin.Plugin.ChicoryTV.Tests.csproj", "{10235034-68F6-44AC-8C54-4C6F12DAD534}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -315,6 +323,42 @@ Global
{49123AF1-38FE-4546-9DBD-8B7F1B4CFC7F}.Debug No Sync|x64.Build.0 = Debug|Any CPU
{49123AF1-38FE-4546-9DBD-8B7F1B4CFC7F}.Debug No Sync|x86.ActiveCfg = Debug|Any CPU
{49123AF1-38FE-4546-9DBD-8B7F1B4CFC7F}.Debug No Sync|x86.Build.0 = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug|x64.ActiveCfg = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug|x64.Build.0 = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug|x86.ActiveCfg = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug|x86.Build.0 = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Release|Any CPU.Build.0 = Release|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Release|x64.ActiveCfg = Release|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Release|x64.Build.0 = Release|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Release|x86.ActiveCfg = Release|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Release|x86.Build.0 = Release|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug No Sync|Any CPU.ActiveCfg = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug No Sync|Any CPU.Build.0 = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug No Sync|x64.ActiveCfg = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug No Sync|x64.Build.0 = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug No Sync|x86.ActiveCfg = Debug|Any CPU
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8}.Debug No Sync|x86.Build.0 = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug|Any CPU.Build.0 = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug|x64.ActiveCfg = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug|x64.Build.0 = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug|x86.ActiveCfg = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug|x86.Build.0 = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Release|Any CPU.ActiveCfg = Release|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Release|Any CPU.Build.0 = Release|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Release|x64.ActiveCfg = Release|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Release|x64.Build.0 = Release|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Release|x86.ActiveCfg = Release|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Release|x86.Build.0 = Release|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug No Sync|Any CPU.ActiveCfg = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug No Sync|Any CPU.Build.0 = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug No Sync|x64.ActiveCfg = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug No Sync|x64.Build.0 = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug No Sync|x86.ActiveCfg = Debug|Any CPU
{10235034-68F6-44AC-8C54-4C6F12DAD534}.Debug No Sync|x86.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -325,5 +369,8 @@ Global
{591FB3F4-4DD8-441B-B7C8-F2A42BF69992} = {325E6DA0-52B3-4431-98A2-72C36F403704}
{2EF80455-953D-4696-831D-E8CBCA82B0EF} = {325E6DA0-52B3-4431-98A2-72C36F403704}
{56F56E76-CEF4-4639-B7BB-03FD201BB019} = {325E6DA0-52B3-4431-98A2-72C36F403704}
{65793B68-0114-8A23-3D53-9EDEAEBFFD0F} = {4958D7D8-4791-2CCE-6FFA-082B65933577}
{5E6B1E48-F229-4FE1-8BA6-66994ADBE5A8} = {65793B68-0114-8A23-3D53-9EDEAEBFFD0F}
{10235034-68F6-44AC-8C54-4C6F12DAD534} = {65793B68-0114-8A23-3D53-9EDEAEBFFD0F}
EndGlobalSection
EndGlobal
@@ -36,7 +36,11 @@ public sealed class ApiSecurityOperationTransformer(IApiKeyProvider apiKeyProvid
operation.Security ??= new List<OpenApiSecurityRequirement>();
operation.Security.Add(new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference(SchemeName)] = new List<string>()
// Microsoft.OpenApi 2.x needs the host document to serialize this as the
// component name. Without it the in-memory requirement looks populated,
// but the generated JSON contains `security: [ {} ]`, which means anonymous
// access in OpenAPI rather than the X-Api-Key requirement enforced at runtime.
[new OpenApiSecuritySchemeReference(SchemeName, context.Document, null)] = new List<string>()
});
operation.Responses ??= new OpenApiResponses();
File diff suppressed because it is too large Load Diff
+12 -7
View File
@@ -11,16 +11,18 @@ desired ownership model.
Stock Jellyfin 12.0-rc2 does **not**, however, give an `ILiveTvService` provider a way to supply the
schedule-derived position in that file. Jellyfin seeks from the client's `StartTimeTicks`; its web client
tunes a Live TV channel with zero, and the provider's stream methods receive no start-time argument.
Jellyfin also normalizes provider sources as infinite Live TV, while opening the selected source only once.
It does not reopen the channel when a finite file reaches the next scheduled boundary.
Jellyfin also marks provider sources as infinite Live TV. The directly usable native-file path retains the
backing source's finite runtime metadata, but Jellyfin still does not treat that runtime or the EPG boundary as
a request to reopen the channel on the next scheduled item.
The provisional result is therefore:
- **Go** for a small installed plugin probe and for Jellyfin-owned codec negotiation on one selected item.
- **No-go** for replacing the existing continuous channel path with a server-plugin-only implementation
until both provider-supplied initial offset and boundary transition semantics have a proven solution.
- **Administrator-only for the probe.** The Live TV provider contract has no user context when it resolves
the backing item, so per-library user restrictions are not yet enforced for that item.
- **Isolated-lab-only for the probe.** The Live TV provider contract has no user context when it resolves the
backing item, so the plugin cannot enforce per-library user restrictions. An "administrator-only" warning is
not an authorization control; the live probe must use a loopback-only cloned Jellyfin with no non-admin users.
- **Do not start Kodi-specific implementation yet.** Preserve the existing M3U/XMLTV path and use the
Jellyfin result to decide whether Kodi can reuse an official Jellyfin integration or needs a thin companion.
@@ -55,7 +57,8 @@ It returns:
- source channel and mirror-adjusted lookup time;
- physical playout item, start/finish, in/out points, and current in-file offset;
- the next physical transition;
- a token-free typed source reference (`JellyfinItem`, `LocalFile`, `PlexItem`, `EmbyItem`, or `RemoteUrl`).
- a typed source reference (`JellyfinItem`, `LocalFile`, `PlexItem`, `EmbyItem`, or `RemoteUrl`). Credential-bearing
remote URLs are deliberately not returned by this phase-one endpoint.
The handler depends only on the database context. It never asks the FFmpeg process or segmenter services to
start work. The endpoint is explicitly machine-key authenticated and non-cacheable because local paths may be
@@ -79,8 +82,9 @@ The checked runtime is Jellyfin Server and Web `v12.0-rc2` on .NET 10.
3. The stock web client maps a currently airing programme to its channel and starts it with position zero.
4. Jellyfin uses nonzero `StartTimeTicks` for its native FFmpeg `-ss` path, but the plugin cannot populate that
request field through the Live TV provider contract.
5. Jellyfin forces Live TV media sources to `IsInfiniteStream = true` and clears finite runtime metadata.
Guide refresh persists EPG metadata; it is not a transition scheduler for an already-open stream.
5. Jellyfin forces Live TV media sources to `IsInfiniteStream = true`. For the probe's supported non-opening
native sources, `RunTimeTicks` remains present, but neither it nor guide refresh becomes a transition scheduler
for an already-open stream.
Returning the file alone therefore proves native playback ownership but starts at the beginning. Returning a
custom continuous HTTP/HLS stream could solve position and transitions, but it would make the plugin or
@@ -119,6 +123,7 @@ never substitute the backing library item as the playback session item.
| On-demand playout clock | Deferred | Needs an explicit player-owned clock contract. |
| External JSON playout guide | Deferred | Existing JSON guide intentionally omits it. |
| Per-user backing-library authorization | Blocking gap | `ILiveTvService` source resolution has no user argument. |
| Multiple Jellyfin servers | Probe constraint | Item IDs are resolved on the Jellyfin server hosting the plugin; the phase-one contract does not yet encode server identity. |
## Live probe and evidence still required
@@ -0,0 +1,312 @@
using Jellyfin.Plugin.ChicoryTV.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace Jellyfin.Plugin.ChicoryTV.Tests;
[TestFixture]
public sealed class ErsatzTvLiveTvServiceTests
{
[Test]
public async Task OpenUsesDiscoverySnapshotWhenScheduleClockCrossesBoundary()
{
DateTimeOffset now = new(2026, 7, 14, 12, 0, 0, TimeSpan.Zero);
var fixture = new ServiceFixture(now);
Guid itemAId = Guid.NewGuid();
Guid itemBId = Guid.NewGuid();
var sourceA = new MediaSourceInfo { Id = "source-a" };
var sourceAForOpen = new MediaSourceInfo { Id = "source-a" };
var sourceB = new MediaSourceInfo { Id = "source-b" };
Movie itemA = fixture.AddItem(itemAId, sourceA);
fixture.AddItem(itemBId, sourceB);
fixture.MediaSourceManager.GetPlaybackMediaSources(
itemA,
null!,
true,
true,
Arg.Any<CancellationToken>())
.Returns(
Task.FromResult<IReadOnlyList<MediaSourceInfo>>([sourceA]),
Task.FromResult<IReadOnlyList<MediaSourceInfo>>([sourceAForOpen]));
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(
Task.FromResult(PlaybackResponse(now, itemAId)),
Task.FromResult(PlaybackResponse(now.AddSeconds(1), itemBId)));
List<MediaSourceInfo> discovered = await fixture.Service.GetChannelStreamMediaSources("1", default);
fixture.Time.Advance(TimeSpan.FromSeconds(2));
MediaSourceInfo opened = await fixture.Service.GetChannelStream("1", "source-a", default);
discovered.ShouldBe([sourceA]);
opened.ShouldBeSameAs(sourceAForOpen);
await fixture.Client.Received(1).GetPlaybackSourceAsync(
1,
Arg.Any<DateTimeOffset>(),
Arg.Any<CancellationToken>());
}
[Test]
public async Task OpenRefreshesCurrentSourceAfterDiscoverySnapshotExpires()
{
DateTimeOffset now = new(2026, 7, 14, 12, 0, 0, TimeSpan.Zero);
var fixture = new ServiceFixture(now);
Guid itemAId = Guid.NewGuid();
Guid itemBId = Guid.NewGuid();
var sourceA = new MediaSourceInfo { Id = "source-a" };
var sourceB = new MediaSourceInfo { Id = "source-b" };
fixture.AddItem(itemAId, sourceA);
fixture.AddItem(itemBId, sourceB);
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(
Task.FromResult(PlaybackResponse(now, itemAId)),
Task.FromResult(PlaybackResponse(now.AddSeconds(16), itemBId)));
await fixture.Service.GetChannelStreamMediaSources("1", default);
fixture.Time.Advance(TimeSpan.FromSeconds(16));
MediaSourceInfo opened = await fixture.Service.GetChannelStream("1", "source-b", default);
opened.ShouldBeSameAs(sourceB);
await fixture.Client.Received(1).GetPlaybackSourceAsync(
1,
now.AddSeconds(16),
Arg.Any<CancellationToken>());
await fixture.Client.Received(2).GetPlaybackSourceAsync(
1,
Arg.Any<DateTimeOffset>(),
Arg.Any<CancellationToken>());
}
[Test]
public async Task DiscoveryFiltersRequiresOpeningAndOpenSelectsRequestedStreamId()
{
DateTimeOffset now = new(2026, 7, 14, 12, 0, 0, TimeSpan.Zero);
var fixture = new ServiceFixture(now);
Guid itemId = Guid.NewGuid();
var nested = new MediaSourceInfo { Id = "nested", RequiresOpening = true };
var first = new MediaSourceInfo { Id = "first" };
var requested = new MediaSourceInfo { Id = "requested" };
fixture.AddItem(itemId, nested, first, requested);
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(PlaybackResponse(now, itemId));
List<MediaSourceInfo> discovered = await fixture.Service.GetChannelStreamMediaSources("1", default);
MediaSourceInfo opened = await fixture.Service.GetChannelStream("1", "REQUESTED", default);
discovered.ShouldBe([first, requested]);
opened.ShouldBeSameAs(requested);
await fixture.Client.Received(1).GetPlaybackSourceAsync(
1,
Arg.Any<DateTimeOffset>(),
Arg.Any<CancellationToken>());
}
[Test]
public async Task OpenWithBlankStreamIdUsesFirstDiscoveredSource()
{
var fixture = new ServiceFixture();
Guid itemId = Guid.NewGuid();
var first = new MediaSourceInfo { Id = "first" };
var second = new MediaSourceInfo { Id = "second" };
fixture.AddItem(itemId, first, second);
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(PlaybackResponse(fixture.Time.GetUtcNow(), itemId));
await fixture.Service.GetChannelStreamMediaSources("1", default);
MediaSourceInfo opened = await fixture.Service.GetChannelStream("1", string.Empty, default);
opened.ShouldBeSameAs(first);
}
[Test]
public void DiscoveryRejectsWhenEveryNativeSourceRequiresOpening()
{
var fixture = new ServiceFixture();
Guid itemId = Guid.NewGuid();
fixture.AddItem(itemId, new MediaSourceInfo { Id = "nested", RequiresOpening = true });
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(PlaybackResponse(fixture.Time.GetUtcNow(), itemId));
NotSupportedException exception = Assert.ThrowsAsync<NotSupportedException>(
() => fixture.Service.GetChannelStreamMediaSources("1", default))!;
exception.Message.ShouldContain("no native media source usable");
}
[Test]
public void DiscoveryRejectsMalformedChannelIdWithoutCallingErsatzTv()
{
var fixture = new ServiceFixture();
InvalidOperationException exception = Assert.ThrowsAsync<InvalidOperationException>(
() => fixture.Service.GetChannelStreamMediaSources("not-an-integer", default))!;
exception.Message.ShouldContain("is not an integer");
fixture.Client.DidNotReceiveWithAnyArgs().GetPlaybackSourceAsync(default, default, default);
}
[Test]
public void DiscoveryRejectsChannelWithNoActiveItem()
{
var fixture = new ServiceFixture();
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(new PlaybackSourceResponse
{
ChannelId = 1,
ResolvedAt = fixture.Time.GetUtcNow()
});
InvalidOperationException exception = Assert.ThrowsAsync<InvalidOperationException>(
() => fixture.Service.GetChannelStreamMediaSources("1", default))!;
exception.Message.ShouldContain("has no active playout item");
}
[Test]
public void DiscoveryRejectsNonJellyfinSource()
{
var fixture = new ServiceFixture();
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(PlaybackResponse(fixture.Time.GetUtcNow(), (string?)null, PlaybackSourceKind.LocalFile));
NotSupportedException exception = Assert.ThrowsAsync<NotSupportedException>(
() => fixture.Service.GetChannelStreamMediaSources("1", default))!;
exception.Message.ShouldContain("only JellyfinItem is supported");
}
[Test]
public void DiscoveryRejectsMalformedJellyfinItemId()
{
var fixture = new ServiceFixture();
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(PlaybackResponse(fixture.Time.GetUtcNow(), "not-a-guid"));
InvalidOperationException exception = Assert.ThrowsAsync<InvalidOperationException>(
() => fixture.Service.GetChannelStreamMediaSources("1", default))!;
exception.Message.ShouldContain("invalid Jellyfin item id");
}
[Test]
public void DiscoveryRejectsMissingJellyfinItem()
{
var fixture = new ServiceFixture();
Guid missingItemId = Guid.NewGuid();
fixture.Client.GetPlaybackSourceAsync(1, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
.Returns(PlaybackResponse(fixture.Time.GetUtcNow(), missingItemId));
InvalidOperationException exception = Assert.ThrowsAsync<InvalidOperationException>(
() => fixture.Service.GetChannelStreamMediaSources("1", default))!;
exception.Message.ShouldContain("was not found");
}
[Test]
public async Task UnsafeLabAcknowledgementIsOffByDefaultAndBlocksExposure()
{
var fixture = new ServiceFixture(unsafeLabAccessEnabled: false);
IEnumerable<ChannelInfo> channels = await fixture.Service.GetChannelsAsync(default);
InvalidOperationException exception = Assert.ThrowsAsync<InvalidOperationException>(
() => fixture.Service.GetChannelStreamMediaSources("1", default))!;
channels.ShouldBeEmpty();
exception.Message.ShouldContain("Explicitly acknowledge the unsafe lab setting");
await fixture.Client.DidNotReceiveWithAnyArgs().GetGuideAsync(default, default, default);
await fixture.Client.DidNotReceiveWithAnyArgs().GetPlaybackSourceAsync(default, default, default);
new PluginConfiguration().EnableUnsafeLabAccess.ShouldBeFalse();
}
private static PlaybackSourceResponse PlaybackResponse(
DateTimeOffset resolvedAt,
Guid? itemId,
PlaybackSourceKind kind = PlaybackSourceKind.JellyfinItem) =>
PlaybackResponse(resolvedAt, itemId?.ToString(), kind);
private static PlaybackSourceResponse PlaybackResponse(
DateTimeOffset resolvedAt,
string? itemId,
PlaybackSourceKind kind = PlaybackSourceKind.JellyfinItem) =>
new()
{
ChannelId = 1,
ResolvedAt = resolvedAt,
Active = new PlaybackItem
{
CurrentOffsetTicks = TimeSpan.FromMinutes(3).Ticks,
Source = new PlaybackSourceReference
{
Kind = kind,
ItemId = itemId
}
}
};
private sealed class ServiceFixture
{
public ServiceFixture(
DateTimeOffset? now = null,
bool unsafeLabAccessEnabled = true)
{
Time = new ManualTimeProvider(
now ?? new DateTimeOffset(2026, 7, 14, 12, 0, 0, TimeSpan.Zero));
Client = Substitute.For<IErsatzTvClient>();
ConfigurationAccessor = Substitute.For<IPluginConfigurationAccessor>();
LibraryManager = Substitute.For<ILibraryManager>();
MediaSourceManager = Substitute.For<IMediaSourceManager>();
ConfigurationAccessor.Configuration.Returns(new PluginConfiguration
{
EnableUnsafeLabAccess = unsafeLabAccessEnabled
});
Service = new ErsatzTvLiveTvService(
Client,
ConfigurationAccessor,
LibraryManager,
MediaSourceManager,
NullLogger<ErsatzTvLiveTvService>.Instance,
Time);
}
public IErsatzTvClient Client { get; }
public IPluginConfigurationAccessor ConfigurationAccessor { get; }
public ILibraryManager LibraryManager { get; }
public IMediaSourceManager MediaSourceManager { get; }
public ManualTimeProvider Time { get; }
public ErsatzTvLiveTvService Service { get; }
public Movie AddItem(Guid itemId, params MediaSourceInfo[] sources)
{
var item = new Movie { Id = itemId };
LibraryManager.GetItemById(itemId).Returns(item);
MediaSourceManager.GetPlaybackMediaSources(
item,
null!,
true,
true,
Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<MediaSourceInfo>>(sources));
return item;
}
}
private sealed class ManualTimeProvider(DateTimeOffset utcNow) : TimeProvider
{
private DateTimeOffset _utcNow = utcNow;
public override DateTimeOffset GetUtcNow() => _utcNow;
public void Advance(TimeSpan amount) => _utcNow = _utcNow.Add(amount);
}
}
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Jellyfin.Plugin.ChicoryTV/Jellyfin.Plugin.ChicoryTV.csproj" />
</ItemGroup>
<ItemGroup>
<!-- The plugin excludes Jellyfin runtime assets because the server supplies them.
Tests run outside Jellyfin, so they need the pinned assemblies in the test host. -->
<PackageReference Include="Jellyfin.Controller" VersionOverride="12.0.0-rc2" />
<PackageReference Include="Jellyfin.Model" VersionOverride="12.0.0-rc2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="NUnit" />
<PackageReference Include="NUnit3TestAdapter" />
<PackageReference Include="Shouldly" />
</ItemGroup>
</Project>
@@ -10,6 +10,7 @@ public sealed class PluginConfiguration : BasePluginConfiguration
{
BaseUrl = "http://localhost:8409";
ApiKey = string.Empty;
EnableUnsafeLabAccess = false;
}
/// <summary>Gets or sets the ErsatzTV server base URL.</summary>
@@ -17,4 +18,9 @@ public sealed class PluginConfiguration : BasePluginConfiguration
/// <summary>Gets or sets the ErsatzTV API key.</summary>
public string ApiKey { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the authorization-incomplete lab probe is enabled.
/// </summary>
public bool EnableUnsafeLabAccess { get; set; }
}
@@ -5,7 +5,7 @@
<title>ChicoryTV</title>
</head>
<body>
<div id="ChicoryTvConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button">
<div id="ChicoryTvConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-checkbox">
<div data-role="content">
<div class="content-primary">
<form id="ChicoryTvConfigForm">
@@ -19,6 +19,16 @@
<input id="ApiKey" name="ApiKey" type="password" is="emby-input" autocomplete="off" />
<div class="fieldDescription">Sent to ErsatzTV as X-Api-Key.</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input id="EnableUnsafeLabAccess" name="EnableUnsafeLabAccess" type="checkbox" is="emby-checkbox" />
<span>I understand this unsafe lab probe bypasses per-user backing-library authorization</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
Required to expose any ChicoryTV channels or sources. This is not administrator-role
enforcement. Do not enable it on a shared or untrusted Jellyfin deployment.
</div>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
<span>Save</span>
@@ -38,6 +48,7 @@
ApiClient.getPluginConfiguration(ChicoryTvConfig.pluginUniqueId).then(function (config) {
document.querySelector('#BaseUrl').value = config.BaseUrl || '';
document.querySelector('#ApiKey').value = config.ApiKey || '';
document.querySelector('#EnableUnsafeLabAccess').checked = config.EnableUnsafeLabAccess === true;
Dashboard.hideLoadingMsg();
});
});
@@ -48,6 +59,7 @@
ApiClient.getPluginConfiguration(ChicoryTvConfig.pluginUniqueId).then(function (config) {
config.BaseUrl = document.querySelector('#BaseUrl').value.trim();
config.ApiKey = document.querySelector('#ApiKey').value.trim();
config.EnableUnsafeLabAccess = document.querySelector('#EnableUnsafeLabAccess').checked;
ApiClient.updatePluginConfiguration(ChicoryTvConfig.pluginUniqueId, config).then(function (result) {
Dashboard.processPluginConfigurationUpdateResult(result);
});
@@ -4,7 +4,7 @@ using System.Text.Json;
namespace Jellyfin.Plugin.ChicoryTV;
internal sealed class ErsatzTvClient : IDisposable
internal sealed class ErsatzTvClient : IErsatzTvClient, IDisposable
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
@@ -13,11 +13,17 @@ internal sealed class ErsatzTvClient : IDisposable
private readonly HttpClient _httpClient = new();
private readonly SemaphoreSlim _guideLock = new(1, 1);
private readonly IPluginConfigurationAccessor _configurationAccessor;
private readonly TimeProvider _timeProvider;
private GuideResponse? _cachedGuide;
private DateTimeOffset _cachedGuideExpiresAt;
public ErsatzTvClient()
public ErsatzTvClient(
IPluginConfigurationAccessor configurationAccessor,
TimeProvider timeProvider)
{
_configurationAccessor = configurationAccessor;
_timeProvider = timeProvider;
}
public async Task<GuideResponse> GetGuideAsync(
@@ -36,7 +42,7 @@ internal sealed class ErsatzTvClient : IDisposable
GuideResponse guide = await GetGuideCoreAsync(start, end, cancellationToken).ConfigureAwait(false);
_cachedGuide = guide;
_cachedGuideExpiresAt = DateTimeOffset.UtcNow.AddSeconds(30);
_cachedGuideExpiresAt = _timeProvider.GetUtcNow().AddSeconds(30);
return guide;
}
finally
@@ -67,7 +73,7 @@ internal sealed class ErsatzTvClient : IDisposable
private GuideResponse? GetCachedGuide(DateTimeOffset? start, DateTimeOffset? end)
{
GuideResponse? cached = _cachedGuide;
if (cached is null || DateTimeOffset.UtcNow >= _cachedGuideExpiresAt)
if (cached is null || _timeProvider.GetUtcNow() >= _cachedGuideExpiresAt)
{
return null;
}
@@ -97,7 +103,7 @@ internal sealed class ErsatzTvClient : IDisposable
private async Task<T> GetAsync<T>(string relativePath, CancellationToken cancellationToken)
{
var configuration = Plugin.Instance?.Configuration
var configuration = _configurationAccessor.Configuration
?? throw new InvalidOperationException("The ChicoryTV plugin has not been initialized.");
string configuredBaseUrl = configuration.BaseUrl?.Trim() ?? string.Empty;
if (!Uri.TryCreate(configuredBaseUrl.TrimEnd('/') + "/", UriKind.Absolute, out Uri? baseUri)
@@ -93,7 +93,5 @@ public sealed class PlaybackSourceReference
public string? Path { get; set; }
public string? Url { get; set; }
public bool IsLive { get; set; }
}
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Globalization;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
@@ -10,22 +11,34 @@ namespace Jellyfin.Plugin.ChicoryTV;
internal sealed class ErsatzTvLiveTvService : ILiveTvService
{
private const string ReadOnlyMessage = "ChicoryTV is a read-only Live TV probe and does not support timers.";
private const string UnsafeLabAccessMessage =
"ChicoryTV is disabled. Explicitly acknowledge the unsafe lab setting before exposing channels. " +
"This probe cannot enforce per-user access to backing Jellyfin library items.";
private static readonly TimeSpan DiscoverySnapshotLifetime = TimeSpan.FromSeconds(15);
private readonly ErsatzTvClient _client;
private readonly IErsatzTvClient _client;
private readonly IPluginConfigurationAccessor _configurationAccessor;
private readonly ILibraryManager _libraryManager;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly ILogger<ErsatzTvLiveTvService> _logger;
private readonly TimeProvider _timeProvider;
private readonly ConcurrentDictionary<int, DiscoverySnapshot> _discoverySnapshots = new();
private int _disabledWarningLogged;
public ErsatzTvLiveTvService(
ErsatzTvClient client,
IErsatzTvClient client,
IPluginConfigurationAccessor configurationAccessor,
ILibraryManager libraryManager,
IMediaSourceManager mediaSourceManager,
ILogger<ErsatzTvLiveTvService> logger)
ILogger<ErsatzTvLiveTvService> logger,
TimeProvider timeProvider)
{
_client = client;
_configurationAccessor = configurationAccessor;
_libraryManager = libraryManager;
_mediaSourceManager = mediaSourceManager;
_logger = logger;
_timeProvider = timeProvider;
}
public string Name => "ChicoryTV";
@@ -34,6 +47,12 @@ internal sealed class ErsatzTvLiveTvService : ILiveTvService
public async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
{
if (!IsUnsafeLabAccessEnabled())
{
LogDisabledOnce();
return Array.Empty<ChannelInfo>();
}
GuideResponse guide = await _client.GetGuideAsync(null, null, cancellationToken).ConfigureAwait(false);
return guide.Channels.Select(channel => new ChannelInfo
{
@@ -50,6 +69,12 @@ internal sealed class ErsatzTvLiveTvService : ILiveTvService
DateTime endDateUtc,
CancellationToken cancellationToken)
{
if (!IsUnsafeLabAccessEnabled())
{
LogDisabledOnce();
return Array.Empty<ProgramInfo>();
}
if (!int.TryParse(channelId, NumberStyles.None, CultureInfo.InvariantCulture, out int parsedChannelId))
{
return Array.Empty<ProgramInfo>();
@@ -85,11 +110,19 @@ internal sealed class ErsatzTvLiveTvService : ILiveTvService
string channelId,
CancellationToken cancellationToken)
{
EnsureUnsafeLabAccessEnabled();
int parsedChannelId = ParseChannelId(channelId);
ResolvedMediaSources resolved = await ResolveMediaSourcesAsync(
channelId,
"resolving",
parsedChannelId,
cancellationToken).ConfigureAwait(false);
return resolved.Sources;
_discoverySnapshots[parsedChannelId] = new DiscoverySnapshot(
resolved.ChannelId,
resolved.JellyfinItemId,
resolved.JellyfinItemGuid,
resolved.CurrentOffsetTicks,
resolved.ExpiresAt);
LogResolution("discovering", resolved, usesDiscoverySnapshot: false);
return [.. resolved.Sources];
}
public async Task<MediaSourceInfo> GetChannelStream(
@@ -97,17 +130,55 @@ internal sealed class ErsatzTvLiveTvService : ILiveTvService
string streamId,
CancellationToken cancellationToken)
{
ResolvedMediaSources resolved = await ResolveMediaSourcesAsync(
channelId,
"opening",
cancellationToken).ConfigureAwait(false);
EnsureUnsafeLabAccessEnabled();
int parsedChannelId = ParseChannelId(channelId);
DateTimeOffset now = _timeProvider.GetUtcNow();
ResolvedMediaSources resolved;
bool usesDiscoverySnapshot;
if (_discoverySnapshots.TryGetValue(parsedChannelId, out DiscoverySnapshot? cached)
&& cached is not null
&& now < cached.ExpiresAt)
{
List<MediaSourceInfo> sources = await GetNativeMediaSourcesAsync(
cached.ChannelId,
cached.JellyfinItemId,
cached.JellyfinItemGuid,
cancellationToken).ConfigureAwait(false);
resolved = new ResolvedMediaSources(
cached.ChannelId,
cached.JellyfinItemId,
cached.JellyfinItemGuid,
cached.CurrentOffsetTicks,
sources,
cached.ExpiresAt);
usesDiscoverySnapshot = true;
}
else
{
resolved = await ResolveMediaSourcesAsync(
parsedChannelId,
cancellationToken).ConfigureAwait(false);
_discoverySnapshots[parsedChannelId] = new DiscoverySnapshot(
resolved.ChannelId,
resolved.JellyfinItemId,
resolved.JellyfinItemGuid,
resolved.CurrentOffsetTicks,
resolved.ExpiresAt);
usesDiscoverySnapshot = false;
}
MediaSourceInfo? source = string.IsNullOrWhiteSpace(streamId)
? resolved.Sources.FirstOrDefault()
: resolved.Sources.FirstOrDefault(
candidate => string.Equals(candidate.Id, streamId, StringComparison.OrdinalIgnoreCase));
return source
?? throw new InvalidOperationException(
if (source is null)
{
throw new InvalidOperationException(
$"Jellyfin media source '{streamId}' is no longer available for ErsatzTV channel {channelId}.");
}
LogResolution("opening", resolved, usesDiscoverySnapshot);
return source;
}
public Task CloseLiveStream(string id, CancellationToken cancellationToken) => Task.CompletedTask;
@@ -140,19 +211,24 @@ internal sealed class ErsatzTvLiveTvService : ILiveTvService
private static Task<T> NotSupported<T>() => Task.FromException<T>(new NotSupportedException(ReadOnlyMessage));
private async Task<ResolvedMediaSources> ResolveMediaSourcesAsync(
string channelId,
string operation,
CancellationToken cancellationToken)
private static int ParseChannelId(string channelId)
{
if (!int.TryParse(channelId, NumberStyles.None, CultureInfo.InvariantCulture, out int parsedChannelId))
{
throw new InvalidOperationException($"ErsatzTV channel id '{channelId}' is not an integer.");
}
return parsedChannelId;
}
private async Task<ResolvedMediaSources> ResolveMediaSourcesAsync(
int channelId,
CancellationToken cancellationToken)
{
DateTimeOffset resolvedAt = _timeProvider.GetUtcNow();
PlaybackSourceResponse response = await _client.GetPlaybackSourceAsync(
parsedChannelId,
DateTimeOffset.UtcNow,
channelId,
resolvedAt,
cancellationToken).ConfigureAwait(false);
PlaybackItem active = response.Active
?? throw new InvalidOperationException(
@@ -169,9 +245,30 @@ internal sealed class ErsatzTvLiveTvService : ILiveTvService
$"ErsatzTV returned invalid Jellyfin item id '{active.Source.ItemId}' for channel {channelId}.");
}
var item = _libraryManager.GetItemById(jellyfinItemId)
List<MediaSourceInfo> sources = await GetNativeMediaSourcesAsync(
channelId,
active.Source.ItemId,
jellyfinItemId,
cancellationToken).ConfigureAwait(false);
return new ResolvedMediaSources(
response.ChannelId,
active.Source.ItemId,
jellyfinItemId,
active.CurrentOffsetTicks,
sources,
_timeProvider.GetUtcNow().Add(DiscoverySnapshotLifetime));
}
private async Task<List<MediaSourceInfo>> GetNativeMediaSourcesAsync(
int channelId,
string jellyfinItemId,
Guid jellyfinItemGuid,
CancellationToken cancellationToken)
{
var item = _libraryManager.GetItemById(jellyfinItemGuid)
?? throw new InvalidOperationException(
$"Jellyfin library item {active.Source.ItemId} referenced by ErsatzTV channel {channelId} was not found.");
$"Jellyfin library item {jellyfinItemId} referenced by ErsatzTV channel {channelId} was not found.");
IReadOnlyList<MediaSourceInfo> nativeSources = await _mediaSourceManager.GetPlaybackMediaSources(
item,
null,
@@ -189,19 +286,68 @@ internal sealed class ErsatzTvLiveTvService : ILiveTvService
if (sources.Count == 0)
{
throw new NotSupportedException(
$"Jellyfin item {active.Source.ItemId} has no native media source usable without dynamic opening.");
$"Jellyfin item {jellyfinItemId} has no native media source usable without dynamic opening.");
}
_logger.LogInformation(
"ChicoryTV {Operation} ErsatzTV channel {ChannelId} as Jellyfin item {JellyfinItemId}; " +
"schedule-derived CurrentOffsetTicks={CurrentOffsetTicks}. ILiveTvService has no playback-offset parameter.",
operation,
response.ChannelId,
active.Source.ItemId,
active.CurrentOffsetTicks);
return new ResolvedMediaSources(sources);
return sources;
}
private sealed record ResolvedMediaSources(List<MediaSourceInfo> Sources);
private bool IsUnsafeLabAccessEnabled()
{
bool enabled = _configurationAccessor.Configuration?.EnableUnsafeLabAccess == true;
if (!enabled)
{
_discoverySnapshots.Clear();
}
return enabled;
}
private void EnsureUnsafeLabAccessEnabled()
{
if (!IsUnsafeLabAccessEnabled())
{
LogDisabledOnce();
throw new InvalidOperationException(UnsafeLabAccessMessage);
}
}
private void LogDisabledOnce()
{
if (Interlocked.Exchange(ref _disabledWarningLogged, 1) == 0)
{
_logger.LogWarning("{Message}", UnsafeLabAccessMessage);
}
}
private void LogResolution(
string operation,
ResolvedMediaSources resolved,
bool usesDiscoverySnapshot)
{
_logger.LogInformation(
"ChicoryTV {Operation} ErsatzTV channel {ChannelId} as Jellyfin item {JellyfinItemId}; " +
"schedule-derived CurrentOffsetTicks={CurrentOffsetTicks}. " +
"UsedDiscoverySnapshot={UsedDiscoverySnapshot}. ILiveTvService has no playback-offset parameter.",
operation,
resolved.ChannelId,
resolved.JellyfinItemId,
resolved.CurrentOffsetTicks,
usesDiscoverySnapshot);
}
private sealed record ResolvedMediaSources(
int ChannelId,
string JellyfinItemId,
Guid JellyfinItemGuid,
long CurrentOffsetTicks,
List<MediaSourceInfo> Sources,
DateTimeOffset ExpiresAt);
private sealed record DiscoverySnapshot(
int ChannelId,
string JellyfinItemId,
Guid JellyfinItemGuid,
long CurrentOffsetTicks,
DateTimeOffset ExpiresAt);
}
@@ -0,0 +1,17 @@
namespace Jellyfin.Plugin.ChicoryTV;
/// <summary>Reads the guide and schedule-derived playback source from ErsatzTV.</summary>
public interface IErsatzTvClient
{
/// <summary>Gets a guide window.</summary>
Task<GuideResponse> GetGuideAsync(
DateTimeOffset? start,
DateTimeOffset? end,
CancellationToken cancellationToken);
/// <summary>Gets the source scheduled on a channel at a point in time.</summary>
Task<PlaybackSourceResponse> GetPlaybackSourceAsync(
int channelId,
DateTimeOffset at,
CancellationToken cancellationToken);
}
@@ -24,4 +24,10 @@
<EmbeddedResource Include="Configuration/configPage.html" />
</ItemGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>Jellyfin.Plugin.ChicoryTV.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
</Project>
@@ -0,0 +1,15 @@
using Jellyfin.Plugin.ChicoryTV.Configuration;
namespace Jellyfin.Plugin.ChicoryTV;
/// <summary>Provides the current persisted plugin configuration.</summary>
public interface IPluginConfigurationAccessor
{
/// <summary>Gets the current configuration, if the plugin has initialized.</summary>
PluginConfiguration? Configuration { get; }
}
internal sealed class PluginConfigurationAccessor : IPluginConfigurationAccessor
{
public PluginConfiguration? Configuration => Plugin.Instance?.Configuration;
}
@@ -4,14 +4,17 @@ This standalone, read-only plugin proves the narrow Jellyfin-owned playback path
## Build and install
The project deliberately is not part of `ErsatzTV.sln`. It targets `net10.0` and pins both `Jellyfin.Controller` and `Jellyfin.Model` to exactly `12.0.0-rc2`, excluding their runtime assets as the official plugin template does.
The plugin and its focused test project are part of `ErsatzTV.sln`, so the normal build catches provider-contract regressions. The plugin targets `net10.0` and pins both `Jellyfin.Controller` and `Jellyfin.Model` to exactly `12.0.0-rc2`, excluding their runtime assets as the official plugin template does.
```shell
dotnet build integrations/jellyfin/Jellyfin.Plugin.ChicoryTV/Jellyfin.Plugin.ChicoryTV.csproj
dotnet test integrations/jellyfin/Jellyfin.Plugin.ChicoryTV.Tests/Jellyfin.Plugin.ChicoryTV.Tests.csproj
```
Copy `bin/Debug/net10.0/Jellyfin.Plugin.ChicoryTV.dll` (and the PDB when debugging) into its own directory below Jellyfin's plugins directory, then restart Jellyfin. In Dashboard > Plugins > ChicoryTV, configure the ErsatzTV base URL and API key. Refresh Jellyfin's Live TV guide after changing the connection.
The plugin is inert by default. To expose channels, the configuration page also requires an explicit acknowledgement that this unsafe lab probe cannot enforce per-user access to the backing Jellyfin items. The acknowledgement is only an opt-in flag; it is **not** an administrator-role check or any other authorization enforcement. Do not enable the probe on a shared or untrusted Jellyfin deployment.
The ErsatzTV side must provide:
- `GET /api/v1/guide`, with `Start`, `End`, and `Channels`; each channel has `Id`, `Number`, `Name`, and `Programmes`.
@@ -22,7 +25,9 @@ The ErsatzTV side must provide:
- Only `Source.Kind == JellyfinItem` is accepted. Local files, URLs, Plex, Emby, and unknown kinds fail explicitly; there is no proxy or ErsatzTV transcode fallback.
- Native sources that require a nested dynamic-open operation are omitted. This first probe is for directly usable native Jellyfin library media sources.
- `ILiveTvService` source resolution has no user parameter. This probe performs a non-user-aware library lookup, so administrators must not treat Live TV channel access as authorization for otherwise restricted backing items.
- The unsafe-lab acknowledgement is off by default. While it is off, the service returns no channels or programmes and refuses source discovery/open calls. Enabling it does not repair the authorization gap.
- Jellyfin requests guide programmes per channel; the plugin reuses a matching guide response for 30 seconds to avoid rebuilding the complete ErsatzTV guide for every channel in one refresh.
- Source discovery keeps only the resolved schedule identity per channel for 15 seconds and rehydrates fresh native media-source objects on open. An immediately following open therefore selects the same scheduled item even if the schedule clock crosses a boundary between the two calls, without sharing Jellyfin's mutable source objects across requests. After expiration, open resolves the current item again. This handshake grace does not retune a running stream or implement schedule transitions.
- Jellyfin normalizes non-default Live TV sources as infinite/interlaced-capable and enables transcoding. Those stock-server mutations can affect negotiation even though the source metadata originates from the native library item.
- The schedule-derived `CurrentOffsetTicks` is logged when resolving/opening, but it is not applied. The exact stock Jellyfin client sends `StartTimeTicks=0`, and `ILiveTvService` has no offset parameter. This probe makes no claim that Jellyfin consumes the logged offset.
- A finite library file reaching EOF does not retune the channel. There is no continuous stream or transition engine.
@@ -11,7 +11,9 @@ public sealed class ServiceRegistrator : IPluginServiceRegistrator
/// <inheritdoc />
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
{
serviceCollection.AddSingleton<ErsatzTvClient>();
serviceCollection.AddSingleton(TimeProvider.System);
serviceCollection.AddSingleton<IPluginConfigurationAccessor, PluginConfigurationAccessor>();
serviceCollection.AddSingleton<IErsatzTvClient, ErsatzTvClient>();
serviceCollection.AddSingleton<ILiveTvService, ErsatzTvLiveTvService>();
}
}
-1
View File
@@ -215,7 +215,6 @@ export interface components {
"kind": components["schemas"]["ChannelPlaybackSourceKind"];
"itemId": null | string;
"path": null | string;
"url": null | string;
"isLive": boolean;
};
"ChannelPlaybackSourceResponseModel": {