feat(60): in-browser channel preview on the channels list #551

Merged
timothy merged 17 commits from feat/60-channel-preview into main 2026-07-22 00:29:36 +02:00
28 changed files with 2446 additions and 16 deletions
+70 -2
View File
@@ -96,7 +96,10 @@ internal static class Mapper
channel.ShowInEpg);
}
internal static ChannelResponseModel ProjectToResponseModel(Channel channel, int playoutCount) =>
internal static ChannelResponseModel ProjectToResponseModel(
Channel channel,
int playoutCount,
bool iptvJwtEnabled) =>
new(
channel.Id,
channel.Number,
@@ -110,7 +113,8 @@ internal static class Mapper
channel.IsEnabled,
channel.ShowInEpg,
playoutCount,
GetLogoUrl(channel));
GetLogoUrl(channel),
GetPreview(channel.StreamingMode, channel.Number, iptvJwtEnabled, channel.IsEnabled, playoutCount));
internal static ResolutionViewModel ProjectToViewModel(Resolution resolution) =>
new(resolution.Height, resolution.Width);
@@ -174,4 +178,68 @@ internal static class Mapper
StreamingMode.HttpLiveStreamingSegmenter => "HLS Segmenter",
_ => throw new ArgumentOutOfRangeException(nameof(channel))
};
#nullable enable
internal static ChannelPreviewResponseModel GetPreview(
StreamingMode streamingMode,
string channelNumber,
bool iptvJwtEnabled,
bool isEnabled,
int playoutCount)
{
// Precedence among the three Unavailable causes (checked in this order; the first match wins):
// 1. JWT enabled — a host-wide auth configuration; nothing the operator can fix per-channel.
// 2. channel disabled — an explicit operator choice; IptvController 404s a disabled channel, so
// preview must not even try.
// 3. no playout — the channel could theoretically play once scheduled, but a manifest
// request against it blocks indefinitely today; catch it before that happens.
//
// /iptv/* is gated by ConditionalIptvAuthorizeFilter only when JWT is configured, and the
// "jwt" scheme does not accept the SPA's ctv-session cookie. Nothing mints a JWT for the
// SPA today, so preview cannot run at all in that configuration.
if (iptvJwtEnabled)
{
return new ChannelPreviewResponseModel(
ChannelPreviewAvailability.Unavailable,
null,
"IPTV JWT authentication is enabled");
}
if (!isEnabled)
{
return new ChannelPreviewResponseModel(
ChannelPreviewAvailability.Unavailable,
null,
"Channel is disabled");
}
if (playoutCount == 0)
{
return new ChannelPreviewResponseModel(
ChannelPreviewAvailability.Unavailable,
null,
"Channel has no playout");
}
return streamingMode switch
{
StreamingMode.HttpLiveStreamingSegmenter or StreamingMode.HttpLiveStreamingDirect =>
new ChannelPreviewResponseModel(
ChannelPreviewAvailability.Available,
$"/iptv/channel/{channelNumber}.m3u8",
null),
// A browser cannot play video/mp2t. Forcing ?mode=segmenter yields a playable stream,
// but one that does not exercise the channel's configured Transport Stream pipeline —
// the SPA labels this result accordingly.
StreamingMode.TransportStream or StreamingMode.TransportStreamHybrid =>
new ChannelPreviewResponseModel(
ChannelPreviewAvailability.ForcedHlsOnly,
$"/iptv/channel/{channelNumber}.m3u8?mode=segmenter",
null),
_ => throw new ArgumentOutOfRangeException(nameof(streamingMode))
};
}
#nullable restore
}
@@ -1,5 +1,5 @@
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Api.Channels;
namespace ErsatzTV.Application.Channels;
public record GetAllChannelsForApi : IRequest<List<ChannelResponseModel>>;
public record GetAllChannelsForApi(bool IptvJwtEnabled) : IRequest<List<ChannelResponseModel>>;
@@ -13,6 +13,6 @@ public class GetAllChannelsForApiHandler(IChannelRepository channelRepository)
CancellationToken cancellationToken)
{
IEnumerable<Channel> channels = Optional(await channelRepository.GetAll(cancellationToken)).Flatten();
return channels.Map(c => ProjectToResponseModel(c, GetPlayoutsCount(c))).ToList();
return channels.Map(c => ProjectToResponseModel(c, GetPlayoutsCount(c), request.IptvJwtEnabled)).ToList();
}
}
@@ -0,0 +1,32 @@
#nullable enable
namespace ErsatzTV.Core.Api.Channels;
/// <summary>Server-declared browser-preview capability for a channel.</summary>
/// <remarks>
/// The SPA renders and acts on this; it never derives preview eligibility itself (see
/// docs/decisions.md, api.healthcheck-remediation-dto for the same pattern). Deriving it in the
/// SPA would mean keying behavior off the human-readable StreamingMode label.
/// </remarks>
public record ChannelPreviewResponseModel(
// One of ChannelPreviewAvailability's values. A plain string (not a C# enum), which keeps the
// OpenAPI schema simple, but the tradeoff is that the generated TypeScript types this as a bare
// `string`, not a literal union — the SPA hand-maintains its own `ChannelPreviewAvailability`
// union (web/src/api/channels.ts) and narrows against it, rather than getting one for free.
string Availability,
// Rooted, directly-usable HLS manifest URL; null when Availability is Unavailable.
string? ManifestUrl,
// Human-readable reason; non-null only when Availability is Unavailable.
string? UnavailableReason);
public static class ChannelPreviewAvailability
{
/// <summary>The channel's configured mode is browser-playable; preview exercises the real pipeline.</summary>
public const string Available = "Available";
/// <summary>Configured for Transport Stream; preview must force an HLS session and is content-only.</summary>
public const string ForcedHlsOnly = "ForcedHlsOnly";
/// <summary>Preview cannot run at all (IPTV JWT auth is enabled and the SPA cannot mint a token).</summary>
public const string Unavailable = "Unavailable";
}
@@ -19,4 +19,6 @@ public record ChannelResponseModel(
int PlayoutCount,
// Rooted, directly-usable logo URL for the SPA's <img src>; null when the channel has no logo
// (SPA then renders the generated initials fallback). See ErsatzTV.Application Channels.Mapper.GetLogoUrl.
string? Logo);
string? Logo,
// Server-declared browser-preview capability; see ChannelPreviewResponseModel.
ChannelPreviewResponseModel Preview);
@@ -0,0 +1,126 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Application.Channels;
[TestFixture]
public class ChannelPreviewTests
{
[TestCase(StreamingMode.HttpLiveStreamingSegmenter)]
[TestCase(StreamingMode.HttpLiveStreamingDirect)]
public void HlsModes_Are_Available_With_Plain_Manifest_Url(StreamingMode mode)
{
ChannelPreviewResponseModel result =
Mapper.GetPreview(mode, "12.1", iptvJwtEnabled: false, isEnabled: true, playoutCount: 1);
result.Availability.ShouldBe("Available");
result.ManifestUrl.ShouldBe("/iptv/channel/12.1.m3u8");
result.UnavailableReason.ShouldBeNull();
}
[TestCase(StreamingMode.TransportStream)]
[TestCase(StreamingMode.TransportStreamHybrid)]
public void TransportStream_Modes_Are_ForcedHlsOnly(StreamingMode mode)
{
ChannelPreviewResponseModel result =
Mapper.GetPreview(mode, "12.1", iptvJwtEnabled: false, isEnabled: true, playoutCount: 1);
result.Availability.ShouldBe("ForcedHlsOnly");
result.ManifestUrl.ShouldBe("/iptv/channel/12.1.m3u8?mode=segmenter");
result.UnavailableReason.ShouldBeNull();
}
[TestCase(StreamingMode.HttpLiveStreamingSegmenter)]
[TestCase(StreamingMode.HttpLiveStreamingDirect)]
[TestCase(StreamingMode.TransportStream)]
[TestCase(StreamingMode.TransportStreamHybrid)]
public void Jwt_Enabled_Makes_Every_Mode_Unavailable(StreamingMode mode)
{
ChannelPreviewResponseModel result =
Mapper.GetPreview(mode, "12.1", iptvJwtEnabled: true, isEnabled: true, playoutCount: 1);
result.Availability.ShouldBe("Unavailable");
result.ManifestUrl.ShouldBeNull();
result.UnavailableReason.ShouldBe("IPTV JWT authentication is enabled");
}
[Test]
public void Disabled_Channel_Is_Unavailable()
{
ChannelPreviewResponseModel result = Mapper.GetPreview(
StreamingMode.HttpLiveStreamingSegmenter,
"12.1",
iptvJwtEnabled: false,
isEnabled: false,
playoutCount: 1);
result.Availability.ShouldBe("Unavailable");
result.ManifestUrl.ShouldBeNull();
result.UnavailableReason.ShouldBe("Channel is disabled");
}
[Test]
public void Zero_Playout_Count_Is_Unavailable()
{
ChannelPreviewResponseModel result = Mapper.GetPreview(
StreamingMode.HttpLiveStreamingSegmenter,
"12.1",
iptvJwtEnabled: false,
isEnabled: true,
playoutCount: 0);
result.Availability.ShouldBe("Unavailable");
result.ManifestUrl.ShouldBeNull();
result.UnavailableReason.ShouldBe("Channel has no playout");
}
[Test]
public void Jwt_Enabled_Takes_Precedence_Over_Disabled_Channel()
{
// Both causes are true at once: JWT enabled (checked first) must win over the channel being
// disabled (checked second), per the precedence order documented on GetPreview.
ChannelPreviewResponseModel result = Mapper.GetPreview(
StreamingMode.HttpLiveStreamingSegmenter,
"12.1",
iptvJwtEnabled: true,
isEnabled: false,
playoutCount: 0);
result.Availability.ShouldBe("Unavailable");
result.ManifestUrl.ShouldBeNull();
result.UnavailableReason.ShouldBe("IPTV JWT authentication is enabled");
}
[Test]
public void Disabled_Channel_Takes_Precedence_Over_Zero_Playout_Count()
{
// Both causes are true at once: channel disabled (checked second) must win over zero
// playouts (checked third), per the precedence order documented on GetPreview.
ChannelPreviewResponseModel result = Mapper.GetPreview(
StreamingMode.HttpLiveStreamingSegmenter,
"12.1",
iptvJwtEnabled: false,
isEnabled: false,
playoutCount: 0);
result.Availability.ShouldBe("Unavailable");
result.ManifestUrl.ShouldBeNull();
result.UnavailableReason.ShouldBe("Channel is disabled");
}
[Test]
public void Channel_Number_Is_Used_Verbatim_In_The_Manifest_Url()
{
ChannelPreviewResponseModel result = Mapper.GetPreview(
StreamingMode.HttpLiveStreamingSegmenter,
"7",
iptvJwtEnabled: false,
isEnabled: true,
playoutCount: 1);
result.ManifestUrl.ShouldBe("/iptv/channel/7.m3u8");
}
}
@@ -35,7 +35,9 @@ public class GetAllChannelsForApiHandlerTests
]);
var handler = new GetAllChannelsForApiHandler(repository);
List<ChannelResponseModel> result = await handler.Handle(new GetAllChannelsForApi(), CancellationToken.None);
List<ChannelResponseModel> result = await handler.Handle(
new GetAllChannelsForApi(IptvJwtEnabled: false),
CancellationToken.None);
ChannelResponseModel channel = result.ShouldHaveSingleItem();
channel.Id.ShouldBe(7);
@@ -61,7 +63,9 @@ public class GetAllChannelsForApiHandlerTests
.Returns([NewChannel(new Artwork { ArtworkKind = ArtworkKind.Logo, Path = "abc123.png" })]);
var handler = new GetAllChannelsForApiHandler(repository);
List<ChannelResponseModel> result = await handler.Handle(new GetAllChannelsForApi(), CancellationToken.None);
List<ChannelResponseModel> result = await handler.Handle(
new GetAllChannelsForApi(IptvJwtEnabled: false),
CancellationToken.None);
// Uploaded logos are addressed as "iptv/logos/{file}"; the browse DTO roots it (leading slash) so
// the SPA's <img src> resolves against the site root regardless of the current SPA route.
@@ -76,7 +80,9 @@ public class GetAllChannelsForApiHandlerTests
.Returns([NewChannel(new Artwork { ArtworkKind = ArtworkKind.Logo, Path = "https://example.com/logo.png" })]);
var handler = new GetAllChannelsForApiHandler(repository);
List<ChannelResponseModel> result = await handler.Handle(new GetAllChannelsForApi(), CancellationToken.None);
List<ChannelResponseModel> result = await handler.Handle(
new GetAllChannelsForApi(IptvJwtEnabled: false),
CancellationToken.None);
// An absolute external URL is directly usable and must pass through unchanged (no leading slash added).
result.ShouldHaveSingleItem().Logo.ShouldBe("https://example.com/logo.png");
@@ -1,7 +1,9 @@
using System.Text.Json;
using ErsatzTV.Application.Channels;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Api.MediaItems;
using ErsatzTV.Core.Api.Settings;
using ErsatzTV.Core.Domain;
using ErsatzTV.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
@@ -153,7 +155,8 @@ public class OpenApiSerializerContractTests
true,
true,
2,
"/iptv/logos/logo.png");
"/iptv/logos/logo.png",
Mapper.GetPreview(StreamingMode.HttpLiveStreamingSegmenter, "1", false, true, 2));
private static string FindOpenApiDocument()
{
@@ -26,7 +26,8 @@ public class ChannelController(
{
[HttpGet("/api/v1/channels")]
[EndpointGroupName("general")]
public async Task<List<ChannelResponseModel>> GetAll() => await mediator.Send(new GetAllChannelsForApi());
public async Task<List<ChannelResponseModel>> GetAll() =>
await mediator.Send(new GetAllChannelsForApi(JwtHelper.IsEnabled));
[HttpGet("/api/v1/channels/state")]
[Tags("Channels")]
+30 -1
View File
@@ -23895,6 +23895,31 @@
],
"type": "string"
},
"ChannelPreviewResponseModel": {
"required": [
"availability",
"manifestUrl",
"unavailableReason"
],
"type": "object",
"properties": {
"availability": {
"type": "string"
},
"manifestUrl": {
"type": [
"null",
"string"
]
},
"unavailableReason": {
"type": [
"null",
"string"
]
}
}
},
"ChannelResponseModel": {
"required": [
"id",
@@ -23909,7 +23934,8 @@
"isEnabled",
"showInEpg",
"playoutCount",
"logo"
"logo",
"preview"
],
"type": "object",
"properties": {
@@ -23957,6 +23983,9 @@
"null",
"string"
]
},
"preview": {
"$ref": "#/components/schemas/ChannelPreviewResponseModel"
}
}
},
+5
View File
@@ -85,6 +85,11 @@ Exemplars:
(`record NamedIdResponseModel(int Id, string Name)`) when a response DTO needs to embed a list of
named references (e.g. a schedule item's `watermarks` / `graphicsElements`) rather than minting a
one-off `(int, string)` record per domain.
- **Server-declared capability fields.** When the SPA must decide whether an action is possible,
the server declares it as structured metadata on the response DTO (`{Availability, ...}`) rather
than the SPA inferring it from a display string. Examples: health-check remediation
(`api.healthcheck-remediation-dto`) and channel preview capability
(`ChannelPreviewResponseModel`).
- **Flatten polymorphic VMs for the wire**: when an Application ViewModel is an abstract/polymorphic
record (subtypes carrying extra fields), the OpenAPI schema only captures the base shape — promote
every subtype field to a nullable top-level member on a flat response DTO and pattern-match the
+1
View File
@@ -193,6 +193,7 @@ redirect (nothing to redirect *from*). Recorded here so the parity tracker is co
| SPA route | Screen | Notes |
|---|---|---|
| `/app/auto-tune` | `AutoTuneScreen` | **Net-new (#69).** Auto-Tune wizard: bulk-generate channels from library metadata (axes: TV Shows / TV Genres / Movie Genres) → preview & select → bulk-create, over the PR1 `POST /api/v1/channels/auto-tune/preview` + `POST /api/v1/channels/auto-tune` endpoints. Additive/non-destructive; no Blazor equivalent. Per-channel DetailPanel deferred to #383. |
| `/app/channels` (Play button) | `ChannelPreviewPanel` | **Net-new (#60).** In-browser channel preview: the channels-list Play button opens a `SlideOver` HLS player driven by the server-declared `Preview` field on `ChannelResponseModel` (`Available` / `ForcedHlsOnly` / `Unavailable`) — not derived client-side. HLS-mode channels preview directly; Transport Stream channels require an explicit opt-in and always show a caveat that the check does not exercise the channel's configured pipeline; JWT-enabled deployments show `Unavailable` (`/iptv/*` doesn't accept the SPA's session cookie). No Blazor predecessor — this is an addition, not a parity item. See `docs/decisions.md` → `api.channel-preview-capability`. |
## Section 3 — BLAZOR-ONLY (blocking issues)
+29
View File
@@ -3441,3 +3441,32 @@ leaving the shared tree dirty is the one outcome that would make this script a n
**The enum lives in `ErsatzTV.Core`, not the Application command, on purpose.** The OpenAPI string-enum pass (`Startup.UseStringEnumSchemas`) scans the Core assembly wholesale; an enum defined in `ErsatzTV.Application` renders as a bare `integer` in the spec while every sibling advanced-options enum (`PlaybackOrder`, `ChannelSubtitleMode`, …) is a string enum. Placing `CreateChannelFromLineupClearField` in `ErsatzTV.Core/Api/Channels/` makes the wire contract a string enum by construction, matching its siblings.
**SPA is id-fields-first; the API is complete ahead of the UI.** The Channel Builder + Auto-Tune DetailPanel re-add a real "None" option to the five id selects (watermark + fillers) — the pickers #89 had degraded to "Inherit"-only — routed through a `CLEAR` overrides sentinel folded into `advanced.clear` at request-build time (`applyOverridesToRequest`, so the sentinel never leaks as a field value). The three string clear-fields are covered by the backend enum for machine clients (MCP) but the SPA text inputs keep "empty = inherit"; adding a tri-state to those inputs is deferred, not blocked. This is the deliberate "REST API is a real audience" posture (`rest-api-purpose-mcp-and-new-ui`).
## 2026-07-21 — Browser channel preview is a server-declared per-channel capability (#60)
`key: api.channel-preview-capability` · `status: active` · `since: 2026-07-21` · `supersedes: none` · `superseded-by: none`
**Rule:** Whether a channel can be previewed in the browser is declared by the server, not derived by the SPA, as an additive `Preview` field (`{Availability, ManifestUrl, UnavailableReason}`) on `ChannelResponseModel`.
**Signals:** a Play button that does nothing; preview eligibility inferred from a display string; a green preview on a Transport Stream channel being read as validating its configured pipeline · paths: `ErsatzTV.Core/Api/Channels/ChannelPreviewResponseModel.cs`, `ErsatzTV.Application/Channels/Mapper.cs`, `web/src/screens/channels/ChannelPreviewPanel.tsx` · issues: #60
**Mechanics:** `Mapper.GetPreview(StreamingMode, channelNumber, iptvJwtEnabled, isEnabled, playoutCount)` is pure; `JwtHelper.IsEnabled` is read only at `ChannelController.GetAll` and passed in
`ChannelPreviewAvailability` is one of `Available`, `ForcedHlsOnly`, or `Unavailable`, computed in one
place from the real `StreamingMode` enum plus JWT status. The SPA renders and acts on it and derives
nothing — deriving it client-side would mean keying behavior off `Mapper.GetStreamingMode`'s
human-readable display label, where a copy tweak would silently break playback.
`Unavailable` now covers three causes, checked in this order (first match wins): JWT enabled, the
channel is disabled (`IptvController` 404s a disabled channel, so preview must not even try), and
the channel has zero playouts (a manifest request against one blocks indefinitely). Only the JWT
case was in scope at first pass; the other two were keying preview on `StreamingMode` + JWT alone,
so a disabled or playout-less channel was declared `Available` and then failed confusingly.
Only the two HLS modes are browser-playable; a browser cannot play the `video/mp2t` that the
Transport Stream modes serve over `/iptv/*`. Those are declared `ForcedHlsOnly`: preview is offered
only as an explicit opt-in that requests `/iptv/channel/{n}.m3u8?mode=segmenter`, and is always shown
with a caveat that the check does not exercise the channel's configured pipeline. Fatal HLS errors
are reported, never auto-recovered — a diagnostic surface must show the fault rather than retry past
it; a user-initiated Retry re-issues the manifest request via a real `playToken` because the manifest
GET starts a server-side session, so a byte-identical repeat URL would otherwise be a no-op.
`/iptv/*` does not accept the SPA's `ctv-session` cookie, and nothing mints a JWT for the SPA, so
under a JWT-enabled deployment preview is declared `Unavailable` with the reason `IPTV JWT
authentication is enabled` rather than failing silently against a 401.
+1
View File
@@ -11,6 +11,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `api.artwork-rooted-urls` | API response DTOs return artwork as rooted, directly-usable URLs (plus passthrough for absolute/proxy URLs), never relative Blazor-convention paths. | 2026-07-07 | [link](../decisions.md#2026-07-07--api-artwork-contract-rooted-urls-produced-server-side) |
| `api.async-op-contract` | Queue-triggering `/api/*` endpoints normalize onto one contract — 202 Accepted (queued), 404 (missing entity), 409 (lock held), 422 (domain precondition) — with Trakt as the reference implementation; playout list/detail GETs also carry an `isLocked` observability flag as the HTTP-observable substitute for a live push channel. | 2026-07-11 | [link](../decisions.md#2026-07-11--async-op-api-contract-normalization--playout-build-observability--f9-scan-endpoints-235) |
| `api.channel-health-signal` | Channel health rides `ChannelResponseModel`/`ChannelListItem` DTOs as a raw `int PlayoutCount` fact (free — `GetAll` already `Include`s `Playouts`), not a new endpoint, not `/channels/state` (runtime-liveness cadence), and not a derived `ChannelHealth` enum (would freeze policy before the #383/#384 auto-tune status taxonomy lands). | 2026-07-17 | [link](../decisions.md#2026-07-17--channel-health-on-the-api--the-raw-playoutcount-fact-on-the-list-dto-not-a-derived-status-enum-72) |
| `api.channel-preview-capability` | Whether a channel can be previewed in the browser is declared by the server, not derived by the SPA, as an additive `Preview` field (`{Availability, ManifestUrl, UnavailableReason}`) on `ChannelResponseModel`. | 2026-07-21 | [link](../decisions.md#2026-07-21--browser-channel-preview-is-a-server-declared-per-channel-capability-60) |
| `api.decode-by-id` | Endpoints that decode/expand opaque stored state accept a database row id and resolve it server-side rather than round-tripping client-supplied serialized state. | 2026-07-07 | [link](../decisions.md#2026-07-07--decode-style-endpoints-take-a-row-id-and-look-up-server-side) |
| `api.from-lineup-clear-to-none` | `POST /api/v1/channels/from-lineup` (and the Auto-Tune per-channel `advanced`, which reuses the same DTO) distinguishes *inherit* from *clear-to-none* with a typed `clear` enum list on `advanced`. A field left null/omitted still inherits the template value (unchanged for every existing client); naming a field in `clear` forces it to none on the new channel even when the template sets one. Sending both a set value and a clear for the same field is a validation error. | 2026-07-21 | [link](../decisions.md#2026-07-21--from-lineup-advanced-overrides-express-clear-to-none-via-a-typed-clear-enum-list-135) |
| `api.healthcheck-remediation-dto` | Health-check remediation is server-declared `{Kind, Target}` metadata on an additive DTO field; the SPA renders/acts on it, it doesn't derive labels itself. | 2026-07-17 | [link](../decisions.md#2026-07-17--health-check-remediation-is-server-declared-kind-target-on-an-additive-dto-the-spa-acts-on-it-164) |
+16
View File
@@ -209,6 +209,22 @@ manifest. **In tests, mock `hls.js` wholesale** (`vi.mock('hls.js', …)` with a
touches a real `MediaSource`; assert the manifest URL via the mocked `loadSource` spy (see
`PlaybackTroubleshootingScreen.test.tsx`).
It also takes an optional `onError(message)` wired to `Hls.Events.ERROR` (fatal errors only) and,
on the Safari native path, the `<video>` element's own `error` event. Fatal errors are reported,
never auto-recovered — a diagnostic surface must show the fault rather than retry past it. Pass a
**stable** `onError` (`useCallback`); it is in the attach effect's dependency array, so an unstable
identity restarts the stream every render. When mocking `hls.js` in a test that exercises errors,
include `ERROR` in the mock's `static Events`.
It also takes an optional `onPlaying()`, called once playback has actually started — wired to the
`<video>` element's own `playing` event on **both** the hls.js/MSE path and the Safari native-HLS
path. It is deliberately **not** wired to `Hls.Events.MANIFEST_PARSED`: that fires before any media
has decoded (the manifest for an `HttpLiveStreamingDirect` channel always parses, even over a black
video), so it only issues the `video.play()` kick. `onPlaying` is purely additive (omitting it is
safe) and mirrors `onError`'s requirements exactly: pass a **stable** `onPlaying` (`useCallback`),
since it too sits in the attach effect's dependency array and an unstable identity would restart the
stream every render.
## 5c. Media "Add to…" affordances
Screens that let the user add media items to a collection/playlist/schedule use the shared layer in
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,193 @@
# In-browser channel preview (ersatztv#60) — design
**Issue:** [#60 — Backlog: browser channel playback after UI redesign](http://192.168.1.95:3000/timothy/ersatztv/issues/60)
**Date:** 2026-07-21
**Status:** approved, ready for implementation planning
## Purpose
Give an operator a way to answer, from inside ChicoryTV, **"does this channel actually work
right now, and is it playing what the guide says?"** — without opening Jellyfin, Kodi, or
Dispatcharr.
This is a **verification tool**, not a viewing experience. Every design choice below resolves in
favour of diagnostic honesty over watchability: failures are surfaced rather than recovered, and a
green preview is only ever claimed for the pipeline that was actually exercised.
Explicitly out of scope: channel switching, fullscreen/lean-back UX, resume, a guide-driven
"watch" surface. If a real viewing experience is wanted later it is a separate issue built on this
component.
## Prior art already in the repo
Recon established that most of the machinery exists:
- `hls.js` is already a dependency (`web/package.json`).
- `web/src/media/HlsPlayer.tsx` is a working, reusable, teardown-safe HLS `<video>` component
(hls.js when MSE is available; native HLS on Safari). Consumed today only by
`PlaybackTroubleshootingScreen`. See `docs/spa-conventions.md` §5b.
- `ChannelsScreen.tsx` already renders a **permanently-disabled Play button** per row
(`:598`, title `"Preview unavailable for {name}"`) — this feature's socket, pre-wired.
- CSP/CORP need no change: `SecurityHeadersMiddleware` sets `default-src 'self'` (the fallback for
`media-src`) and `connect-src 'self'`, and `Cross-Origin-Resource-Policy: same-origin` does not
affect same-origin `<video>`/MSE loads from `/app`.
- `GET /api/v1/channels/state` already returns `NowPlaying` (`Title`/`StartUtc`/`FinishUtc`) per
channel, and `ChannelsScreen` already fetches and renders it in its "Now" column
(`ChannelsScreen.tsx:209,585`) — so the guide correlation needs no new endpoint, no new fetch,
and no timer.
## Constraints discovered during design
### Only two of four streaming modes are browser-playable
A `<video>` element cannot play `video/mp2t`.
| `StreamingMode` | URL | Browser-playable |
|---|---|---|
| `HttpLiveStreamingSegmenter` | `/iptv/channel/{n}.m3u8` → session variant | yes (HLS) |
| `HttpLiveStreamingDirect` | `/iptv/channel/{n}.m3u8` | yes (HLS) |
| `TransportStreamHybrid` | `/iptv/channel/{n}.ts` | no (raw MPEG-TS) |
| `TransportStream` | `/iptv/channel/{n}.ts` | no (raw MPEG-TS) |
### `/iptv/*` does not accept the SPA session cookie
`ConditionalIptvAuthorizeFilter` no-ops unless `JwtHelper.IsEnabled` (i.e. `JWT:IssuerSigningKey`
is configured) — so `/iptv/*` is **anonymous by default**. When JWT *is* enabled, the `"jwt"`
scheme accepts only a bearer token or `?access_token=`; the SPA's `ctv-session` cookie is a
distinct scheme and does not satisfy it, and **nothing in the app currently mints a JWT for the
SPA**. Preview must therefore degrade visibly under that configuration rather than fail silently.
> This same latent hole affects the **existing** troubleshooting preview, which feeds
> `/iptv/session/.troubleshooting/live.m3u8` to `HlsPlayer` with no token. Out of scope here;
> tracked as a follow-up issue.
### Streaming mode is exposed to the SPA only as a display string
`ChannelResponseModel.StreamingMode` is a human label (`"HLS Segmenter"`, `"MPEG-TS (Legacy)"`)
produced by `ErsatzTV.Application/Channels/Mapper.GetStreamingMode`. Deriving preview eligibility
from it in the SPA would let a copy tweak silently break the player.
## Design
### Server: one additive, server-declared capability field
Following `api.healthcheck-remediation-dto` (server-declared metadata on an additive DTO field;
the SPA renders and acts on it, it does not derive labels itself) and `api.artwork-rooted-urls`
(rooted, directly-usable URLs):
`ChannelResponseModel` (the list DTO the SPA previews from) gains a `Preview` field.
`ChannelDetailResponseModel` deliberately does not — nothing consumes it there, so it stays out
rather than being added speculatively.
```
Preview: {
Availability: "Available" | "ForcedHlsOnly" | "Unavailable"
ManifestUrl: string? // rooted and ready to use, e.g. "/iptv/channel/12.1.m3u8"
// or "/iptv/channel/12.1.m3u8?mode=segmenter" for ForcedHlsOnly
UnavailableReason: string? // e.g. "IPTV JWT authentication is enabled"
}
```
Computed server-side in one place from `JwtHelper.IsEnabled` and the real `StreamingMode` enum:
| Condition | `Availability` | `ManifestUrl` |
|---|---|---|
| `JwtHelper.IsEnabled` | `Unavailable` | `null` |
| `HttpLiveStreamingSegmenter` / `HttpLiveStreamingDirect` | `Available` | `/iptv/channel/{n}.m3u8` |
| `TransportStream` / `TransportStreamHybrid` | `ForcedHlsOnly` | `/iptv/channel/{n}.m3u8?mode=segmenter` |
Additive-only, consistent with `api.versioning-v1`. This is the single source of truth for preview
capability; **no** `IptvJwtEnabled` flag is added to `AuthConfigResponse`.
### SPA
- **`web/src/media/HlsPlayer.tsx`** — gains an optional `onError` callback wired to
`Hls.Events.ERROR` and to the `<video>` element's own `error` event (Safari native path). Today
failures are silent, which is disqualifying for a diagnostic tool. Strictly additive; existing
`PlaybackTroubleshootingScreen` usage is unchanged.
- **`web/src/screens/channels/ChannelPreviewPanel.tsx`** — new. A `SlideOver`
(`spa.autotune-detailpanel-slideover`) owning preview state, the player, the diagnostic readout,
and the guide correlation. Understandable and testable without the channels list.
- **`ChannelsScreen.tsx`** — the existing disabled Play button becomes live and opens the panel;
its state derives from `Preview.Availability` alone.
### Panel contents
```
Preview: 12.1 Vaporwave [x]
+--------------------------------------+
| [ video ] |
+--------------------------------------+
Mode: HLS Segmenter
URL: /iptv/channel/12.1.m3u8 [copy]
State: * playing
Guide says now: "Neon Nights" 20:00-21:00
```
For `ForcedHlsOnly`, a persistent caveat banner accompanies every result:
> This channel is configured for Transport Stream, which browsers cannot play. This preview forces
> an HLS segmenter session — it checks the content, **not** the channel's configured pipeline.
### Data flow
1. `GET /api/v1/channels` — each row already carries `Preview`. Play button state comes straight
from `Preview.Availability`; no extra request, no client-side mode parsing.
2. Click Play → panel opens with the channel and its `Preview`. For `ForcedHlsOnly` the primary
button is disabled and a secondary "Preview via HLS anyway" action uses the same `ManifestUrl`.
3. Panel passes `Preview.ManifestUrl` to `HlsPlayer` as `src`, incrementing `playToken` on each
play — the segmenter manifest GET **starts a server-side session**, so a repeat play of an
identical URL must re-issue the request rather than be a state no-op (`spa-conventions` §5b).
4. "Guide says now" is read from the `ChannelStateResponseModel.NowPlaying`
(`Title`/`StartUtc`/`FinishUtc`) that `ChannelsScreen` **already** has in hand via `statesById`
(`ChannelsScreen.tsx:209`) and already renders in its "Now" column. It is passed to the panel as
a prop. **No new fetch and no timer** — the panel re-renders whenever the screen's existing
channel-state query refreshes. When `NowPlaying` is null the panel shows "Nothing scheduled".
5. Close/unmount → `HlsPlayer` tears down the hls.js instance (existing behavior), ending segment
fetches.
### Error handling
- Player states are explicit and plain-language: `idle -> starting -> playing -> stalled ->
failed(reason)`.
- Fatal hls.js errors are **reported, not auto-recovered**. A diagnostic tool that silently retries
hides the fault it exists to reveal.
- The manifest URL in play is always visible and copyable, so any failure can be reproduced with
`curl` outside the browser.
- A `ForcedHlsOnly` result never reads as validating the configured TS pipeline.
## Testing
- **Vitest with `hls.js` mocked wholesale** per `spa-conventions` §5b (class exposing
`static isSupported()`, `static Events`, `loadSource`/`attachMedia`/`on`/`destroy`) so jsdom
never touches a real `MediaSource`; the manifest URL is asserted via the `loadSource` spy.
Established in `PlaybackTroubleshootingScreen.test.tsx`.
- Panel tests per `Availability` value: button state, URL loaded, caveat banner present only for
`ForcedHlsOnly`, error state rendered when the mocked hls.js emits a fatal `ERROR`.
- `PlaybackTroubleshootingScreen`'s existing test stays green unchanged — the guard that the
`HlsPlayer` extension is genuinely additive.
- **Server:** unit tests over the preview-capability mapper for all four `StreamingMode` values x
JWT on/off (8 cases).
- **Live-E2E** via `scripts/e2e-local.sh` against a **fresh config dir**
(`testing.e2e-local-fresh-config-dir`): create a segmenter channel, confirm `GET
/api/v1/channels` returns a usable `Preview.ManifestUrl`, and `curl` that manifest to confirm a
real playlist comes back. Runs **before** the push (`testing.live-e2e-prepush-timing`).
## Process obligations
- Touches `ErsatzTV.Core/Api/**` → regenerate OpenAPI artifacts (`v1.json`, `v1.d.ts`,
`endpoint-index.md`) via `./scripts/update-openapi.sh` then `npm run generate:api`, in the same
diff (`release.api-contract-ci-gate`). Build the app project **first**
(`process.pr-routine-sequence`).
- Mandatory independent cold-context review before push (`process.independent-review-rubric`) —
API DTO surface plus auth-config-derived behavior.
- Docs updated in the same PR: `docs/api-conventions.md` checklist, `docs/spa-conventions.md` §5b
(the `onError` extension), and a decision record for the server-declared preview-capability
field.
## Follow-ups (separate issues)
1. **Mint a short-lived JWT for the SPA** so `/iptv/*` preview and the existing troubleshooting
screen work under a JWT-enabled deployment. New auth surface; needs its own security review.
2. **Selector gap:** `scripts/select-queue.sh` ranks Renovate's bot-authored "Dependency Dashboard"
(#22) as a workable pickup. It should be excluded.
+2
View File
@@ -260,6 +260,8 @@ describe('ChicoryTV SPA scaffold', () => {
language: 'en',
name: 'Retro Cartoons',
number: '5.1',
// Server-derived preview eligibility (Task 2/60): required on the ChannelResponseModel row.
preview: { availability: 'Unavailable', manifestUrl: null, unavailableReason: null },
showInEpg: true,
sortNumber: 5.1,
streamingMode: 'HLS Direct'
+6
View File
@@ -2,6 +2,12 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { ApiError, request } from './client';
import type { components } from './generated/v1';
// ChannelResponseModel.preview.availability is typed as a bare `string` in the generated types
// (ChannelPreviewResponseModel.cs uses a plain C# string, not an enum, to keep the OpenAPI schema
// simple — see the comment there). Hand-maintain the real set of values here so a typo like
// 'ForcedHLSOnly' fails to compile instead of silently disabling a branch forever.
export type ChannelPreviewAvailability = 'Available' | 'ForcedHlsOnly' | 'Unavailable';
export type ChannelSummary = components['schemas']['ChannelResponseModel'];
export type ChannelState = components['schemas']['ChannelStateResponseModel'];
export type Channel = components['schemas']['ChannelDetailResponseModel'];
+6
View File
@@ -237,6 +237,11 @@ export interface components {
};
"ChannelPlayoutMode": "Continuous" | "OnDemand";
"ChannelPlayoutSource": "Generated" | "Mirror";
"ChannelPreviewResponseModel": {
"availability": string;
"manifestUrl": null | string;
"unavailableReason": null | string;
};
"ChannelResponseModel": {
"id": number;
"number": string;
@@ -251,6 +256,7 @@ export interface components {
"showInEpg": boolean;
"playoutCount": number;
"logo": null | string;
"preview": components["schemas"]["ChannelPreviewResponseModel"];
};
"ChannelSongVideoMode": "Default" | "WithProgress";
"ChannelStateResponseModel": {
+108
View File
@@ -0,0 +1,108 @@
import { render } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { HlsPlayer } from './HlsPlayer';
const hlsMock = {
isSupported: true,
loadSource: vi.fn(),
attachMedia: vi.fn(),
on: vi.fn(),
destroy: vi.fn(),
startLoad: vi.fn(),
recoverMediaError: vi.fn()
};
vi.mock('hls.js', () => {
class MockHls {
static isSupported() {
return hlsMock.isSupported;
}
static Events = { MANIFEST_PARSED: 'hlsManifestParsed', ERROR: 'hlsError' };
loadSource = hlsMock.loadSource;
attachMedia = hlsMock.attachMedia;
on = hlsMock.on;
destroy = hlsMock.destroy;
startLoad = hlsMock.startLoad;
recoverMediaError = hlsMock.recoverMediaError;
}
return { default: MockHls };
});
describe('HlsPlayer', () => {
beforeEach(() => {
vi.clearAllMocks();
hlsMock.isSupported = true;
});
it('reports a fatal hls.js error through onError', () => {
const onError = vi.fn();
render(<HlsPlayer onError={onError} src="/iptv/channel/12.1.m3u8" />);
const errorHandler = hlsMock.on.mock.calls.find((call) => call[0] === 'hlsError')?.[1];
expect(errorHandler).toBeTypeOf('function');
errorHandler({}, { fatal: true, type: 'networkError', details: 'manifestLoadError' });
expect(onError).toHaveBeenCalledWith('networkError: manifestLoadError');
});
it('ignores non-fatal hls.js errors', () => {
const onError = vi.fn();
render(<HlsPlayer onError={onError} src="/iptv/channel/12.1.m3u8" />);
const errorHandler = hlsMock.on.mock.calls.find((call) => call[0] === 'hlsError')?.[1];
errorHandler({}, { fatal: false, type: 'mediaError', details: 'bufferStalledError' });
expect(onError).not.toHaveBeenCalled();
});
it('does not auto-recover a fatal error', () => {
render(<HlsPlayer onError={vi.fn()} src="/iptv/channel/12.1.m3u8" />);
const errorHandler = hlsMock.on.mock.calls.find((call) => call[0] === 'hlsError')?.[1];
errorHandler({}, { fatal: true, type: 'networkError', details: 'manifestLoadError' });
// A diagnostic player must surface the fault, not silently retry past it — auto-recovery is
// hls.js's own startLoad()/recoverMediaError(), so assert those directly rather than only
// inferring it from loadSource's call count.
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
expect(hlsMock.startLoad).not.toHaveBeenCalled();
expect(hlsMock.recoverMediaError).not.toHaveBeenCalled();
});
it('does not report onPlaying when hls.js merely parses the manifest', () => {
// MANIFEST_PARSED fires before any media has decoded — an HttpLiveStreamingDirect manifest
// always parses even over a black video, so onPlaying must not be driven by it.
const onPlaying = vi.fn();
render(<HlsPlayer onPlaying={onPlaying} src="/iptv/channel/12.1.m3u8" />);
const manifestHandler = hlsMock.on.mock.calls.find((call) => call[0] === 'hlsManifestParsed')?.[1];
expect(manifestHandler).toBeTypeOf('function');
manifestHandler();
expect(onPlaying).not.toHaveBeenCalled();
});
it('reports onPlaying when the video element fires its real playing event', () => {
const onPlaying = vi.fn();
const { container } = render(<HlsPlayer onPlaying={onPlaying} src="/iptv/channel/12.1.m3u8" />);
const video = container.querySelector('video');
expect(video).not.toBeNull();
video?.dispatchEvent(new Event('playing'));
expect(onPlaying).toHaveBeenCalledTimes(1);
});
it('is safe with no onPlaying provided', () => {
const { container } = render(<HlsPlayer src="/iptv/channel/12.1.m3u8" />);
const manifestHandler = hlsMock.on.mock.calls.find((call) => call[0] === 'hlsManifestParsed')?.[1];
expect(() => manifestHandler()).not.toThrow();
const video = container.querySelector('video');
expect(() => video?.dispatchEvent(new Event('playing'))).not.toThrow();
});
});
+30 -2
View File
@@ -12,6 +12,14 @@ export interface HlsPlayerProps {
playToken?: number;
className?: string;
style?: CSSProperties;
// Called with a human-readable reason when playback fails. Fatal errors are reported, never
// auto-recovered: a diagnostic player that silently retries hides the fault it exists to reveal.
onError?: (message: string) => void;
// Called once playback has actually started — wired to the `<video>` element's own `playing`
// event on both the hls.js/MSE path and the native-HLS (Safari) path, since MANIFEST_PARSED fires
// before any media has decoded (an HttpLiveStreamingDirect manifest always parses even over a
// black video). Optional and purely additive — omitting it is safe.
onPlaying?: () => void;
}
// A small HLS video player. Uses hls.js when Media Source Extensions are available (config mirrors
@@ -19,7 +27,7 @@ export interface HlsPlayerProps {
// segments exist, so the manifest request must tolerate an unbounded time-to-first-byte), and falls
// back to the browser's native HLS support (Safari) otherwise. Reusable across any screen that needs
// to preview an ErsatzTV HLS stream.
export function HlsPlayer({ src, playToken = 0, className, style }: HlsPlayerProps) {
export function HlsPlayer({ src, playToken = 0, className, style, onError, onPlaying }: HlsPlayerProps) {
const videoRef = useRef<HTMLVideoElement | null>(null);
const hlsRef = useRef<Hls | null>(null);
@@ -59,8 +67,18 @@ export function HlsPlayer({ src, playToken = 0, className, style }: HlsPlayerPro
// Autoplay may be blocked; the user can press play manually.
});
});
hls.on(Hls.Events.ERROR, (_event, data) => {
if (data.fatal) {
onError?.(`${data.type}: ${data.details}`);
}
});
const onVideoPlaying = () => {
onPlaying?.();
};
video.addEventListener('playing', onVideoPlaying);
return () => {
video.removeEventListener('playing', onVideoPlaying);
destroyHls();
};
}
@@ -73,8 +91,18 @@ export function HlsPlayer({ src, playToken = 0, className, style }: HlsPlayerPro
});
};
video.addEventListener('canplay', onCanPlay);
const onVideoError = () => {
onError?.('The browser could not play this stream');
};
video.addEventListener('error', onVideoError);
const onVideoPlaying = () => {
onPlaying?.();
};
video.addEventListener('playing', onVideoPlaying);
return () => {
video.removeEventListener('canplay', onCanPlay);
video.removeEventListener('error', onVideoError);
video.removeEventListener('playing', onVideoPlaying);
video.removeAttribute('src');
video.load();
};
@@ -82,7 +110,7 @@ export function HlsPlayer({ src, playToken = 0, className, style }: HlsPlayerPro
return undefined;
// playToken forces re-attachment for repeat plays of an identical src (see HlsPlayerProps).
}, [src, playToken]);
}, [src, playToken, onError, onPlaying]);
// Final unmount safety net (covers the hls.js instance in every path).
useEffect(
+91 -1
View File
@@ -2,6 +2,31 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-li
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ChannelsScreen } from './ChannelsScreen';
// The channel preview panel mounts HlsPlayer, which imports hls.js. jsdom has no MediaSource, so
// hls.js must never touch the real implementation here — mocked wholesale, same shape as
// channels/ChannelPreviewPanel.test.tsx.
const hlsMock = {
isSupported: true,
loadSource: vi.fn(),
attachMedia: vi.fn(),
on: vi.fn(),
destroy: vi.fn()
};
vi.mock('hls.js', () => {
class MockHls {
static isSupported() {
return hlsMock.isSupported;
}
static Events = { MANIFEST_PARSED: 'hlsManifestParsed', ERROR: 'hlsError' };
loadSource = hlsMock.loadSource;
attachMedia = hlsMock.attachMedia;
on = hlsMock.on;
destroy = hlsMock.destroy;
}
return { default: MockHls };
});
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
@@ -19,6 +44,10 @@ function channelRow(overrides: Record<string, unknown> = {}): Record<string, unk
// The API always sends playoutCount; default to a healthy channel so only tests that opt in
// render the "No playout" fault state.
playoutCount: 1,
// Server-derived preview eligibility (Task 2). Defaults to Unavailable so most existing
// fixtures keep asserting the disabled preview button; tests that need a different
// availability override this explicitly.
preview: { availability: 'Unavailable', manifestUrl: null, unavailableReason: null },
showInEpg: true,
sortNumber: 5.1,
streamingMode: 'HLS Direct',
@@ -255,7 +284,7 @@ describe('ChannelsScreen — load + render', () => {
expect(fetchCount(handle, '/api/v1/channels')).toBe(channelFetchesBeforePoll);
});
it('keeps preview disabled because the list DTO lacks legacy preview support data', async () => {
it('keeps preview disabled when the fixture defaults to Unavailable', async () => {
mockApi({
channels: [channelRow({ streamingMode: 'HLS Segmenter' })],
channelStates: [stateRow({ onAir: true })]
@@ -266,6 +295,67 @@ describe('ChannelsScreen — load + render', () => {
expect(screen.getByRole('button', { name: 'Preview unavailable for Retro Cartoons' })).toBeDisabled();
});
it('enables preview for an available channel and opens the panel', async () => {
mockApi({
channels: [
channelRow({
name: 'Vaporwave',
preview: { availability: 'Available', manifestUrl: '/iptv/channel/12.1.m3u8', unavailableReason: null }
})
]
});
render(<ChannelsScreen />);
const play = await screen.findByRole('button', { name: 'Preview Vaporwave' });
expect(play).toBeEnabled();
fireEvent.click(play);
expect(await screen.findByText('Preview: Vaporwave')).toBeInTheDocument();
});
it('disables preview and explains why when the server says unavailable', async () => {
mockApi({
channels: [
channelRow({
name: 'Vaporwave',
preview: {
availability: 'Unavailable',
manifestUrl: null,
unavailableReason: 'IPTV JWT authentication is enabled'
}
})
]
});
render(<ChannelsScreen />);
const play = await screen.findByRole('button', { name: /IPTV JWT authentication is enabled/ });
expect(play).toBeDisabled();
});
it('offers preview for a transport-stream channel via the forced-hls path', async () => {
mockApi({
channels: [
channelRow({
name: 'Retro TV',
preview: {
availability: 'ForcedHlsOnly',
manifestUrl: '/iptv/channel/12.2.m3u8?mode=segmenter',
unavailableReason: null
},
streamingMode: 'MPEG-TS'
})
]
});
render(<ChannelsScreen />);
const play = await screen.findByRole('button', { name: 'Preview Retro TV' });
expect(play).toBeEnabled();
});
});
describe('ChannelsScreen — filtering + selection', () => {
+50 -1
View File
@@ -22,12 +22,14 @@ import {
getWatermarks,
messageFromError,
useChannelsScreenQuery,
type ChannelPreviewAvailability,
type ChannelState,
type ChannelSummary,
type CreateChannelRequest
} from '../api';
import { navigateToPath } from '../routing';
import { usePrimaryAction } from '../primaryAction';
import { ChannelPreviewPanel } from './channels/ChannelPreviewPanel';
type ChannelViewFilter = 'all' | 'onair' | 'disabled' | 'noplayout';
@@ -193,6 +195,7 @@ export function ChannelsScreen() {
const [mutationError, setMutationError] = useState<string | null>(null);
const [mutating, setMutating] = useState(false);
const [creatingBlank, setCreatingBlank] = useState(false);
const [previewChannelId, setPreviewChannelId] = useState<null | number>(null);
// TopBar "Add Channel" primary action → the library-to-lineup builder.
usePrimaryAction('channels', () => navigateToPath('/app/new-channel'));
@@ -474,6 +477,7 @@ export function ChannelsScreen() {
key={group}
mutating={mutating}
onDelete={deleteOne}
onPreview={setPreviewChannelId}
onToggle={toggleOne}
selectedIds={selectedIds}
statesById={statesById}
@@ -487,6 +491,31 @@ export function ChannelsScreen() {
<span><code>{groups.length}</code> groups</span>
</div>
</div>
{previewChannelId !== null &&
(() => {
const previewChannel = channels.find((channel) => channel.id === previewChannelId);
if (!previewChannel) {
return null;
}
return (
<ChannelPreviewPanel
channel={{
...previewChannel,
preview: {
...previewChannel.preview,
// The generated ChannelSummary types `availability` as a bare `string` (see
// web/src/api/channels.ts); narrow it once here so ChannelPreviewPanel's own
// comparisons are checked against the real ChannelPreviewAvailability union.
availability: previewChannel.preview.availability as ChannelPreviewAvailability
}
}}
nowPlaying={statesById.get(previewChannelId)?.nowPlaying ?? null}
onClose={() => setPreviewChannelId(null)}
open
/>
);
})()}
</div>
);
}
@@ -496,6 +525,7 @@ function ChannelGroupRows({
group,
mutating,
onDelete,
onPreview,
onToggle,
selectedIds,
statesById
@@ -504,6 +534,7 @@ function ChannelGroupRows({
group: string;
mutating: boolean;
onDelete: (channel: ChannelSummary) => void;
onPreview: (channelId: number) => void;
onToggle: (channelId: number) => void;
selectedIds: Set<number>;
statesById: Map<number, ChannelState>;
@@ -521,6 +552,7 @@ function ChannelGroupRows({
key={channel.id}
mutating={mutating}
onDelete={onDelete}
onPreview={onPreview}
onToggle={onToggle}
selected={selectedIds.has(channel.id)}
state={statesById.get(channel.id) ?? null}
@@ -538,6 +570,7 @@ function ChannelTableRow({
channel,
mutating,
onDelete,
onPreview,
onToggle,
selected,
state
@@ -545,6 +578,7 @@ function ChannelTableRow({
channel: ChannelSummary;
mutating: boolean;
onDelete: (channel: ChannelSummary) => void;
onPreview: (channelId: number) => void;
onToggle: (channelId: number) => void;
selected: boolean;
state: ChannelState | null;
@@ -553,6 +587,10 @@ function ChannelTableRow({
const dim = !channel.isEnabled;
const progress = state ? progressFromChannelState(state) : null;
const streamingTone = streamingModeBadgeTones[channel.streamingMode] ?? 'neutral';
// Narrow once: ChannelSummary types `preview.availability` as a bare `string` (see
// web/src/api/channels.ts), so comparing the union-typed local below against a mistyped literal
// (e.g. 'UnavailableX') is a compile error, where comparing the raw string field would not be.
const previewAvailability = channel.preview.availability as ChannelPreviewAvailability;
return (
<tr className={`${live ? 'ctv-channel-row-live ' : ''}${selected ? 'ctv-channel-row-selected ' : ''}${dim ? 'ctv-channel-row-dim' : ''}`}>
@@ -595,7 +633,18 @@ function ChannelTableRow({
<td className="ctv-channel-ffmpeg">{channel.ffmpegProfile || 'Unassigned'}</td>
<td>
<div className="ctv-channel-actions">
<IconButton disabled size="sm" title={`Preview unavailable for ${channel.name}`}>
<IconButton
disabled={previewAvailability === 'Unavailable'}
onClick={() => onPreview(channel.id)}
size="sm"
title={
previewAvailability === 'Unavailable'
? channel.preview.unavailableReason
? `Preview unavailable for ${channel.name} — ${channel.preview.unavailableReason}`
: `Preview unavailable for ${channel.name}`
: `Preview ${channel.name}`
}
>
<Play aria-hidden="true" size={15} />
</IconButton>
<IconButton onClick={() => navigateToPath(`/app/edit-channel/${channel.id}`)} size="sm" title={`Edit ${channel.name}`}>
@@ -0,0 +1,336 @@
import { act } from 'react';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChannelPreviewAvailability } from '../../api/channels';
import { ChannelPreviewPanel } from './ChannelPreviewPanel';
const hlsMock = {
isSupported: true,
loadSource: vi.fn(),
attachMedia: vi.fn(),
on: vi.fn(),
destroy: vi.fn()
};
vi.mock('hls.js', () => {
class MockHls {
static isSupported() {
return hlsMock.isSupported;
}
static Events = { MANIFEST_PARSED: 'hlsManifestParsed', ERROR: 'hlsError' };
loadSource = hlsMock.loadSource;
attachMedia = hlsMock.attachMedia;
on = hlsMock.on;
destroy = hlsMock.destroy;
}
return { default: MockHls };
});
function channel(preview: ChannelPreview, streamingMode = 'HLS Segmenter', id = 1) {
return { id, name: 'Vaporwave', number: '12.1', preview, streamingMode };
}
interface ChannelPreview {
availability: ChannelPreviewAvailability;
manifestUrl: null | string;
unavailableReason: null | string;
}
const available: ChannelPreview = {
availability: 'Available',
manifestUrl: '/iptv/channel/12.1.m3u8',
unavailableReason: null
};
const forced: ChannelPreview = {
availability: 'ForcedHlsOnly',
manifestUrl: '/iptv/channel/12.1.m3u8?mode=segmenter',
unavailableReason: null
};
const available2: ChannelPreview = {
availability: 'Available',
manifestUrl: '/iptv/channel/34.1.m3u8',
unavailableReason: null
};
const unavailable: ChannelPreview = {
availability: 'Unavailable',
manifestUrl: null,
unavailableReason: 'IPTV JWT authentication is enabled'
};
function getErrorHandler() {
return hlsMock.on.mock.calls.find((call) => call[0] === 'hlsError')?.[1];
}
function getManifestHandler() {
return hlsMock.on.mock.calls.find((call) => call[0] === 'hlsManifestParsed')?.[1];
}
describe('ChannelPreviewPanel', () => {
beforeEach(() => {
vi.clearAllMocks();
hlsMock.isSupported = true;
});
afterEach(() => {
cleanup();
});
it('loads the declared manifest url for an available channel', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(hlsMock.loadSource).toHaveBeenCalledWith('/iptv/channel/12.1.m3u8');
});
it('shows the now-playing title it was given', () => {
render(
<ChannelPreviewPanel
channel={channel(available)}
nowPlaying={{ finishUtc: '2026-07-21T21:00:00Z', startUtc: '2026-07-21T20:00:00Z', title: 'Neon Nights' }}
onClose={vi.fn()}
open
/>
);
expect(screen.getByText('Neon Nights')).toBeInTheDocument();
});
it('shows nothing-scheduled when there is no now-playing', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(screen.getByText('Nothing scheduled')).toBeInTheDocument();
});
it('does not autoplay a forced-hls channel and shows the caveat both before and after opting in', () => {
render(
<ChannelPreviewPanel
channel={channel(forced, 'MPEG-TS')}
nowPlaying={null}
onClose={vi.fn()}
open
/>
);
// Before opting in: nothing loaded, but the caveat already explains why the primary action
// (autoplay) is unavailable.
expect(hlsMock.loadSource).not.toHaveBeenCalled();
expect(screen.getByText(/not the channel's configured pipeline/i)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /preview via hls anyway/i }));
// After opting in: the stream loads, and the caveat persists as a banner beside the result.
expect(hlsMock.loadSource).toHaveBeenCalledWith('/iptv/channel/12.1.m3u8?mode=segmenter');
expect(screen.getByText(/not the channel's configured pipeline/i)).toBeInTheDocument();
});
it('never shows the caveat for an available channel', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(screen.queryByText(/not the channel's configured pipeline/i)).not.toBeInTheDocument();
});
it('renders the server reason and no player when unavailable', () => {
render(
<ChannelPreviewPanel channel={channel(unavailable)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(screen.getByText('IPTV JWT authentication is enabled')).toBeInTheDocument();
expect(hlsMock.loadSource).not.toHaveBeenCalled();
});
it('surfaces a fatal playback error', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
const errorHandler = getErrorHandler();
act(() => {
errorHandler({}, { details: 'manifestLoadError', fatal: true, type: 'networkError' });
});
expect(screen.getByText(/networkError: manifestLoadError/)).toBeInTheDocument();
});
it('shows the manifest url so a failure can be reproduced with curl', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(screen.getByText('/iptv/channel/12.1.m3u8')).toBeInTheDocument();
});
it('clicking Retry re-issues the manifest request (a fresh play token)', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button', { name: /retry/i }));
expect(hlsMock.loadSource).toHaveBeenCalledTimes(2);
expect(hlsMock.loadSource).toHaveBeenNthCalledWith(2, '/iptv/channel/12.1.m3u8');
});
it('clicking Retry clears a prior error', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
const errorHandler = getErrorHandler();
act(() => {
errorHandler({}, { details: 'manifestLoadError', fatal: true, type: 'networkError' });
});
expect(screen.getByText(/networkError: manifestLoadError/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /retry/i }));
expect(screen.queryByText(/networkError: manifestLoadError/)).not.toBeInTheDocument();
});
it('stays in starting once hls.js merely reports MANIFEST_PARSED', () => {
// MANIFEST_PARSED fires before any media has decoded, so it must not be enough to reach playing.
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(screen.getByText('starting')).toBeInTheDocument();
const manifestHandler = getManifestHandler();
act(() => {
manifestHandler();
});
expect(screen.getByText('starting')).toBeInTheDocument();
});
it('reaches the playing state once the video element fires its real playing event', () => {
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(screen.getByText('starting')).toBeInTheDocument();
// SlideOver renders into a document.body portal, not the render() container.
const video = document.body.querySelector('video');
expect(video).not.toBeNull();
act(() => {
video?.dispatchEvent(new Event('playing'));
});
expect(screen.getByText('playing')).toBeInTheDocument();
});
it('does not let a subsequent playing event (e.g. a manual play-button click) erase a fatal error', () => {
// A fatal error must be reported and stay reported: it must never be silently erased by a later
// `playing` event, such as the one fired when the operator manually clicks the visible play
// button on the <video controls> element after the failure banner is already showing.
render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
const errorHandler = getErrorHandler();
act(() => {
errorHandler({}, { details: 'manifestLoadError', fatal: true, type: 'networkError' });
});
expect(screen.getByText(/failed — networkError: manifestloaderror/i)).toBeInTheDocument();
const video = document.body.querySelector('video');
expect(video).not.toBeNull();
act(() => {
video?.dispatchEvent(new Event('playing'));
});
expect(screen.getByText(/failed — networkError: manifestloaderror/i)).toBeInTheDocument();
expect(screen.queryByText('playing')).not.toBeInTheDocument();
});
describe('switching to a different channel while mounted (render-phase reset)', () => {
it('does not auto-start a forced-hls-only channel switched in from an available one', () => {
const { rerender } = render(
<ChannelPreviewPanel channel={channel(available)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
rerender(
<ChannelPreviewPanel channel={channel(forced, 'MPEG-TS', 2)} nowPlaying={null} onClose={vi.fn()} open />
);
// No new load for the forced channel: it must stay opt-in, never auto-start.
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
expect(screen.getByRole('button', { name: /preview via hls anyway/i })).toBeInTheDocument();
});
it('clears a prior error and starts the new channel when switching between two available channels', () => {
const { rerender } = render(
<ChannelPreviewPanel channel={channel(available, undefined, 1)} nowPlaying={null} onClose={vi.fn()} open />
);
const errorHandler = getErrorHandler();
act(() => {
errorHandler({}, { details: 'manifestLoadError', fatal: true, type: 'networkError' });
});
expect(screen.getByText(/networkError: manifestLoadError/)).toBeInTheDocument();
rerender(
<ChannelPreviewPanel channel={channel(available2, undefined, 2)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(screen.queryByText(/networkError: manifestLoadError/)).not.toBeInTheDocument();
expect(hlsMock.loadSource).toHaveBeenLastCalledWith('/iptv/channel/34.1.m3u8');
// The failed-flag reset runs in an effect, not during render, so prove it actually ran: the
// new channel must still be able to reach `playing`. Without this assertion, deleting that
// reset leaves the suite green while the new channel sits at `starting` forever, because
// onPlaying would keep returning early on the PREVIOUS channel's stale failed flag.
const video = document.body.querySelector('video');
act(() => {
video?.dispatchEvent(new Event('playing'));
});
expect(screen.getByText('playing')).toBeInTheDocument();
});
it('does not carry the retry play token over to the next channel', () => {
// Both channels share a manifest URL so the only thing that could re-trigger the attach
// effect across the switch is playToken. If the reset failed to zero it out, the token
// would be unchanged (2 -> 2) and the effect (and loadSource) would NOT re-fire on switch.
const sameUrlA: ChannelPreview = {
availability: 'Available',
manifestUrl: '/iptv/channel/shared.m3u8',
unavailableReason: null
};
const sameUrlB: ChannelPreview = {
availability: 'Available',
manifestUrl: '/iptv/channel/shared.m3u8',
unavailableReason: null
};
const { rerender } = render(
<ChannelPreviewPanel channel={channel(sameUrlA, undefined, 1)} nowPlaying={null} onClose={vi.fn()} open />
);
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button', { name: /retry/i }));
fireEvent.click(screen.getByRole('button', { name: /retry/i }));
expect(hlsMock.loadSource).toHaveBeenCalledTimes(3);
rerender(
<ChannelPreviewPanel channel={channel(sameUrlB, undefined, 2)} nowPlaying={null} onClose={vi.fn()} open />
);
// A fresh channel with playToken reset to 0 differs from the prior effective token (2),
// so the attach effect re-fires exactly once more even though the manifest url is unchanged.
expect(hlsMock.loadSource).toHaveBeenCalledTimes(4);
});
});
});
@@ -0,0 +1,165 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { ChannelPreviewAvailability } from '../../api/channels';
import { Button } from '../../components/forms';
import { SlideOver } from '../../components/overlay';
import { HlsPlayer } from '../../media/HlsPlayer';
export const FORCED_HLS_CAVEAT =
"This channel is configured for Transport Stream, which browsers cannot play. This preview forces an HLS segmenter session — it checks the content, not the channel's configured pipeline.";
export interface ChannelPreviewNowPlaying {
title: string;
startUtc: string;
finishUtc: string;
}
export interface ChannelPreviewPanelProps {
open: boolean;
onClose: () => void;
channel: {
id: number;
name: string;
number: string;
streamingMode: string;
preview: {
availability: ChannelPreviewAvailability;
manifestUrl: null | string;
unavailableReason: null | string;
};
};
nowPlaying: ChannelPreviewNowPlaying | null;
}
type PlaybackState = 'failed' | 'idle' | 'playing' | 'starting';
// Operator diagnostic: renders a live HLS preview of a channel so an operator can answer "does this
// channel actually work right now, and is it playing what the guide says" without leaving the SPA.
export function ChannelPreviewPanel({ channel, nowPlaying, onClose, open }: ChannelPreviewPanelProps) {
const { availability, manifestUrl, unavailableReason } = channel.preview;
const forced = availability === 'ForcedHlsOnly';
// Forced previews are opt-in: they do not exercise the configured pipeline (StreamingMode is
// Transport Stream, which browsers can't play), so they must never start on their own. Available
// channels start immediately — that is the whole point of the panel.
const [started, setStarted] = useState(availability === 'Available');
const [state, setState] = useState<PlaybackState>(availability === 'Available' ? 'starting' : 'idle');
const [error, setError] = useState<null | string>(null);
// Bumped on every (re)play. The manifest GET itself starts a server-side session, so a repeat play
// of an identical URL — e.g. Retry after a failure — must re-issue the request rather than be a
// no-op; HlsPlayer tears down and re-attaches whenever this changes, even with the same src.
const [playToken, setPlayToken] = useState(0);
// Tracks whether the panel is currently showing a fatal error, mirrored alongside `state` so
// onPlaying (a stable-identity callback, see below) can check it without needing `state` in its
// dependency array. A fatal error must never be erased by a later `playing` event — including the
// native <video controls> `playing` event fired when the operator manually clicks play on a
// buffered/partial stream after the failure banner is already showing (that would silently hide
// the fault the panel exists to reveal). Only user-initiated Retry may clear it.
const failedRef = useRef(false);
// Reset when the panel is reopened for a different channel. Adjusted synchronously during
// render (React's documented "adjusting state when a prop changes" pattern) rather than in a
// useEffect body, which would trip the react-hooks "no set-state-in-effect" rule (spa-conventions
// §3) and cause an extra commit.
const [resetKey, setResetKey] = useState(channel.id);
if (resetKey !== channel.id) {
setResetKey(channel.id);
setStarted(availability === 'Available');
setState(availability === 'Available' ? 'starting' : 'idle');
setError(null);
setPlayToken(0);
}
// failedRef mutations are confined to event handlers and this effect — never render-phase — per
// the react-hooks/refs rule (mutating a ref during render is disallowed even for the documented
// "adjust state during render" pattern above, which is fine only for React state setters). This
// runs after the render-phase reset above has committed, before any user interaction or media
// event can reach onPlaying, so there is no window where a stale `true` could suppress it.
useEffect(() => {
failedRef.current = false;
}, [channel.id]);
// Stable identity: HlsPlayer keeps onError in its attach effect's dependency array, so an inline
// arrow would tear down and restart the stream on every render.
const onError = useCallback((message: string) => {
failedRef.current = true;
setError(message);
setState('failed');
}, []);
// Stable identity for the same reason as onError above. Ignores the event entirely while a fatal
// error is showing (see failedRef above) so it cannot erase the failure.
const onPlaying = useCallback(() => {
if (failedRef.current) {
return;
}
setError(null);
setState('playing');
}, []);
const onOptIn = useCallback(() => {
setStarted(true);
setState('starting');
}, []);
// User-initiated only: fatal HLS errors are never auto-recovered (a diagnostic tool that silently
// retries hides the fault it exists to reveal). Retry re-issues the manifest request by bumping
// playToken and clears the previous error so a stale failure doesn't linger over a fresh attempt.
const onRetry = useCallback(() => {
failedRef.current = false;
setError(null);
setState('starting');
setPlayToken((current) => current + 1);
}, []);
const src = started ? manifestUrl : null;
return (
<SlideOver onClose={onClose} open={open} subtitle={`Channel ${channel.number}`} title={`Preview: ${channel.name}`}>
{availability === 'Unavailable' ? (
<div className="ctv-channels-error" role="alert">
{unavailableReason}
</div>
) : (
<>
{forced && (
<p className="ctv-settings-warn-callout ctv-preview-caveat">{FORCED_HLS_CAVEAT}</p>
)}
{forced && !started && (
<Button onClick={onOptIn} variant="secondary">
Preview via HLS anyway
</Button>
)}
{src && (
<>
<HlsPlayer
className="ctv-preview-video"
onError={onError}
onPlaying={onPlaying}
playToken={playToken}
src={src}
style={{ aspectRatio: '16 / 9', background: '#000' }}
/>
<div className="ctv-detail-actions">
<Button onClick={onRetry} size="sm" variant="secondary">
Retry
</Button>
</div>
</>
)}
</>
)}
<dl className="ctv-detail-infogrid ctv-preview-facts">
<dt>Mode</dt>
<dd>{channel.streamingMode}</dd>
<dt>URL</dt>
<dd>{manifestUrl ?? 'None'}</dd>
<dt>State</dt>
<dd>{error ? `Failed — ${error}` : state}</dd>
<dt>Guide says now</dt>
<dd>{nowPlaying ? nowPlaying.title : 'Nothing scheduled'}</dd>
</dl>
</SlideOver>
);
}
+6
View File
@@ -1,5 +1,11 @@
import '@testing-library/jest-dom/vitest';
// jsdom has no real media pipeline: HTMLMediaElement.prototype.play is unimplemented and returns
// undefined rather than a Promise, which would otherwise force production code (HlsPlayer) to guard
// every call site with `?.` purely to survive tests. Stub it to behave like a real browser instead —
// tests that need an autoplay-blocked rejection can override it with vi.spyOn(...).mockRejectedValue.
HTMLMediaElement.prototype.play = () => Promise.resolve();
if (!window.localStorage) {
const storage = new Map<string, string>();
+20
View File
@@ -1117,6 +1117,26 @@ body {
gap: 2px;
}
/* ChannelPreviewPanel (#60) — the video needs a max-width so it never overflows the slide-over
body, and the forced-HLS caveat needs a little breathing room around the shared warn-callout. */
.ctv-preview-video {
display: block;
width: 100%;
max-width: 100%;
border-radius: var(--radius-sm);
}
.ctv-preview-caveat {
margin: 0 0 var(--space-6, 12px);
}
/* Two classes (higher specificity than .ctv-detail-infogrid alone) so this margin actually wins
over that shared rule's `margin: 0`, without weakening .ctv-detail-infogrid for its other
consumer (MediaDetailScreen), which relies on margin:0 there. */
.ctv-preview-facts.ctv-detail-infogrid {
margin-top: var(--space-6, 12px);
}
.ctv-channels-footer {
display: flex;
align-items: center;