Compare commits

..
Author SHA1 Message Date
timothy 68f073ed42 Merge pull request 'feat(api): channel on-air / now-playing state endpoint (#97)' (#112) from issue-97-channel-state-api into docs/59-ui-redesign-brief 2026-07-04 05:48:46 +00:00
timothyandClaude Fable 5 f6306d622f docs: advance ChicoryTV issue queue past #102 (PR #119); next prompt = SPA stack merge pass
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 07:45:34 +02:00
timothyandClaude Fable 5 a867eecaa5 docs: advance ChicoryTV issue queue past #104/#111 (PRs #117/#118); single-session prompt for #102
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 00:05:42 +02:00
timothyandClaude Fable 5 4d37de3455 docs: Codex prompt B uses effort-tiered subagents; relax build cap to <5 concurrent
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 22:58:18 +02:00
timothyandClaude Fable 5 0f8066f06d docs: advance ChicoryTV issue queue past #100/#101/#107/#110 (PR #116); next prompts #104 (Claude) + #111 (Codex)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 22:53:58 +02:00
timothyandClaude Fable 5 dc373e5a53 docs: advance ChicoryTV issue queue past #108 (PR #114); split next handoff into Claude+Codex parallel prompts
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 21:30:33 +02:00
timothyandClaude Fable 5 e663cabe9c docs: advance ChicoryTV issue queue past #105 (PR #113)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 22:37:01 +02:00
timothyandClaude Fable 5 b5714061f8 docs: prescribe per-step subagent models in issue-queue handoff
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 21:56:43 +02:00
timothyandClaude Fable 5 4db142c2f2 docs: advance ChicoryTV issue queue past #97 (PR #112)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 21:55:10 +02:00
timothyandClaude Fable 5 73455aae28 fix(api): surface programs not filler in channel state, tighten queries
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m40s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m52s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Adversarial review fixes for the #97 endpoint:

- nowPlaying now resolves like the XMLTV guide: when the wall-clock item
  is pre/mid-roll filler, surface the guide group's program item (title +
  full program bounds) instead of the filler; a guide entry with no
  program item (e.g. fallback loop) reports null. Previously an ad break
  would retitle the channel and reset progress every 30 seconds.
- covering-item lookup now runs one cheap projected query per distinct
  playout offset instead of hydrating the full metadata include tree for
  a window widened by the largest offset across ALL channels (up to 24h);
  metadata is fetched in a second query scoped to the covering guide
  groups, time-bounded to stay safe against GuideGroup recycling (mod
  10000). Regression caught while testing: covering items are keyed by
  (source channel, lookup time) so a source channel no longer inherits
  its offset mirror's lookup result.
- GetChannelStatesForApi now carries Now explicitly (controller passes
  DateTime.UtcNow), making boundary semantics testable: new tests pin
  now == Start (playing) and now == Finish (not playing), plus mid-roll,
  filler-only, and mirror-source-row cases.
- ChannelNowPlayingResponseModel title is non-nullable in the schema
  (#nullable enable) — GetDisplayTitle always returns a string.
- GetState uses the typed-return controller convention; Playouts.Mapper
  reverted to internal (handler lives in the same assembly).
- Spec doc notes the OnDemand drift caveat and filler semantics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 21:53:21 +02:00
timothyandClaude Fable 5 e66f49e54a fix(api): make channel state NowPlaying nullable in DTO
An off-air channel has no current playout item, so the handler returns
null for NowPlaying; the DTO now declares that (file-scoped #nullable —
ErsatzTV.Core has NRT disabled project-wide). Regenerated OpenAPI and
web types: nowPlaying keeps its nullable oneOf schema (matching the
schema contract test) and channelNumber loses a spurious nullable
annotation left over from an earlier draft — the field is required.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 21:37:00 +02:00
timothyandClaude Fable 5 3e44947597 docs: add ChicoryTV issue-queue handoff (one issue per session)
Living handoff document driving the sequential backend-gap work
(#97, #100-#111, merge pass, then UX screens). Each session works
one queue item and rewrites this file for the next.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 21:31:22 +02:00
timothy 07e9d9838d fix(api): resolve mirror channel now playing state 2026-07-02 20:02:01 +02:00
timothy f01ffc6254 test(api): enforce nullable channel now playing schema 2026-07-02 19:50:19 +02:00
timothy 6057bcea7d docs(api): document channel state endpoint 2026-07-02 19:45:53 +02:00
timothy 7b903d4bb4 feat(api): return channel runtime state 2026-07-02 19:37:14 +02:00
timothy 7c1a1d5672 feat(api): add channel state endpoint contract 2026-07-02 19:29:59 +02:00
timothy 1891498563 chore: ignore local worktrees 2026-07-02 19:24:06 +02:00
timothy 7484df1e5b docs(api): plan channel state endpoint 2026-07-02 19:20:50 +02:00
timothy 52bfdbcdce docs(api): specify channel state endpoint 2026-07-02 19:16:07 +02:00
timothy 6b3a698283 feat(api): add bulk channel operations
fixes #98
2026-07-02 19:07:35 +02:00
timothy 32c0d6a6d3 feat(api): enrich channel list response 2026-07-02 18:56:05 +02:00
timothy 97b6c4bee7 fix(web): harden spa foundation
refs #95
2026-07-02 18:36:56 +02:00
timothy 032b9d8116 fix(web): address app shell review findings
refs #94
2026-07-02 18:33:16 +02:00
timothy 6e6fd67fea feat(web): implement ChicoryTV dashboard
refs #83
2026-07-02 18:29:19 +02:00
timothy 5fb3bb2ebc feat(web): add ChicoryTV app shell
refs #82
2026-07-02 18:21:59 +02:00
timothy d1cc12e065 feat(web): add typed API client auth
refs #81
2026-07-02 08:23:19 +02:00
timothy e6df6ac10a feat(web): add ChicoryTV component primitives
refs #80
2026-07-02 08:09:09 +02:00
timothy e282bcecfa feat(frontend): wire ChicoryTV SPA themes
refs #79
2026-07-02 07:56:12 +02:00
timothy b183c6a154 feat(frontend): scaffold ChicoryTV SPA
refs #78
2026-07-02 07:37:00 +02:00
timothyandClaude Opus 4.8 c0b20a0ac5 docs: add auto-tuning screen + borrowed-concept enrichments to brief
Adds the Auto-tuning wizard as hero screen 5 (#69) and annotates the
Channels-list and Schedule-editor sections + prompts with the borrowed
enrichments: lineup health + resume badge (#72, #68), weighted
distribution / reroll / pad-to-boundary / seasonal (#70, #71, #77, #73).

Refs #59 #69

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 00:45:07 +02:00
timothyandClaude Opus 4.8 482396497e docs: link Create Channel backend gaps to epic #62 (#63-#68)
Refs #59 #62

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 23:02:48 +02:00
timothyandClaude Opus 4.8 4229717575 docs: add Create Channel workflow redesign + backend gaps
Replaces the inherited 4-editor channel-creation chain with a single
library-to-lineup builder: browse/search library with artwork, drag
shows into the lineup, friendly toggles (shuffle, always-on), one image
for logo+bug, technical settings via built-in/custom Channel Templates
with advanced override. Lists prerequisite backend gaps (composite
create endpoint, Channel Templates, library browse API, full image-type
support incl. transparent re-encode, unified logo/bug, always-on vs
on-demand) and a Claude Design prompt for the screen.

Refs #59

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 23:00:09 +02:00
timothyandClaude Opus 4.8 0826198d21 docs: add ChicoryTV UI redesign visual-direction brief (Pass 1)
Records the locked design direction for #59: React SPA on the REST API,
API-first (design pulls the API), Komodo-slick look, ChicoryTV dark +
chicory-blue brand. Includes the 4 hero screens with real domain
vocabulary and ready-to-paste Claude Design prompts.

Refs #59

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 20:58:12 +02:00
timothy a2d2f5930c chore: stop tracking local MCP config
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 2m31s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 3m31s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 3m50s
2026-07-01 19:59:18 +02:00
timothy 45ade1fd78 Merge pull request #56 from issue9-ffmpeg8
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 4m17s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 5m13s
Build ErsatzTV Image / Build & push image (amd64) (push) Has been cancelled
fix(ffmpeg): align transcode pipelines with ffmpeg 8
2026-07-01 17:51:13 +00:00
timothy e170b2dc3c fix(ffmpeg): align transcode pipelines with ffmpeg 8
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m4s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 5m17s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
refs #9
2026-07-01 19:37:51 +02:00
timothy 183f6c5d2a Merge pull request #55 from issue42-jellyfin-musicvideos
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 4m20s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 5m15s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 3m58s
feat(jellyfin): sync MusicVideo libraries
2026-06-30 20:54:20 +00:00
timothy 5560790bcb feat(jellyfin): sync music video libraries refs #42
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 3m53s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 5m4s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
2026-06-30 19:33:06 +02:00
timothy f25cfdb593 feat(api): default-deny mutating API writes
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 4m42s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 5m55s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 3m52s
feat(api): default-deny mutating API writes

Refs #43
2026-06-30 16:55:31 +00:00
timothy 527332a3ac feat(api): default-deny mutating API writes
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m36s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 5m37s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Refs #43
2026-06-30 18:49:35 +02:00
timothy cd20dfb2aa Merge pull request 'test: make channel logo generator testable' (#53) from feature/39-channel-logo-generator-testable into main
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 3m42s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 4m52s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 3m33s
Merge pull request #53 from feature/39-channel-logo-generator-testable

Test channel logo generator path injection
2026-06-30 16:20:48 +00:00
timothy 8e6379a51b test: make channel logo generator testable
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m13s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 5m14s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
refs #39
2026-06-30 18:14:23 +02:00
timothy 4aec234e20 feat(api): standardize FFmpeg profile endpoints
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 4m8s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 5m19s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 4m43s
Merge PR #52: feat(api): standardize FFmpeg profile endpoints

Refs #38
2026-06-30 05:42:06 +00:00
timothy 861827dcbc feat(api): standardize ffmpeg profile endpoints
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m12s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 6m13s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
refs #38
2026-06-30 07:29:47 +02:00
timothy 30ecd9a8a7 Merge pull request 'feat(api): add playout REST endpoints' (#51) from issue37-rest-api-playouts into main
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 3m58s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 4m47s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 4m58s
Merge pull request #51: feat(api): add playout REST endpoints
2026-06-29 18:37:26 +00:00
timothy b53b06c615 feat(api): add playout REST endpoints
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 3m34s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m48s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
fixes #37
2026-06-29 20:31:18 +02:00
timothy 4f8b3042db feat(api): add schedule REST endpoints
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 4m12s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 5m13s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 6m23s
Merge pull request 'feat(api): add schedule REST endpoints' (#50) from feature/36-rest-api-schedules into main
2026-06-29 16:17:40 +00:00
timothy b552905799 feat(api): add schedule REST endpoints
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 3m40s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m52s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Refs #36
2026-06-29 08:13:14 +02:00
timothy 0d101e79b1 Merge pull request 'fix(api): standardize error response contract' (#47) from issue46-rest-api-error-contract into main
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 3m54s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 4m55s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 4m54s
Renovate / Renovate (push) Successful in 49s
Dependency vulnerability scan / NuGet vulnerable packages (push) Successful in 41s
fix(api): standardize error response contract

Refs #46
2026-06-28 14:37:54 +00:00
234 changed files with 31325 additions and 411 deletions
+31
View File
@@ -50,6 +50,37 @@ jobs:
- name: Restore
run: dotnet restore
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '22.x'
cache: npm
cache-dependency-path: web/package-lock.json
- name: Install SPA dependencies
working-directory: web
run: npm ci
- name: Check generated SPA API client
working-directory: web
run: npm run check:api
- name: Lint SPA
working-directory: web
run: npm run lint
- name: Typecheck SPA
working-directory: web
run: npm run typecheck
- name: Test SPA
working-directory: web
run: npm test -- --run
- name: Build SPA
working-directory: web
run: npm run build
- name: Strip Scanner project ref (matches Docker build)
run: sed -i '/Scanner/d' ErsatzTV/ErsatzTV.csproj
+7
View File
@@ -3,9 +3,13 @@
project.lock.json
.DS_Store
*.pyc
.worktrees/
# Claude Code
.mcp/
.mcp.json
.agents/
plugins/
nupkg/
# Visual Studio Code
@@ -48,3 +52,6 @@ scripts/download-test-content.sh
docker-compose.override.yml
ErsatzTV/wwwroot/v2/
ErsatzTV/wwwroot/app/
web/dist/
web/node_modules/
-56
View File
@@ -1,56 +0,0 @@
{
"mcpServers": {
"docker-mcp": {
"command": "uvx",
"args": [
"mcp-server-docker"
],
"env": {
"DOCKER_HOST": "ssh://timothy@192.168.1.99"
}
},
"ssh-mcp": {
"command": "npx",
"args": [
"-y",
"ssh-mcp",
"--",
"--host=192.168.1.99",
"--user=timothy"
],
"env": {}
},
"gitea": {
"command": "gitea-mcp-server",
"args": [
"-t", "stdio",
"-host", "http://192.168.1.95:3000",
"-token", "8341af0733ab9ce084ea7adf38b76aa9ebc3bd67"
],
"env": {}
},
"csharp-lsp": {
"command": "/usr/local/share/dotnet/dotnet",
"args": [
"run",
"--project", "/Users/timothy/ersatztv/.mcp/csharp-lsp-mcp/csharp-lsp-mcp/src/CSharpLspMcp",
"-c", "Release"
],
"env": {
"PATH": "/usr/local/share/dotnet:/Users/timothy/.dotnet/tools:/usr/bin:/bin:/usr/sbin:/sbin"
}
},
"nuget": {
"command": "/usr/local/share/dotnet/dotnet",
"args": [
"dnx",
"NuGet.Mcp.Server",
"--source", "https://api.nuget.org/v3/index.json",
"--yes"
],
"env": {
"DOTNET_ROOT": "/usr/local/share/dotnet"
}
}
}
}
@@ -0,0 +1,5 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.Channels;
public record BulkDeleteChannels(IReadOnlyList<int> ChannelIds) : IRequest<Either<BaseError, Unit>>;
@@ -0,0 +1,62 @@
using System.IO.Abstractions;
using System.Threading.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Channel = ErsatzTV.Core.Domain.Channel;
namespace ErsatzTV.Application.Channels;
public class BulkDeleteChannelsHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> workerChannel,
IFileSystem fileSystem,
ISearchTargets searchTargets)
: IRequestHandler<BulkDeleteChannels, Either<BaseError, Unit>>
{
public async Task<Either<BaseError, Unit>> Handle(
BulkDeleteChannels request,
CancellationToken cancellationToken)
{
if (request.ChannelIds.Count == 0)
{
return Left<BaseError, Unit>(BaseError.New("At least one channel id is required"));
}
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
List<int> channelIds = request.ChannelIds.Distinct().ToList();
List<Channel> channels = await dbContext.Channels
.Where(c => channelIds.Contains(c.Id))
.ToListAsync(cancellationToken);
if (channels.Count != channelIds.Count)
{
var found = channels.Select(c => c.Id).ToHashSet();
int missingId = channelIds.First(id => !found.Contains(id));
return Left<BaseError, Unit>(new NotFoundError($"Channel {missingId} does not exist."));
}
dbContext.Channels.RemoveRange(channels);
await dbContext.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
searchTargets.SearchTargetsChanged();
foreach (Channel channel in channels)
{
string cacheFile = Path.Combine(FileSystemLayout.ChannelGuideCacheFolder, $"{channel.Number}.xml");
if (fileSystem.File.Exists(cacheFile))
{
fileSystem.File.Delete(cacheFile);
}
}
await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
return Right<BaseError, Unit>(Unit.Default);
}
}
@@ -0,0 +1,6 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.Channels;
public record BulkMoveChannelsToGroup(IReadOnlyList<int> ChannelIds, string Group)
: IRequest<Either<BaseError, Unit>>;
@@ -0,0 +1,61 @@
using System.Threading.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.Channels.ChannelValidations;
using Channel = ErsatzTV.Core.Domain.Channel;
namespace ErsatzTV.Application.Channels;
public class BulkMoveChannelsToGroupHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> workerChannel,
ISearchTargets searchTargets)
: IRequestHandler<BulkMoveChannelsToGroup, Either<BaseError, Unit>>
{
public async Task<Either<BaseError, Unit>> Handle(
BulkMoveChannelsToGroup request,
CancellationToken cancellationToken)
{
if (request.ChannelIds.Count == 0)
{
return Left<BaseError, Unit>(BaseError.New("At least one channel id is required"));
}
Validation<BaseError, string> groupValidation = ValidateGroup(request.Group);
if (groupValidation.IsFail)
{
return Left<BaseError, Unit>(groupValidation.FailToSeq().Head());
}
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
List<int> channelIds = request.ChannelIds.Distinct().ToList();
List<Channel> channels = await dbContext.Channels
.Where(c => channelIds.Contains(c.Id))
.ToListAsync(cancellationToken);
if (channels.Count != channelIds.Count)
{
var found = channels.Select(c => c.Id).ToHashSet();
int missingId = channelIds.First(id => !found.Contains(id));
return Left<BaseError, Unit>(new NotFoundError($"Channel {missingId} does not exist."));
}
foreach (Channel channel in channels)
{
channel.Group = request.Group;
}
await dbContext.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
searchTargets.SearchTargetsChanged();
await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
return Right<BaseError, Unit>(Unit.Default);
}
}
@@ -1,6 +1,8 @@
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Channel = ErsatzTV.Core.Domain.Channel;
@@ -14,18 +16,41 @@ public class UpdateChannelNumbersHandler(
{
public async Task<Option<BaseError>> Handle(UpdateChannelNumbers request, CancellationToken cancellationToken)
{
Option<BaseError> validationError = ValidateRequest(request);
if (validationError.IsSome)
{
return validationError;
}
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
try
{
var numberUpdates = request.Channels.ToDictionary(c => c.Id, c => c.Number);
var channelIds = numberUpdates.Keys;
List<int> channelIds = numberUpdates.Keys.ToList();
List<Channel> channelsToUpdate = await dbContext.Channels
.Where(c => channelIds.Contains(c.Id))
.ToListAsync(cancellationToken);
if (channelsToUpdate.Count != channelIds.Count)
{
var found = channelsToUpdate.Select(c => c.Id).ToHashSet();
int missingId = channelIds.First(id => !found.Contains(id));
return new NotFoundError($"Channel {missingId} does not exist.");
}
List<string> requestedNumbers = numberUpdates.Values.ToList();
bool numberConflict = await dbContext.Channels
.AnyAsync(
c => requestedNumbers.Contains(c.Number) && !channelIds.Contains(c.Id),
cancellationToken);
if (numberConflict)
{
return BaseError.New("Channel number must be unique");
}
// give every channel a non-conflicting number
foreach (var channel in channelsToUpdate)
{
@@ -69,4 +94,32 @@ public class UpdateChannelNumbersHandler(
return BaseError.New("Failed to update channel numbers: " + ex.Message);
}
}
private static Option<BaseError> ValidateRequest(UpdateChannelNumbers request)
{
if (request.Channels.Count == 0)
{
return BaseError.New("At least one channel is required");
}
if (request.Channels.Select(c => c.Id).Distinct().Count() != request.Channels.Count)
{
return BaseError.New("Channel ids must be unique");
}
if (request.Channels.Select(c => c.Number).Distinct(StringComparer.Ordinal).Count() != request.Channels.Count)
{
return BaseError.New("Channel number must be unique");
}
foreach (ChannelSortViewModel channel in request.Channels)
{
if (!Regex.IsMatch(channel.Number, Channel.NumberValidator))
{
return BaseError.New("Invalid channel number; two decimals are allowed for subchannels");
}
}
return Option<BaseError>.None;
}
}
+6 -1
View File
@@ -42,10 +42,15 @@ internal static class Mapper
new(
channel.Id,
channel.Number,
channel.SortNumber,
channel.Name,
channel.Group,
channel.Categories,
channel.FFmpegProfile.Name,
channel.PreferredAudioLanguageCode,
GetStreamingMode(channel));
GetStreamingMode(channel),
channel.IsEnabled,
channel.ShowInEpg);
internal static ResolutionViewModel ProjectToViewModel(Resolution resolution) =>
new(resolution.Height, resolution.Width);
@@ -0,0 +1,5 @@
using ErsatzTV.Core.Api.Channels;
namespace ErsatzTV.Application.Channels;
public record GetChannelStatesForApi(DateTime Now) : IRequest<List<ChannelStateResponseModel>>;
@@ -0,0 +1,151 @@
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Interfaces.FFmpeg;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using PlayoutMapper = ErsatzTV.Application.Playouts.Mapper;
namespace ErsatzTV.Application.Channels;
public class GetChannelStatesForApiHandler(
IDbContextFactory<TvContext> dbContextFactory,
IFFmpegSegmenterService ffmpegSegmenterService)
: IRequestHandler<GetChannelStatesForApi, List<ChannelStateResponseModel>>
{
// a guide entry (program + surrounding filler) never spans anywhere near a day; the time
// bound also protects against GuideGroup values recycling (mod 10000) elsewhere in a playout
private static readonly TimeSpan GuideEntryBound = TimeSpan.FromDays(1);
public async Task<List<ChannelStateResponseModel>> Handle(
GetChannelStatesForApi request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
List<Channel> channels = await dbContext.Channels
.AsNoTracking()
.OrderBy(c => c.SortNumber)
.ThenBy(c => c.Number)
.ToListAsync(cancellationToken);
if (channels.Count == 0)
{
return [];
}
Dictionary<int, (int SourceChannelId, TimeSpan Offset, DateTime LookupTime)> channelLookup = channels
.ToDictionary(
c => c.Id,
c =>
{
TimeSpan offset = c.PlayoutOffset ?? TimeSpan.Zero;
return (c.MirrorSourceChannelId ?? c.Id, offset, request.Now - offset);
});
// one covering-item query per distinct lookup time (i.e. per distinct playout offset,
// typically just one) with a cheap projection; metadata is hydrated in a second query
// for only the covering items' guide groups
var coveringBySourceAndTime = new Dictionary<(int SourceChannelId, DateTime LookupTime), CoveringItem>();
foreach (IGrouping<DateTime, (int SourceChannelId, TimeSpan Offset, DateTime LookupTime)> timeGroup in
channelLookup.Values.GroupBy(v => v.LookupTime))
{
DateTime lookupTime = timeGroup.Key;
int[] sourceChannelIds = timeGroup.Map(v => v.SourceChannelId).Distinct().ToArray();
List<CoveringItem> covering = await dbContext.PlayoutItems
.AsNoTracking()
.Where(pi => sourceChannelIds.Contains(pi.Playout.ChannelId))
.Where(pi => pi.Start <= lookupTime && pi.Finish > lookupTime)
.Select(pi => new CoveringItem(pi.Id, pi.PlayoutId, pi.Playout.ChannelId, pi.GuideGroup, pi.Start))
.ToListAsync(cancellationToken);
foreach (CoveringItem item in covering.OrderBy(ci => ci.Start))
{
coveringBySourceAndTime.TryAdd((item.ChannelId, lookupTime), item);
}
}
Dictionary<(int PlayoutId, int GuideGroup), List<PlayoutItem>> itemsByGuideEntry = [];
if (coveringBySourceAndTime.Count > 0)
{
int[] playoutIds = coveringBySourceAndTime.Values.Map(ci => ci.PlayoutId).Distinct().ToArray();
int[] guideGroups = coveringBySourceAndTime.Values.Map(ci => ci.GuideGroup).Distinct().ToArray();
DateTime windowStart = channelLookup.Values.Min(v => v.LookupTime) - GuideEntryBound;
DateTime windowFinish = channelLookup.Values.Max(v => v.LookupTime) + GuideEntryBound;
List<PlayoutItem> guideEntryItems = await dbContext.PlayoutItems
.AsNoTracking()
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as Episode).EpisodeMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as Episode).Season)
.ThenInclude(s => s.Show)
.ThenInclude(s => s.ShowMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as Movie).MovieMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as MusicVideo).MusicVideoMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as MusicVideo).Artist)
.ThenInclude(a => a.ArtistMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as OtherVideo).OtherVideoMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as Song).SongMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as Image).ImageMetadata)
.Include(pi => pi.MediaItem)
.ThenInclude(mi => (mi as RemoteStream).RemoteStreamMetadata)
.Where(pi => playoutIds.Contains(pi.PlayoutId) && guideGroups.Contains(pi.GuideGroup))
.Where(pi => pi.Start <= windowFinish && pi.Finish > windowStart)
.ToListAsync(cancellationToken);
itemsByGuideEntry = guideEntryItems
.GroupBy(pi => (pi.PlayoutId, pi.GuideGroup))
.ToDictionary(g => g.Key, g => g.OrderBy(pi => pi.Start).ToList());
}
return channels
.Map(channel =>
{
(int sourceChannelId, TimeSpan offset, DateTime lookupTime) = channelLookup[channel.Id];
ChannelNowPlayingResponseModel nowPlaying = null;
if (coveringBySourceAndTime.TryGetValue((sourceChannelId, lookupTime), out CoveringItem covering) &&
itemsByGuideEntry.TryGetValue(
(covering.PlayoutId, covering.GuideGroup),
out List<PlayoutItem> guideEntry))
{
// like the XMLTV guide, surface the program rather than its filler: use the
// covering item itself when it is a program part, otherwise the guide entry's
// first program item; an entry with no program item (e.g. offline fallback
// filler) stays null
PlayoutItem coveringItem = guideEntry.Find(pi => pi.Id == covering.Id);
PlayoutItem displayItem = coveringItem?.FillerKind == FillerKind.None
? coveringItem
: guideEntry.Find(pi => pi.FillerKind == FillerKind.None);
if (displayItem is not null)
{
DateTime start = guideEntry[0].Start;
DateTime finish = displayItem.GuideFinish ?? guideEntry.Max(pi => pi.Finish);
nowPlaying = new ChannelNowPlayingResponseModel(
PlayoutMapper.GetDisplayTitle(displayItem.MediaItem, Optional(displayItem.ChapterTitle)),
new DateTimeOffset(start + offset, TimeSpan.Zero),
new DateTimeOffset(finish + offset, TimeSpan.Zero));
}
}
return new ChannelStateResponseModel(
channel.Id,
channel.Number,
ffmpegSegmenterService.IsActive(channel.Number),
nowPlaying);
})
.ToList();
}
private sealed record CoveringItem(int Id, int PlayoutId, int ChannelId, int GuideGroup, DateTime Start);
}
@@ -1,5 +1,6 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -24,8 +25,15 @@ public class CreateFFmpegProfileHandler :
CancellationToken cancellationToken)
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, FFmpegProfile> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(profile => PersistFFmpegProfile(dbContext, profile));
Option<int> maybeResolutionId = await ResolutionMustExist(dbContext, request, cancellationToken);
return await maybeResolutionId.Match(
Some: async resolutionId =>
{
Validation<BaseError, FFmpegProfile> validation = Validate(request, resolutionId);
return await validation.Apply(profile => PersistFFmpegProfile(dbContext, profile));
},
None: () => Task.FromResult<Either<BaseError, CreateFFmpegProfileResult>>(
new NotFoundError($"[Resolution] {request.ResolutionId} does not exist")));
}
private async Task<CreateFFmpegProfileResult> PersistFFmpegProfile(
@@ -38,13 +46,11 @@ public class CreateFFmpegProfileHandler :
return new CreateFFmpegProfileResult(ffmpegProfile.Id);
}
private static async Task<Validation<BaseError, FFmpegProfile>> Validate(
TvContext dbContext,
private static Validation<BaseError, FFmpegProfile> Validate(
CreateFFmpegProfile request,
CancellationToken cancellationToken) =>
(ValidateName(request), ValidateThreadCount(request),
await ResolutionMustExist(dbContext, request, cancellationToken))
.Apply((name, threadCount, resolutionId) =>
int resolutionId) =>
(ValidateName(request), ValidateThreadCount(request))
.Apply((name, threadCount) =>
{
var hwAccel = request.NormalizeVideo
? request.HardwareAcceleration
@@ -110,12 +116,11 @@ public class CreateFFmpegProfileHandler :
private static Validation<BaseError, int> ValidateThreadCount(CreateFFmpegProfile createFFmpegProfile) =>
createFFmpegProfile.AtLeast(0)(p => p.ThreadCount);
private static Task<Validation<BaseError, int>> ResolutionMustExist(
private static Task<Option<int>> ResolutionMustExist(
TvContext dbContext,
CreateFFmpegProfile createFFmpegProfile,
CancellationToken cancellationToken) =>
dbContext.Resolutions
.SelectOneAsync(r => r.Id, r => r.Id == createFFmpegProfile.ResolutionId, cancellationToken)
.MapT(r => r.Id)
.Map(o => o.ToValidation<BaseError>($"[Resolution] {createFFmpegProfile.ResolutionId} does not exist"));
.MapT(r => r.Id);
}
@@ -1,5 +1,6 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Infrastructure.Data;
@@ -19,8 +20,19 @@ public class DeleteFFmpegProfileHandler(
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, FFmpegProfile> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(p => DoDeletion(dbContext, p));
Option<FFmpegProfile> maybeProfile = await FFmpegProfileMustExist(dbContext, request, cancellationToken);
return await maybeProfile.Match(
Some: async profile =>
{
Validation<BaseError, FFmpegProfile> validation = await Validate(
dbContext,
request,
profile,
cancellationToken);
return await validation.Apply(p => DoDeletion(dbContext, p));
},
None: () => Task.FromResult<Either<BaseError, Unit>>(
new NotFoundError($"FFmpegProfile {request.FFmpegProfileId} does not exist")));
}
private async Task<Unit> DoDeletion(TvContext dbContext, FFmpegProfile ffmpegProfile)
@@ -34,19 +46,18 @@ public class DeleteFFmpegProfileHandler(
private async Task<Validation<BaseError, FFmpegProfile>> Validate(
TvContext dbContext,
DeleteFFmpegProfile request,
FFmpegProfile profile,
CancellationToken cancellationToken) =>
(await FFmpegProfileMustNotBeUsed(dbContext, request, cancellationToken),
await FFmpegProfileMustNotBeDefault(request, cancellationToken),
await FFmpegProfileMustExist(dbContext, request, cancellationToken))
.Apply((_, _, ffmpegProfile) => ffmpegProfile);
await FFmpegProfileMustNotBeDefault(request, cancellationToken))
.Apply((_, _) => profile);
private static Task<Validation<BaseError, FFmpegProfile>> FFmpegProfileMustExist(
private static Task<Option<FFmpegProfile>> FFmpegProfileMustExist(
TvContext dbContext,
DeleteFFmpegProfile request,
CancellationToken cancellationToken) =>
dbContext.FFmpegProfiles
.SelectOneAsync(p => p.Id, p => p.Id == request.FFmpegProfileId, cancellationToken)
.Map(o => o.ToValidation<BaseError>($"FFmpegProfile {request.FFmpegProfileId} does not exist"));
.SelectOneAsync(p => p.Id, p => p.Id == request.FFmpegProfileId, cancellationToken);
private static async Task<Validation<BaseError, Unit>> FFmpegProfileMustNotBeUsed(
TvContext dbContext,
@@ -1,5 +1,6 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.FFmpeg;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.FFmpeg.Preset;
@@ -17,8 +18,22 @@ public class UpdateFFmpegProfileHandler(IDbContextFactory<TvContext> dbContextFa
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, FFmpegProfile> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(p => ApplyUpdateRequest(dbContext, p, request, cancellationToken));
Option<FFmpegProfile> maybeProfile = await FFmpegProfileMustExist(dbContext, request, cancellationToken);
return await maybeProfile.Match(
Some: async profile =>
{
Option<int> maybeResolutionId = await ResolutionMustExist(dbContext, request, cancellationToken);
return await maybeResolutionId.Match(
Some: async _ =>
{
Validation<BaseError, FFmpegProfile> validation = await Validate(dbContext, request, profile);
return await validation.Apply(p => ApplyUpdateRequest(dbContext, p, request, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, UpdateFFmpegProfileResult>>(
new NotFoundError($"[Resolution] {request.ResolutionId} does not exist")));
},
None: () => Task.FromResult<Either<BaseError, UpdateFFmpegProfileResult>>(
new NotFoundError("FFmpegProfile does not exist.")));
}
private async Task<UpdateFFmpegProfileResult> ApplyUpdateRequest(
@@ -109,20 +124,16 @@ public class UpdateFFmpegProfileHandler(IDbContextFactory<TvContext> dbContextFa
private static async Task<Validation<BaseError, FFmpegProfile>> Validate(
TvContext dbContext,
UpdateFFmpegProfile request,
CancellationToken cancellationToken) =>
(await FFmpegProfileMustExist(dbContext, request, cancellationToken),
await ValidateName(dbContext, request),
ValidateThreadCount(request),
await ResolutionMustExist(dbContext, request, cancellationToken))
.Apply((ffmpegProfileToUpdate, _, _, _) => ffmpegProfileToUpdate);
FFmpegProfile profile) =>
(await ValidateName(dbContext, request), ValidateThreadCount(request))
.Apply((_, _) => profile);
private static Task<Validation<BaseError, FFmpegProfile>> FFmpegProfileMustExist(
private static Task<Option<FFmpegProfile>> FFmpegProfileMustExist(
TvContext dbContext,
UpdateFFmpegProfile updateFFmpegProfile,
CancellationToken cancellationToken) =>
dbContext.FFmpegProfiles
.SelectOneAsync(p => p.Id, p => p.Id == updateFFmpegProfile.FFmpegProfileId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("FFmpegProfile does not exist."));
.SelectOneAsync(p => p.Id, p => p.Id == updateFFmpegProfile.FFmpegProfileId, cancellationToken);
private static async Task<Validation<BaseError, string>> ValidateName(
TvContext dbContext,
@@ -147,12 +158,11 @@ public class UpdateFFmpegProfileHandler(IDbContextFactory<TvContext> dbContextFa
private static Validation<BaseError, int> ValidateThreadCount(UpdateFFmpegProfile updateFFmpegProfile) =>
updateFFmpegProfile.AtLeast(0)(p => p.ThreadCount);
private static Task<Validation<BaseError, int>> ResolutionMustExist(
private static Task<Option<int>> ResolutionMustExist(
TvContext dbContext,
UpdateFFmpegProfile updateFFmpegProfile,
CancellationToken cancellationToken) =>
dbContext.Resolutions
.SelectOneAsync(r => r.Id, r => r.Id == updateFFmpegProfile.ResolutionId, cancellationToken)
.MapT(r => r.Id)
.Map(o => o.ToValidation<BaseError>($"[Resolution] {updateFFmpegProfile.ResolutionId} does not exist"));
.MapT(r => r.Id);
}
@@ -2,6 +2,7 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -28,8 +29,23 @@ public class CreateClassicPlayoutHandler : IRequestHandler<CreateClassicPlayout,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Playout> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(playout => PersistPlayout(dbContext, playout));
Option<Channel> maybeChannel = await GetChannel(dbContext, request, cancellationToken);
return await maybeChannel.Match(
Some: async channel =>
{
Option<ProgramSchedule> maybeProgramSchedule =
await GetProgramSchedule(dbContext, request, cancellationToken);
return await maybeProgramSchedule.Match(
Some: async programSchedule =>
{
Validation<BaseError, Playout> validation = Validate(request, channel, programSchedule);
return await validation.Apply(playout => PersistPlayout(dbContext, playout));
},
None: () => Task.FromResult<Either<BaseError, CreatePlayoutResponse>>(
new NotFoundError("Program schedule does not exist")));
},
None: () => Task.FromResult<Either<BaseError, CreatePlayoutResponse>>(
new NotFoundError("Channel does not exist")));
}
private async Task<CreatePlayoutResponse> PersistPlayout(TvContext dbContext, Playout playout)
@@ -46,12 +62,12 @@ public class CreateClassicPlayoutHandler : IRequestHandler<CreateClassicPlayout,
return new CreatePlayoutResponse(playout.Id);
}
private static async Task<Validation<BaseError, Playout>> Validate(
TvContext dbContext,
private static Validation<BaseError, Playout> Validate(
CreateClassicPlayout request,
CancellationToken cancellationToken) =>
(await ValidateChannel(dbContext, request, cancellationToken),
await ValidateProgramSchedule(dbContext, request, cancellationToken),
Channel channel,
ProgramSchedule programSchedule) =>
(ChannelMustNotHavePlayouts(channel),
ProgramScheduleMustHaveItems(programSchedule),
ValidateScheduleKind(request))
.Apply((channel, programSchedule, scheduleKind) => new Playout
{
@@ -60,15 +76,13 @@ public class CreateClassicPlayoutHandler : IRequestHandler<CreateClassicPlayout,
ScheduleKind = scheduleKind
});
private static Task<Validation<BaseError, Channel>> ValidateChannel(
private static Task<Option<Channel>> GetChannel(
TvContext dbContext,
CreateClassicPlayout createClassicPlayout,
CancellationToken cancellationToken) =>
dbContext.Channels
.Include(c => c.Playouts)
.SelectOneAsync(c => c.Id, c => c.Id == createClassicPlayout.ChannelId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("Channel does not exist"))
.BindT(ChannelMustNotHavePlayouts);
.SelectOneAsync(c => c.Id, c => c.Id == createClassicPlayout.ChannelId, cancellationToken);
private static Validation<BaseError, Channel> ChannelMustNotHavePlayouts(Channel channel) =>
Optional(channel.Playouts.Count)
@@ -76,15 +90,13 @@ public class CreateClassicPlayoutHandler : IRequestHandler<CreateClassicPlayout,
.Map(_ => channel)
.ToValidation<BaseError>("Channel already has one playout");
private static Task<Validation<BaseError, ProgramSchedule>> ValidateProgramSchedule(
private static Task<Option<ProgramSchedule>> GetProgramSchedule(
TvContext dbContext,
CreateClassicPlayout createClassicPlayout,
CancellationToken cancellationToken) =>
dbContext.ProgramSchedules
.Include(ps => ps.Items)
.SelectOneAsync(ps => ps.Id, ps => ps.Id == createClassicPlayout.ProgramScheduleId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("Program schedule does not exist"))
.BindT(ProgramScheduleMustHaveItems);
.SelectOneAsync(ps => ps.Id, ps => ps.Id == createClassicPlayout.ProgramScheduleId, cancellationToken);
private static Validation<BaseError, ProgramSchedule> ProgramScheduleMustHaveItems(
ProgramSchedule programSchedule) =>
@@ -3,6 +3,7 @@ using System.Threading.Channels;
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Notifications;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -45,6 +46,6 @@ public class DeletePlayoutHandler(
return maybePlayout
.Map(_ => Unit.Default)
.ToEither(BaseError.New($"Playout {request.PlayoutId} does not exist."));
.ToEither<BaseError>(new NotFoundError($"Playout {request.PlayoutId} does not exist."));
}
}
@@ -2,6 +2,7 @@
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
@@ -28,8 +29,16 @@ public class AddProgramScheduleItemHandler : ProgramScheduleItemCommandBase,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(ps => PersistItem(dbContext, request, ps, cancellationToken));
Option<ProgramSchedule> maybeProgramSchedule =
await ProgramScheduleMustExist(dbContext, request.ProgramScheduleId, cancellationToken);
return await maybeProgramSchedule.Match(
Some: async programSchedule =>
{
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, programSchedule);
return await validation.Apply(ps => PersistItem(dbContext, request, ps, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, ProgramScheduleItemViewModel>>(
new NotFoundError("[ProgramScheduleId] does not exist.")));
}
private async Task<ProgramScheduleItemViewModel> PersistItem(
@@ -54,10 +63,25 @@ public class AddProgramScheduleItemHandler : ProgramScheduleItemCommandBase,
return ProjectToViewModel(item);
}
private static Task<Validation<BaseError, ProgramSchedule>> Validate(
private static async Task<Validation<BaseError, ProgramSchedule>> Validate(
TvContext dbContext,
AddProgramScheduleItem request,
CancellationToken cancellationToken) =>
ProgramScheduleMustExist(dbContext, request.ProgramScheduleId, cancellationToken)
.BindT(programSchedule => PlayoutModeMustBeValid(request, programSchedule));
ProgramSchedule programSchedule)
{
Validation<BaseError, ProgramSchedule> validation =
PlayoutModeMustBeValid(request, programSchedule)
.Bind(programSchedule => CollectionTypeMustBeValid(request, programSchedule));
return await validation.ToEither().Match(
Left: error => Task.FromResult<Validation<BaseError, ProgramSchedule>>(
Fail<BaseError, ProgramSchedule>(error)),
Right: async validProgramSchedule =>
{
Either<BaseError, ProgramSchedule> fillerResult = await FillerConfigurationMustBeValid(
dbContext,
request,
validProgramSchedule);
return fillerResult.ToValidation();
});
}
}
@@ -1,5 +1,6 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
@@ -18,11 +19,14 @@ public class DeleteProgramScheduleHandler : IRequestHandler<DeleteProgramSchedul
CancellationToken cancellationToken)
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, ProgramSchedule> validation = await ProgramScheduleMustExist(
Option<ProgramSchedule> maybeProgramSchedule = await ProgramScheduleMustExist(
dbContext,
request,
cancellationToken);
return await validation.Apply(ps => DoDeletion(dbContext, ps));
return await maybeProgramSchedule.Match(
Some: programSchedule => DoDeletion(dbContext, programSchedule).Map(Right<BaseError, Unit>),
None: () => Task.FromResult<Either<BaseError, Unit>>(
new NotFoundError($"ProgramSchedule {request.ProgramScheduleId} does not exist.")));
}
private static Task<Unit> DoDeletion(TvContext dbContext, ProgramSchedule programSchedule)
@@ -31,11 +35,11 @@ public class DeleteProgramScheduleHandler : IRequestHandler<DeleteProgramSchedul
return dbContext.SaveChangesAsync().ToUnit();
}
private static Task<Validation<BaseError, ProgramSchedule>> ProgramScheduleMustExist(
private static Task<Option<ProgramSchedule>> ProgramScheduleMustExist(
TvContext dbContext,
DeleteProgramSchedule request,
CancellationToken cancellationToken) =>
dbContext.ProgramSchedules
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.ProgramScheduleId, cancellationToken)
.Map(o => o.ToValidation<BaseError>($"ProgramSchedule {request.ProgramScheduleId} does not exist."));
.Map(identity);
}
@@ -0,0 +1,6 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.ProgramSchedules;
public record DeleteProgramScheduleItem(int ProgramScheduleId, int ProgramScheduleItemId)
: IRequest<Either<BaseError, Unit>>;
@@ -0,0 +1,46 @@
using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.ProgramSchedules;
public class DeleteProgramScheduleItemHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> channel) : IRequestHandler<DeleteProgramScheduleItem, Either<BaseError, Unit>>
{
public async Task<Either<BaseError, Unit>> Handle(
DeleteProgramScheduleItem request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
ProgramScheduleItem item = await dbContext.ProgramScheduleItems
.Include(i => i.ProgramSchedule)
.ThenInclude(ps => ps.Playouts)
.SingleOrDefaultAsync(
i => i.Id == request.ProgramScheduleItemId && i.ProgramScheduleId == request.ProgramScheduleId,
cancellationToken);
if (item is null)
{
return new NotFoundError(
$"ProgramScheduleItem {request.ProgramScheduleItemId} does not exist on schedule {request.ProgramScheduleId}.");
}
List<Playout> playouts = item.ProgramSchedule.Playouts;
dbContext.ProgramScheduleItems.Remove(item);
await dbContext.SaveChangesAsync(cancellationToken);
foreach (Playout playout in playouts)
{
await channel.WriteAsync(new BuildPlayout(playout.Id, PlayoutBuildMode.Refresh), cancellationToken);
}
return Unit.Default;
}
}
@@ -1,6 +1,7 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
@@ -9,7 +10,7 @@ namespace ErsatzTV.Application.ProgramSchedules;
public abstract class ProgramScheduleItemCommandBase
{
protected static Task<Validation<BaseError, ProgramSchedule>> ProgramScheduleMustExist(
protected static Task<Option<ProgramSchedule>> ProgramScheduleMustExist(
TvContext dbContext,
int programScheduleId,
CancellationToken cancellationToken) =>
@@ -17,7 +18,7 @@ public abstract class ProgramScheduleItemCommandBase
.Include(ps => ps.Items)
.Include(ps => ps.Playouts)
.SelectOneAsync(ps => ps.Id, ps => ps.Id == programScheduleId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("[ProgramScheduleId] does not exist."));
.Map(identity);
protected static async Task<Either<BaseError, ProgramSchedule>> FillerConfigurationMustBeValid(
TvContext dbContext,
@@ -352,9 +353,11 @@ public abstract class ProgramScheduleItemCommandBase
_ => throw new NotSupportedException($"Unsupported playout mode {item.PlayoutMode}")
};
result.ProgramScheduleItemWatermarks = [];
result.ProgramScheduleItemGraphicsElements = [];
foreach (int watermarkId in item.WatermarkIds)
{
result.ProgramScheduleItemWatermarks ??= [];
result.ProgramScheduleItemWatermarks.Add(
new ProgramScheduleItemWatermark
{
@@ -365,7 +368,6 @@ public abstract class ProgramScheduleItemCommandBase
foreach (int graphicsElementId in item.GraphicsElementIds)
{
result.ProgramScheduleItemGraphicsElements ??= [];
result.ProgramScheduleItemGraphicsElements.Add(
new ProgramScheduleItemGraphicsElement
{
@@ -2,6 +2,7 @@
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
@@ -19,8 +20,16 @@ public class ReplaceProgramScheduleItemsHandler(
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(ps => PersistItems(dbContext, request, ps, cancellationToken));
Option<ProgramSchedule> maybeProgramSchedule =
await ProgramScheduleMustExist(dbContext, request.ProgramScheduleId, cancellationToken);
return await maybeProgramSchedule.Match(
Some: async programSchedule =>
{
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, programSchedule);
return await validation.Apply(ps => PersistItems(dbContext, request, ps, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>>>(
new NotFoundError("[ProgramScheduleId] does not exist.")));
}
private async Task<IEnumerable<ProgramScheduleItemViewModel>> PersistItems(
@@ -50,15 +59,20 @@ public class ReplaceProgramScheduleItemsHandler(
return programSchedule.Items.Map(ProjectToViewModel);
}
private static Task<Validation<BaseError, ProgramSchedule>> Validate(
private static async Task<Validation<BaseError, ProgramSchedule>> Validate(
TvContext dbContext,
ReplaceProgramScheduleItems request,
CancellationToken cancellationToken) =>
ProgramScheduleMustExist(dbContext, request.ProgramScheduleId, cancellationToken)
.BindT(programSchedule => PlayoutModesMustBeValid(request, programSchedule))
.BindT(programSchedule => CollectionTypesMustBeValid(request, programSchedule))
.BindT(programSchedule => PlaybackOrdersMustBeValid(request, programSchedule))
.BindT(programSchedule => FillerConfigurationsMustBeValid(dbContext, request, programSchedule));
ProgramSchedule programSchedule)
{
Validation<BaseError, ProgramSchedule> validation = PlayoutModesMustBeValid(request, programSchedule)
.Bind(programSchedule => CollectionTypesMustBeValid(request, programSchedule))
.Bind(programSchedule => PlaybackOrdersMustBeValid(request, programSchedule));
return await validation.ToEither().Match(
Left: error => Task.FromResult<Validation<BaseError, ProgramSchedule>>(
Fail<BaseError, ProgramSchedule>(error)),
Right: validProgramSchedule => FillerConfigurationsMustBeValid(dbContext, request, validProgramSchedule));
}
private static Validation<BaseError, ProgramSchedule> PlayoutModesMustBeValid(
ReplaceProgramScheduleItems request,
@@ -2,6 +2,7 @@
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -20,8 +21,16 @@ public class UpdateProgramScheduleHandler(
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(ps => ApplyUpdateRequest(dbContext, ps, request));
Option<ProgramSchedule> maybeProgramSchedule =
await ProgramScheduleMustExist(dbContext, request, cancellationToken);
return await maybeProgramSchedule.Match(
Some: async programSchedule =>
{
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, programSchedule, cancellationToken);
return await validation.Apply(ps => ApplyUpdateRequest(dbContext, ps, request));
},
None: () => Task.FromResult<Either<BaseError, UpdateProgramScheduleResult>>(
new NotFoundError("Schedule does not exist")));
}
private async Task<UpdateProgramScheduleResult> ApplyUpdateRequest(
@@ -66,17 +75,17 @@ public class UpdateProgramScheduleHandler(
private static async Task<Validation<BaseError, ProgramSchedule>> Validate(
TvContext dbContext,
UpdateProgramSchedule request,
ProgramSchedule programSchedule,
CancellationToken cancellationToken) =>
(await ProgramScheduleMustExist(dbContext, request, cancellationToken), await ValidateName(dbContext, request, cancellationToken))
.Apply((programSchedule, _) => programSchedule);
(await ValidateName(dbContext, request, cancellationToken)).Map(_ => programSchedule);
private static Task<Validation<BaseError, ProgramSchedule>> ProgramScheduleMustExist(
private static Task<Option<ProgramSchedule>> ProgramScheduleMustExist(
TvContext dbContext,
UpdateProgramSchedule request,
CancellationToken cancellationToken) =>
dbContext.ProgramSchedules
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.ProgramScheduleId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("Schedule does not exist"));
.Map(identity);
private static async Task<Validation<BaseError, string>> ValidateName(
TvContext dbContext,
@@ -32,4 +32,9 @@
<ProjectReference Include="..\ErsatzTV.Infrastructure\ErsatzTV.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="..\ErsatzTV\Resources\Fonts\Sen.ttf" Link="Resources\Fonts\Sen.ttf" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\ErsatzTV\wwwroot\images\ersatztv-500.png" Link="Resources\Images\ersatztv-500.png" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -0,0 +1,41 @@
using ErsatzTV.Core.Images;
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
using Shouldly;
using SkiaSharp;
namespace ErsatzTV.Core.Tests.Images;
[TestFixture]
public class ChannelLogoGeneratorTests
{
[TestCase("News", 100, 200)]
[TestCase("A Very Long Channel Name That Should Force Font Shrinking", 100, 200)]
[TestCase("Tall Logo", 180, 120)]
public void GenerateChannelLogo_WithInjectedAssets_ReturnsValidPngWithRequestedDimensions(
string text,
int logoHeight,
int logoWidth)
{
var generator = new ChannelLogoGenerator(
NullLogger<ChannelLogoGenerator>.Instance,
TestAssetPath("Resources", "Images", "ersatztv-500.png"),
TestAssetPath("Resources", "Fonts", "Sen.ttf"));
byte[] bytes = generator.GenerateChannelLogo(text, logoHeight, logoWidth, CancellationToken.None)
.Match(
Left: error => throw new AssertionException(error.Value),
Right: identity);
using var stream = new MemoryStream(bytes);
using var codec = SKCodec.Create(stream);
codec.ShouldNotBeNull();
codec.EncodedFormat.ShouldBe(SKEncodedImageFormat.Png);
codec.Info.Width.ShouldBe(logoWidth);
codec.Info.Height.ShouldBe(logoHeight);
}
private static string TestAssetPath(params string[] segments) =>
Path.Combine([TestContext.CurrentContext.TestDirectory, .. segments]);
}
@@ -0,0 +1,8 @@
namespace ErsatzTV.Core.Api.Channels;
#nullable enable
public record ChannelNowPlayingResponseModel(
string Title,
DateTimeOffset StartUtc,
DateTimeOffset FinishUtc);
@@ -5,8 +5,13 @@ namespace ErsatzTV.Core.Api.Channels;
public record ChannelResponseModel(
int Id,
string Number,
double SortNumber,
string Name,
string Group,
string Categories,
[property: JsonProperty("ffmpegProfile")]
string FFmpegProfile,
string Language,
string StreamingMode);
string StreamingMode,
bool IsEnabled,
bool ShowInEpg);
@@ -0,0 +1,9 @@
namespace ErsatzTV.Core.Api.Channels;
#nullable enable
public record ChannelStateResponseModel(
int ChannelId,
string ChannelNumber,
bool OnAir,
ChannelNowPlayingResponseModel? NowPlaying);
@@ -0,0 +1,33 @@
using ErsatzTV.Core.Domain;
namespace ErsatzTV.Core.Api.Playouts;
public record PlayoutResponseModel(
int Id,
PlayoutScheduleKind ScheduleKind,
string ChannelName,
string ChannelNumber,
ChannelPlayoutMode PlayoutMode,
string ScheduleName,
string ScheduleFile,
TimeSpan? DailyRebuildTime)
{
public static PlayoutResponseModel From(
int id,
PlayoutScheduleKind scheduleKind,
string channelName,
string channelNumber,
ChannelPlayoutMode playoutMode,
string scheduleName,
string scheduleFile,
TimeSpan? dailyRebuildTime) =>
new(
id,
scheduleKind,
channelName,
channelNumber,
playoutMode,
scheduleName,
scheduleFile,
dailyRebuildTime);
}
+23 -5
View File
@@ -10,11 +10,25 @@ public class ChannelLogoGenerator : IChannelLogoGenerator
public const string GetRoute = "/iptv/logos/gen";
public const string GetRouteQueryParamName = "text";
private readonly string _fontPath;
private readonly ILogger _logger;
private readonly string _overlayImagePath;
public ChannelLogoGenerator(
ILogger<ChannelLogoGenerator> logger) =>
ILogger<ChannelLogoGenerator> logger)
: this(logger, DefaultOverlayImagePath(), DefaultFontPath())
{
}
public ChannelLogoGenerator(
ILogger<ChannelLogoGenerator> logger,
string overlayImagePath,
string fontPath)
{
_logger = logger;
_overlayImagePath = overlayImagePath;
_fontPath = fontPath;
}
public Either<BaseError, byte[]> GenerateChannelLogo(
string text,
@@ -29,13 +43,11 @@ public class ChannelLogoGenerator : IChannelLogoGenerator
canvas.Clear(SKColors.Black);
//etv logo
string overlayImagePath = Path.Combine("wwwroot", "images", "ersatztv-500.png");
using var overlayImage = SKBitmap.Decode(overlayImagePath);
using var overlayImage = SKBitmap.Decode(_overlayImagePath);
canvas.DrawBitmap(overlayImage, new SKRect(155, 60, 205, 110));
//Custom Font
string fontPath = Path.Combine(FileSystemLayout.ResourcesCacheFolder, "Sen.ttf");
using var fontTypeface = SKTypeface.FromFile(fontPath);
using var fontTypeface = SKTypeface.FromFile(_fontPath);
var fontSize = 30;
var font = new SKFont
{
@@ -80,4 +92,10 @@ public class ChannelLogoGenerator : IChannelLogoGenerator
public static string GenerateChannelLogoUrl(Channel channel) =>
$"http://localhost:{Settings.StreamingPort}{GetRoute}?{GetRouteQueryParamName}={channel.WebEncodedName}";
private static string DefaultFontPath() =>
Path.Combine(FileSystemLayout.ResourcesCacheFolder, "Sen.ttf");
private static string DefaultOverlayImagePath() =>
Path.Combine("wwwroot", "images", "ersatztv-500.png");
}
@@ -13,6 +13,11 @@ public interface IJellyfinApiClient
string authorizationHeader,
JellyfinLibrary library);
IAsyncEnumerable<Tuple<MusicVideo, int>> GetMusicVideoLibraryItems(
string address,
string authorizationHeader,
JellyfinLibrary library);
IAsyncEnumerable<Tuple<JellyfinShow, int>> GetShowLibraryItemsWithoutPeople(
string address,
string authorizationHeader,
@@ -0,0 +1,13 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Jellyfin;
namespace ErsatzTV.Core.Interfaces.Jellyfin;
public interface IJellyfinMusicVideoLibraryScanner
{
Task<Either<BaseError, Unit>> ScanLibrary(
JellyfinConnectionParameters connectionParameters,
JellyfinLibrary library,
bool deepScan,
CancellationToken cancellationToken);
}
@@ -0,0 +1,38 @@
using ErsatzTV.FFmpeg.Capabilities;
using ErsatzTV.FFmpeg.GlobalOption.HardwareAcceleration;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
namespace ErsatzTV.FFmpeg.Tests.GlobalOption.HardwareAcceleration;
[TestFixture]
public class QsvHardwareAccelerationOptionTests
{
[Test]
public void GlobalOptions_WithDevice_ShouldDeriveQsvDeviceFromVaapiDevice()
{
var option = new QsvHardwareAccelerationOption("/dev/dri/renderD128", FFmpegCapability.Software);
option.GlobalOptions.ShouldBe(
[
"-init_hw_device", "vaapi=va:/dev/dri/renderD128",
"-init_hw_device", "qsv=hw@va",
"-filter_hw_device", "hw"
]);
}
[Test]
public void GlobalOptions_WithHardwareDecode_ShouldEnableQsvHwaccel()
{
var option = new QsvHardwareAccelerationOption(None, FFmpegCapability.Hardware);
option.GlobalOptions.ShouldBe(
[
"-hwaccel", "qsv",
"-hwaccel_output_format", "qsv",
"-init_hw_device", "qsv=hw",
"-filter_hw_device", "hw"
]);
}
}
@@ -16,8 +16,6 @@ public class QsvHardwareAccelerationOption(Option<string> device, FFmpegCapabili
{
get
{
string[] initDevices = ["-init_hw_device", "qsv=hw", "-filter_hw_device", "hw"];
var result = new List<string>
{
"-hwaccel", "qsv",
@@ -29,18 +27,26 @@ public class QsvHardwareAccelerationOption(Option<string> device, FFmpegCapabili
result.Clear();
}
if (OperatingSystem.IsLinux())
var deviceConfigured = false;
foreach (string qsvDevice in device)
{
foreach (string qsvDevice in device)
if (!string.IsNullOrWhiteSpace(qsvDevice))
{
if (!string.IsNullOrWhiteSpace(qsvDevice))
{
result.AddRange(new[] { "-qsv_device", qsvDevice });
}
result.AddRange(
[
"-init_hw_device", $"vaapi=va:{qsvDevice}",
"-init_hw_device", "qsv=hw@va"
]);
deviceConfigured = true;
}
}
result.AddRange(initDevices);
if (!deviceConfigured)
{
result.AddRange(["-init_hw_device", "qsv=hw"]);
}
result.AddRange(["-filter_hw_device", "hw"]);
return result.ToArray();
}
@@ -0,0 +1,73 @@
using System.Net;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Jellyfin;
using ErsatzTV.Core.Interfaces.Metadata;
using ErsatzTV.Infrastructure.Jellyfin;
using LanguageExt;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Infrastructure.Tests.Jellyfin;
public class JellyfinApiClientTests
{
[TestFixture]
public class GetLibraries
{
[Test]
public async Task Should_Project_MusicVideo_Libraries()
{
const string response = """
[
{
"Name": "Concerts",
"CollectionType": "musicvideos",
"ItemId": "library-1",
"LibraryOptions": {
"PathInfos": []
}
}
]
""";
var client = new JellyfinApiClient(
new MemoryCache(new MemoryCacheOptions()),
Substitute.For<IJellyfinPathReplacementService>(),
Substitute.For<IFallbackMetadataProvider>(),
new SingleResponseHttpClientFactory(response),
Substitute.For<ILogger<JellyfinApiClient>>());
Either<BaseError, List<JellyfinLibrary>> result =
await client.GetLibraries("http://jellyfin.example", "MediaBrowser Token=abc");
result.IsRight.ShouldBeTrue();
List<JellyfinLibrary> libraries = result.RightToSeq().Single();
libraries.Count.ShouldBe(1);
libraries[0].Name.ShouldBe("Concerts");
libraries[0].ItemId.ShouldBe("library-1");
libraries[0].MediaKind.ShouldBe(LibraryMediaKind.MusicVideos);
libraries[0].ShouldSyncItems.ShouldBeFalse();
libraries[0].Paths.Single().Path.ShouldBe("jellyfin://library-1");
}
}
private sealed class SingleResponseHttpClientFactory(string response) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => new(new SingleResponseHttpMessageHandler(response));
}
private sealed class SingleResponseHttpMessageHandler(string response) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) =>
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(response)
});
}
}
@@ -42,6 +42,26 @@ public interface IJellyfinApi
[Query]
int limit = 0);
[Get("/Items?sortOrder=Ascending&sortBy=SortName")]
Task<JellyfinLibraryItemsResponse> GetMusicVideoLibraryItems(
[Header("Authorization")]
string authorizationHeader,
[Query]
string parentId,
[Query]
string fields =
"Path,Genres,Artists,Tags,DateCreated,Etag,Overview,Studios,People,OfficialRating,ProviderIds,Chapters",
[Query]
string includeItemTypes = "MusicVideo",
[Query]
bool recursive = true,
[Query]
string filters = "IsNotFolder",
[Query]
int startIndex = 0,
[Query]
int limit = 0);
[Get("/Items?sortOrder=Ascending&sortBy=SortName")]
Task<JellyfinLibraryItemsResponse> GetShowLibraryItemsWithoutPeople(
[Header("Authorization")]
@@ -93,6 +93,23 @@ public class JellyfinApiClient : IJellyfinApiClient
limit: pageSize),
(maybeLibrary, item) => maybeLibrary.Map(lib => ProjectToMovie(lib, item)).Flatten());
public IAsyncEnumerable<Tuple<MusicVideo, int>> GetMusicVideoLibraryItems(
string address,
string authorizationHeader,
JellyfinLibrary library) =>
GetPagedLibraryItems(
"JF Music Videos",
address,
library,
library.MediaSourceId,
library.ItemId,
(service, itemId, skip, pageSize) => service.GetMusicVideoLibraryItems(
authorizationHeader,
itemId,
startIndex: skip,
limit: pageSize),
(maybeLibrary, item) => maybeLibrary.Map(lib => ProjectToMusicVideo(lib, item)).Flatten());
public IAsyncEnumerable<Tuple<JellyfinShow, int>> GetShowLibraryItemsWithoutPeople(
string address,
string authorizationHeader,
@@ -438,6 +455,15 @@ public class JellyfinApiClient : IJellyfinApiClient
Paths = new List<LibraryPath> { new() { Path = $"jellyfin://{response.ItemId}" } },
PathInfos = GetPathInfos(response)
},
"musicvideos" => new JellyfinLibrary
{
ItemId = response.ItemId,
Name = response.Name,
MediaKind = LibraryMediaKind.MusicVideos,
ShouldSyncItems = false,
Paths = new List<LibraryPath> { new() { Path = $"jellyfin://{response.ItemId}" } },
PathInfos = GetPathInfos(response)
},
// TODO: ??? for music libraries
"boxsets" => CacheCollectionLibraryId(response.ItemId),
_ => None
@@ -484,7 +510,7 @@ public class JellyfinApiClient : IJellyfinApiClient
}
string path = item.Path ?? string.Empty;
foreach (JellyfinPathInfo pathInfo in library.PathInfos.Filter(pi =>
foreach (JellyfinPathInfo pathInfo in Optional(library.PathInfos).Flatten().Filter(pi =>
!string.IsNullOrWhiteSpace(pi.NetworkPath)))
{
if (path.StartsWith(pathInfo.NetworkPath, StringComparison.Ordinal))
@@ -620,6 +646,139 @@ public class JellyfinApiClient : IJellyfinApiClient
return metadata;
}
private Option<MusicVideo> ProjectToMusicVideo(JellyfinLibrary library, JellyfinLibraryItemResponse item)
{
try
{
if (item.LocationType != "FileSystem")
{
return None;
}
if (Path.GetExtension(item.Path)?.ToLowerInvariant() == ".strm")
{
_logger.LogInformation("STRM files are not supported; skipping {Path}", item.Path);
return None;
}
string path = item.Path ?? string.Empty;
foreach (JellyfinPathInfo pathInfo in Optional(library.PathInfos).Flatten().Filter(pi =>
!string.IsNullOrWhiteSpace(pi.NetworkPath)))
{
if (path.StartsWith(pathInfo.NetworkPath, StringComparison.Ordinal))
{
path = _jellyfinPathReplacementService.ReplaceNetworkPath(
(JellyfinMediaSource)library.MediaSource,
path,
pathInfo.NetworkPath,
pathInfo.Path);
}
}
var duration = TimeSpan.FromTicks(item.RunTimeTicks);
var version = new MediaVersion
{
Name = "Main",
Duration = duration,
DateAdded = item.DateCreated.UtcDateTime,
MediaFiles =
[
new MediaFile
{
Path = path,
PathHash = PathUtils.GetPathHash(path)
}
],
Streams = [],
Chapters = ProjectToModel(Optional(item.Chapters).Flatten(), duration)
};
MusicVideoMetadata metadata = ProjectToMusicVideoMetadata(item);
var musicVideo = new MusicVideo
{
MediaVersions = [version],
MusicVideoMetadata = [metadata],
TraktListItems = []
};
return musicVideo;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error projecting Jellyfin music video");
return None;
}
}
private static MusicVideoMetadata ProjectToMusicVideoMetadata(JellyfinLibraryItemResponse item)
{
DateTime dateAdded = item.DateCreated.UtcDateTime;
var metadata = new MusicVideoMetadata
{
MetadataKind = MetadataKind.External,
Title = item.Name,
SortTitle = SortTitle.GetSortTitle(item.Name),
Plot = item.Overview,
Year = item.ProductionYear,
DateAdded = dateAdded,
Genres = Optional(item.Genres).Flatten().Map(g => new Genre { Name = g }).ToList(),
Tags = Optional(item.Tags).Flatten().Map(t => new Tag { Name = t }).ToList(),
Studios = Optional(item.Studios).Flatten().Map(s => new Studio { Name = s.Name }).ToList(),
Artists = MusicVideoArtists(item)
.ToList(),
Directors = Optional(item.People).Flatten().Collect(r => ProjectToDirector(r)).ToList(),
Artwork = new List<Artwork>(),
Guids = GuidsFromProviderIds(item.ProviderIds),
Subtitles = new List<Subtitle>()
};
if (DateTime.TryParse(item.PremiereDate, out DateTime releaseDate))
{
metadata.ReleaseDate = releaseDate;
}
if (!string.IsNullOrWhiteSpace(item.ImageTags?.Primary))
{
var poster = new Artwork
{
ArtworkKind = ArtworkKind.Poster,
Path = $"jellyfin://Items/{item.Id}/Images/Primary?tag={item.ImageTags.Primary}",
DateAdded = dateAdded
};
metadata.Artwork.Add(poster);
}
if (item.BackdropImageTags?.Count > 0)
{
var fanArt = new Artwork
{
ArtworkKind = ArtworkKind.FanArt,
Path = $"jellyfin://Items/{item.Id}/Images/Backdrop?tag={item.BackdropImageTags.Head()}",
DateAdded = dateAdded
};
metadata.Artwork.Add(fanArt);
}
return metadata;
}
private static IEnumerable<MusicVideoArtist> MusicVideoArtists(JellyfinLibraryItemResponse item)
{
List<string> artists = Optional(item.Artists).Flatten().ToList();
if (artists.Count == 0)
{
artists = Optional(item.People).Flatten()
.Filter(p => p.Type is "Artist")
.Map(p => p.Name)
.ToList();
}
return artists.Filter(name => !string.IsNullOrWhiteSpace(name))
.Distinct()
.Map(name => new MusicVideoArtist { Name = name });
}
private static Option<Actor> ProjectToActor(JellyfinPersonResponse person, DateTime dateAdded)
{
if (person.Type?.ToLowerInvariant() != "actor")
@@ -10,6 +10,7 @@ public class JellyfinLibraryItemResponse
public DateTimeOffset DateCreated { get; set; }
public long RunTimeTicks { get; set; }
public List<string> Genres { get; set; }
public List<string> Artists { get; set; }
public List<string> Tags { get; set; }
public int ProductionYear { get; set; }
public JellyfinProviderIdsResponse ProviderIds { get; set; }
@@ -0,0 +1,99 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Jellyfin;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Jellyfin;
using ErsatzTV.Scanner.Application.Jellyfin;
using ErsatzTV.Scanner.Core.Interfaces;
using Microsoft.Extensions.Logging;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Scanner.Tests.Application.Jellyfin;
public class SynchronizeJellyfinLibraryByIdHandlerTests
{
[TestFixture]
public class Handle
{
[Test]
public async Task Should_Scan_MusicVideo_Libraries()
{
var scannerProxy = Substitute.For<IScannerProxy>();
var mediaSourceRepository = Substitute.For<IMediaSourceRepository>();
var jellyfinSecretStore = Substitute.For<IJellyfinSecretStore>();
var jellyfinMovieLibraryScanner = Substitute.For<IJellyfinMovieLibraryScanner>();
var jellyfinTelevisionLibraryScanner = Substitute.For<IJellyfinTelevisionLibraryScanner>();
var jellyfinMusicVideoLibraryScanner = Substitute.For<IJellyfinMusicVideoLibraryScanner>();
var libraryRepository = Substitute.For<ILibraryRepository>();
var configElementRepository = Substitute.For<IConfigElementRepository>();
var library = new JellyfinLibrary
{
Id = 42,
Name = "Concerts",
MediaKind = LibraryMediaKind.MusicVideos,
MediaSourceId = 7
};
var mediaSource = new JellyfinMediaSource
{
Id = 7,
Connections =
[
new JellyfinConnection
{
Address = "http://jellyfin.example",
JellyfinMediaSourceId = 7
}
]
};
mediaSourceRepository.GetJellyfinByLibraryId(library.Id).Returns(Some(mediaSource).AsTask());
mediaSourceRepository.GetJellyfinLibrary(library.Id).Returns(Some(library).AsTask());
jellyfinSecretStore.ReadSecrets().Returns(new JellyfinSecrets
{
Address = "http://jellyfin.example",
ApiKey = "abc"
});
configElementRepository.GetValue<int>(
Arg.Is<ConfigElementKey>(key => key.Key == ConfigElementKey.LibraryRefreshInterval.Key),
Arg.Any<CancellationToken>())
.Returns(Task.FromResult<Option<int>>(Some(0)));
jellyfinMusicVideoLibraryScanner.ScanLibrary(
Arg.Any<JellyfinConnectionParameters>(),
library,
true,
Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default).AsTask());
var handler = new SynchronizeJellyfinLibraryByIdHandler(
scannerProxy,
mediaSourceRepository,
jellyfinSecretStore,
jellyfinMovieLibraryScanner,
jellyfinTelevisionLibraryScanner,
jellyfinMusicVideoLibraryScanner,
libraryRepository,
configElementRepository,
Substitute.For<ILogger<SynchronizeJellyfinLibraryByIdHandler>>());
Either<BaseError, string> result = await handler.Handle(
new SynchronizeJellyfinLibraryById("http://ersatztv.example", library.Id, true, true),
CancellationToken.None);
result.LeftToSeq().ShouldBeEmpty();
result.IsRight.ShouldBeTrue();
result.RightToSeq().Single().ShouldBe("Concerts");
await jellyfinMusicVideoLibraryScanner.Received(1).ScanLibrary(
Arg.Is<JellyfinConnectionParameters>(cp =>
cp.Address == "http://jellyfin.example" &&
cp.ApiKey == "abc" &&
cp.MediaSourceId == 7),
library,
true,
Arg.Any<CancellationToken>());
await libraryRepository.Received(1).UpdateLastScan(library);
}
}
}
@@ -14,6 +14,7 @@ public class
private readonly IConfigElementRepository _configElementRepository;
private readonly IJellyfinMovieLibraryScanner _jellyfinMovieLibraryScanner;
private readonly IJellyfinMusicVideoLibraryScanner _jellyfinMusicVideoLibraryScanner;
private readonly IJellyfinSecretStore _jellyfinSecretStore;
private readonly IJellyfinTelevisionLibraryScanner _jellyfinTelevisionLibraryScanner;
@@ -28,6 +29,7 @@ public class
IJellyfinSecretStore jellyfinSecretStore,
IJellyfinMovieLibraryScanner jellyfinMovieLibraryScanner,
IJellyfinTelevisionLibraryScanner jellyfinTelevisionLibraryScanner,
IJellyfinMusicVideoLibraryScanner jellyfinMusicVideoLibraryScanner,
ILibraryRepository libraryRepository,
IConfigElementRepository configElementRepository,
ILogger<SynchronizeJellyfinLibraryByIdHandler> logger)
@@ -37,6 +39,7 @@ public class
_jellyfinSecretStore = jellyfinSecretStore;
_jellyfinMovieLibraryScanner = jellyfinMovieLibraryScanner;
_jellyfinTelevisionLibraryScanner = jellyfinTelevisionLibraryScanner;
_jellyfinMusicVideoLibraryScanner = jellyfinMusicVideoLibraryScanner;
_libraryRepository = libraryRepository;
_configElementRepository = configElementRepository;
_logger = logger;
@@ -75,6 +78,12 @@ public class
parameters.Library,
parameters.DeepScan,
cancellationToken),
LibraryMediaKind.MusicVideos =>
await _jellyfinMusicVideoLibraryScanner.ScanLibrary(
parameters.ConnectionParameters,
parameters.Library,
parameters.DeepScan,
cancellationToken),
_ => Unit.Default
};
@@ -0,0 +1,216 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Extensions;
using ErsatzTV.Core.Interfaces.Jellyfin;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Jellyfin;
using ErsatzTV.Core.Metadata;
using ErsatzTV.Scanner.Core.Interfaces;
using Microsoft.Extensions.Logging;
namespace ErsatzTV.Scanner.Core.Jellyfin;
public class JellyfinMusicVideoLibraryScanner : IJellyfinMusicVideoLibraryScanner
{
private const string UnknownArtist = "Unknown Artist";
private readonly IArtistRepository _artistRepository;
private readonly IJellyfinApiClient _jellyfinApiClient;
private readonly IJellyfinPathReplacementService _pathReplacementService;
private readonly ILibraryRepository _libraryRepository;
private readonly ILogger<JellyfinMusicVideoLibraryScanner> _logger;
private readonly IMediaSourceRepository _mediaSourceRepository;
private readonly IMetadataRepository _metadataRepository;
private readonly IMusicVideoRepository _musicVideoRepository;
private readonly IScannerProxy _scannerProxy;
public JellyfinMusicVideoLibraryScanner(
IScannerProxy scannerProxy,
IJellyfinApiClient jellyfinApiClient,
IJellyfinPathReplacementService pathReplacementService,
IMediaSourceRepository mediaSourceRepository,
IArtistRepository artistRepository,
IMusicVideoRepository musicVideoRepository,
ILibraryRepository libraryRepository,
IMetadataRepository metadataRepository,
ILogger<JellyfinMusicVideoLibraryScanner> logger)
{
_scannerProxy = scannerProxy;
_jellyfinApiClient = jellyfinApiClient;
_pathReplacementService = pathReplacementService;
_mediaSourceRepository = mediaSourceRepository;
_artistRepository = artistRepository;
_musicVideoRepository = musicVideoRepository;
_libraryRepository = libraryRepository;
_metadataRepository = metadataRepository;
_logger = logger;
}
public async Task<Either<BaseError, Unit>> ScanLibrary(
JellyfinConnectionParameters connectionParameters,
JellyfinLibrary library,
bool deepScan,
CancellationToken cancellationToken)
{
try
{
Option<LibraryPath> maybeLibraryPath = Optional(library.Paths).Flatten().HeadOrNone();
return await maybeLibraryPath.Match(
libraryPath => ScanLibrary(connectionParameters, library, libraryPath, cancellationToken),
() => Task.FromResult<Either<BaseError, Unit>>(
BaseError.New($"Jellyfin library {library.Id} has no library path")));
}
catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException)
{
return new ScanCanceled();
}
}
private async Task<Either<BaseError, Unit>> ScanLibrary(
JellyfinConnectionParameters connectionParameters,
JellyfinLibrary library,
LibraryPath libraryPath,
CancellationToken cancellationToken)
{
List<JellyfinPathReplacement> pathReplacements =
await _mediaSourceRepository.GetJellyfinPathReplacements(library.MediaSourceId);
var processed = 0;
await foreach ((MusicVideo incoming, int totalCount) in _jellyfinApiClient
.GetMusicVideoLibraryItems(
connectionParameters.Address,
connectionParameters.AuthorizationHeader,
library)
.WithCancellation(cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return new ScanCanceled();
}
processed++;
decimal percentCompletion = totalCount == 0 ? 1 : Math.Clamp((decimal)processed / totalCount, 0, 1);
if (!await _scannerProxy.UpdateProgress(percentCompletion, cancellationToken))
{
return new ScanCanceled();
}
Either<BaseError, MediaItemScanResult<MusicVideo>> maybeMusicVideo =
await ProcessMusicVideo(library, libraryPath, pathReplacements, incoming, cancellationToken);
foreach (BaseError error in maybeMusicVideo.LeftToSeq())
{
_logger.LogWarning("Error processing Jellyfin music video: {Error}", error.Value);
}
foreach (MediaItemScanResult<MusicVideo> result in maybeMusicVideo.RightToSeq()
.Filter(result => result.IsAdded || result.IsUpdated))
{
if (!await _scannerProxy.ReindexMediaItems([result.Item.Id], cancellationToken))
{
_logger.LogWarning("Failed to reindex media items from scanner process");
}
}
}
return Unit.Default;
}
private async Task<Either<BaseError, MediaItemScanResult<MusicVideo>>> ProcessMusicVideo(
JellyfinLibrary library,
LibraryPath libraryPath,
List<JellyfinPathReplacement> pathReplacements,
MusicVideo incoming,
CancellationToken cancellationToken)
{
string localPath = GetLocalPath(pathReplacements, incoming);
string folder = Path.GetDirectoryName(localPath) ?? libraryPath.Path;
Option<int> maybeParentFolder = await _libraryRepository.GetParentFolderId(libraryPath, folder, cancellationToken);
LibraryFolder libraryFolder = await _libraryRepository.GetOrAddFolder(libraryPath, maybeParentFolder, folder);
return await GetOrAddArtist(libraryPath, incoming)
.BindT(artist => _musicVideoRepository.GetOrAdd(artist, libraryPath, libraryFolder, localPath))
.BindT(result => UpdateMusicVideo(result, incoming, localPath, cancellationToken));
}
private string GetLocalPath(List<JellyfinPathReplacement> pathReplacements, MusicVideo musicVideo) =>
_pathReplacementService.GetReplacementJellyfinPath(
pathReplacements,
musicVideo.GetHeadVersion().MediaFiles.Head().Path,
false);
private async Task<Either<BaseError, Artist>> GetOrAddArtist(LibraryPath libraryPath, MusicVideo musicVideo)
{
string artistName = musicVideo.MusicVideoMetadata
.HeadOrNone()
.Bind(metadata => Optional(metadata.Artists).Flatten().HeadOrNone())
.Map(artist => artist.Name)
.IfNone(UnknownArtist);
var metadata = new ArtistMetadata
{
MetadataKind = MetadataKind.External,
Title = artistName,
SortTitle = SortTitle.GetSortTitle(artistName),
DateAdded = DateTime.UtcNow,
Genres = [],
Styles = [],
Moods = [],
Artwork = [],
Guids = [],
Subtitles = []
};
Option<Artist> maybeArtist = await _artistRepository.GetArtistByMetadata(libraryPath.Id, metadata);
foreach (Artist artist in maybeArtist)
{
return artist;
}
Either<BaseError, MediaItemScanResult<Artist>> result =
await _artistRepository.AddArtist(libraryPath.Id, artistName, metadata);
return result.Map(scanResult => scanResult.Item);
}
private async Task<Either<BaseError, MediaItemScanResult<MusicVideo>>> UpdateMusicVideo(
MediaItemScanResult<MusicVideo> result,
MusicVideo incoming,
string localPath,
CancellationToken cancellationToken)
{
result.LocalPath = localPath;
MusicVideoMetadata incomingMetadata = incoming.MusicVideoMetadata.Head();
bool updated = await UpdateMetadata(result.Item, incomingMetadata);
updated = await _metadataRepository.UpdateStatistics(result.Item, incoming.GetHeadVersion()) || updated;
if (updated)
{
result.IsUpdated = true;
}
return result;
}
private async Task<bool> UpdateMetadata(MusicVideo musicVideo, MusicVideoMetadata incoming)
{
Option<MusicVideoMetadata> maybeExisting = Optional(musicVideo.MusicVideoMetadata).Flatten().HeadOrNone();
foreach (MusicVideoMetadata existing in maybeExisting)
{
existing.Title = incoming.Title;
existing.SortTitle = incoming.SortTitle;
existing.Plot = incoming.Plot;
existing.Year = incoming.Year;
existing.ReleaseDate = incoming.ReleaseDate;
existing.DateUpdated = DateTime.UtcNow;
existing.MetadataKind = MetadataKind.External;
return await _metadataRepository.Update(existing);
}
incoming.MusicVideoId = musicVideo.Id;
musicVideo.MusicVideoMetadata = [incoming];
return await _metadataRepository.Add(incoming);
}
}
+1
View File
@@ -236,6 +236,7 @@ public class Program
services.AddScoped<IJellyfinMovieLibraryScanner, JellyfinMovieLibraryScanner>();
services.AddScoped<IJellyfinTelevisionLibraryScanner, JellyfinTelevisionLibraryScanner>();
services.AddScoped<IJellyfinMusicVideoLibraryScanner, JellyfinMusicVideoLibraryScanner>();
services.AddScoped<IJellyfinCollectionScanner, JellyfinCollectionScanner>();
services.AddScoped<IJellyfinApiClient, JellyfinApiClient>();
services.AddScoped<IJellyfinCollectionRepository, JellyfinCollectionRepository>();
@@ -0,0 +1,57 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Testably.Abstractions.Testing;
namespace ErsatzTV.Tests.Application.Channels;
[TestFixture]
public class BulkDeleteChannelsHandlerTests : ChannelHandlerTestBase
{
private readonly MockFileSystem _fileSystem = new();
private BulkDeleteChannelsHandler MakeHandler() => new(Db.Factory, Worker, _fileSystem, SearchTargets);
[Test]
public async Task Should_Delete_All_Channels()
{
await SeedChannel(1, "5");
await SeedChannel(2, "6");
Either<BaseError, Unit> result =
await MakeHandler().Handle(new BulkDeleteChannels([1, 2]), CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext context = Db.CreateContext();
int count = await context.Channels.CountAsync();
count.ShouldBe(0);
SearchTargets.Received(1).SearchTargetsChanged();
}
[Test]
public async Task Should_Return_NotFound_And_Not_Delete_When_Any_Channel_Is_Missing()
{
await SeedChannel(1, "5");
Either<BaseError, Unit> result =
await MakeHandler().Handle(new BulkDeleteChannels([1, 99]), CancellationToken.None);
BaseError error = LeftOf(result);
error.ShouldBeOfType<NotFoundError>();
await using TvContext context = Db.CreateContext();
bool exists = await context.Channels.AnyAsync(c => c.Id == 1);
exists.ShouldBeTrue();
}
private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
}
@@ -0,0 +1,74 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Application.Channels;
[TestFixture]
public class BulkMoveChannelsToGroupHandlerTests : ChannelHandlerTestBase
{
private BulkMoveChannelsToGroupHandler MakeHandler() => new(Db.Factory, Worker, SearchTargets);
[Test]
public async Task Should_Move_All_Channels_To_Group()
{
await SeedChannel(1, "5");
await SeedChannel(2, "6");
Either<BaseError, Unit> result =
await MakeHandler().Handle(new BulkMoveChannelsToGroup([1, 2], "Movies"), CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext context = Db.CreateContext();
List<string> groups = await context.Channels
.OrderBy(c => c.Id)
.Select(c => c.Group)
.ToListAsync();
groups.ShouldBe(["Movies", "Movies"]);
SearchTargets.Received(1).SearchTargetsChanged();
}
[Test]
public async Task Should_Return_NotFound_And_Not_Move_When_Any_Channel_Is_Missing()
{
await SeedChannel(1, "5", group: "Original");
Either<BaseError, Unit> result =
await MakeHandler().Handle(new BulkMoveChannelsToGroup([1, 99], "Movies"), CancellationToken.None);
BaseError error = LeftOf(result);
error.ShouldBeOfType<NotFoundError>();
await using TvContext context = Db.CreateContext();
string group = await context.Channels.Where(c => c.Id == 1).Select(c => c.Group).SingleAsync();
group.ShouldBe("Original");
}
[Test]
public async Task Should_Reject_Empty_Group()
{
await SeedChannel(1, "5", group: "Original");
Either<BaseError, Unit> result =
await MakeHandler().Handle(new BulkMoveChannelsToGroup([1], ""), CancellationToken.None);
BaseError error = LeftOf(result);
error.ShouldNotBeOfType<NotFoundError>();
error.Value.ShouldContain("group");
await using TvContext context = Db.CreateContext();
string group = await context.Channels.Where(c => c.Id == 1).Select(c => c.Group).SingleAsync();
group.ShouldBe("Original");
}
private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
}
@@ -0,0 +1,53 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Application.Channels;
[TestFixture]
public class GetAllChannelsForApiHandlerTests
{
[Test]
public async Task Should_Project_Management_Table_Fields()
{
IChannelRepository repository = Substitute.For<IChannelRepository>();
repository.GetAll(Arg.Any<CancellationToken>())
.Returns([
new Channel(Guid.NewGuid())
{
Id = 7,
Number = "7.1",
SortNumber = 7.1,
Name = "Retro Cartoons",
Group = "Kids",
Categories = "animation",
FFmpegProfile = new FFmpegProfile { Name = "HLS 720p" },
PreferredAudioLanguageCode = "eng",
StreamingMode = StreamingMode.HttpLiveStreamingSegmenter,
IsEnabled = false,
ShowInEpg = false
}
]);
var handler = new GetAllChannelsForApiHandler(repository);
List<ChannelResponseModel> result = await handler.Handle(new GetAllChannelsForApi(), CancellationToken.None);
ChannelResponseModel channel = result.ShouldHaveSingleItem();
channel.Id.ShouldBe(7);
channel.Number.ShouldBe("7.1");
channel.SortNumber.ShouldBe(7.1);
channel.Name.ShouldBe("Retro Cartoons");
channel.Group.ShouldBe("Kids");
channel.Categories.ShouldBe("animation");
channel.FFmpegProfile.ShouldBe("HLS 720p");
channel.Language.ShouldBe("eng");
channel.StreamingMode.ShouldBe("HLS Segmenter");
channel.IsEnabled.ShouldBeFalse();
channel.ShowInEpg.ShouldBeFalse();
}
}
@@ -0,0 +1,329 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Interfaces.FFmpeg;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Application.Channels;
[TestFixture]
public class GetChannelStatesForApiHandlerTests
{
private static readonly DateTime Now = new(2026, 7, 2, 12, 0, 0, DateTimeKind.Utc);
private InMemoryTvContext _db = null!;
private IFFmpegSegmenterService _segmenter = null!;
[SetUp]
public async Task SetUp()
{
_db = await InMemoryTvContext.CreateAsync();
_segmenter = Substitute.For<IFFmpegSegmenterService>();
}
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
[Test]
public async Task Handle_Should_Return_OnAir_And_Current_NowPlaying()
{
DateTime start = Now.AddMinutes(-10);
DateTime finish = Now.AddMinutes(20);
await SeedChannelWithMovie(start, finish);
_segmenter.IsActive("7.1").Returns(true);
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
List<ChannelStateResponseModel> result =
await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None);
ChannelStateResponseModel state = result.ShouldHaveSingleItem();
state.ChannelId.ShouldBe(7);
state.ChannelNumber.ShouldBe("7.1");
state.OnAir.ShouldBeTrue();
state.NowPlaying.ShouldNotBeNull();
state.NowPlaying.Title.ShouldBe("Retro Cartoons");
state.NowPlaying.StartUtc.ShouldBe(new DateTimeOffset(start, TimeSpan.Zero));
state.NowPlaying.FinishUtc.ShouldBe(new DateTimeOffset(finish, TimeSpan.Zero));
}
[Test]
public async Task Handle_Should_Match_Item_When_Now_Equals_Start()
{
await SeedChannelWithMovie(Now, Now.AddMinutes(30));
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
List<ChannelStateResponseModel> result =
await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None);
result.ShouldHaveSingleItem().NowPlaying.ShouldNotBeNull();
}
[Test]
public async Task Handle_Should_Not_Match_Item_When_Now_Equals_Finish()
{
await SeedChannelWithMovie(Now.AddMinutes(-30), Now);
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
List<ChannelStateResponseModel> result =
await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None);
result.ShouldHaveSingleItem().NowPlaying.ShouldBeNull();
}
[Test]
public async Task Handle_Should_Return_Null_NowPlaying_When_No_Current_Item()
{
await using TvContext context = _db.CreateContext();
context.Channels.Add(MakeChannel(8, "8"));
await context.SaveChangesAsync();
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
List<ChannelStateResponseModel> result =
await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None);
ChannelStateResponseModel state = result.ShouldHaveSingleItem();
state.OnAir.ShouldBeFalse();
state.NowPlaying.ShouldBeNull();
}
[Test]
public async Task Handle_Should_Surface_Program_Not_Filler_During_MidRoll_Break()
{
// program part 1 / mid-roll filler / program part 2, all in one guide group
await using TvContext context = _db.CreateContext();
Channel channel = MakeChannel(12, "12");
var movie = new Movie
{
Id = 120,
MovieMetadata = [new MovieMetadata { Title = "Feature Presentation" }]
};
var filler = new OtherVideo
{
Id = 121,
OtherVideoMetadata = [new OtherVideoMetadata { Title = "Some Bumper" }]
};
var playout = new Playout { Id = 122, Channel = channel, ChannelId = channel.Id, Items = [] };
PlayoutItem MakeItem(int id, MediaItem mediaItem, DateTime start, DateTime finish, FillerKind fillerKind) =>
new()
{
Id = id,
MediaItem = mediaItem,
MediaItemId = mediaItem.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = start,
Finish = finish,
FillerKind = fillerKind,
GuideGroup = 1,
ChapterTitle = string.Empty
};
context.Channels.Add(channel);
context.Movies.Add(movie);
context.OtherVideos.Add(filler);
context.Playouts.Add(playout);
context.PlayoutItems.AddRange(
MakeItem(123, movie, Now.AddMinutes(-20), Now.AddMinutes(-2), FillerKind.None),
MakeItem(124, filler, Now.AddMinutes(-2), Now.AddMinutes(2), FillerKind.MidRoll),
MakeItem(125, movie, Now.AddMinutes(2), Now.AddMinutes(40), FillerKind.None));
await context.SaveChangesAsync();
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
List<ChannelStateResponseModel> result =
await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None);
ChannelStateResponseModel state = result.ShouldHaveSingleItem();
state.NowPlaying.ShouldNotBeNull();
state.NowPlaying.Title.ShouldBe("Feature Presentation");
state.NowPlaying.StartUtc.ShouldBe(new DateTimeOffset(Now.AddMinutes(-20), TimeSpan.Zero));
state.NowPlaying.FinishUtc.ShouldBe(new DateTimeOffset(Now.AddMinutes(40), TimeSpan.Zero));
}
[Test]
public async Task Handle_Should_Return_Null_NowPlaying_For_Guide_Entry_With_Only_Filler()
{
await using TvContext context = _db.CreateContext();
Channel channel = MakeChannel(13, "13");
var filler = new OtherVideo
{
Id = 130,
OtherVideoMetadata = [new OtherVideoMetadata { Title = "Offline Loop" }]
};
var playout = new Playout { Id = 131, Channel = channel, ChannelId = channel.Id, Items = [] };
var item = new PlayoutItem
{
Id = 132,
MediaItem = filler,
MediaItemId = filler.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = Now.AddMinutes(-5),
Finish = Now.AddMinutes(5),
FillerKind = FillerKind.Fallback,
GuideGroup = 1,
ChapterTitle = string.Empty
};
context.Channels.Add(channel);
context.OtherVideos.Add(filler);
context.Playouts.Add(playout);
context.PlayoutItems.Add(item);
await context.SaveChangesAsync();
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
List<ChannelStateResponseModel> result =
await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None);
result.ShouldHaveSingleItem().NowPlaying.ShouldBeNull();
}
[Test]
public async Task Handle_Should_Map_Remote_Stream_NowPlaying_Title()
{
DateTime start = Now.AddMinutes(-10);
DateTime finish = Now.AddMinutes(20);
await using TvContext context = _db.CreateContext();
Channel channel = MakeChannel(9, "9");
var remoteStream = new RemoteStream
{
Id = 90,
RemoteStreamMetadata = [new RemoteStreamMetadata { Title = "Live Source" }]
};
var playout = new Playout { Id = 91, Channel = channel, ChannelId = channel.Id, Items = [] };
var item = new PlayoutItem
{
Id = 92,
MediaItem = remoteStream,
MediaItemId = remoteStream.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = start,
Finish = finish,
ChapterTitle = string.Empty
};
context.Channels.Add(channel);
context.RemoteStreams.Add(remoteStream);
context.Playouts.Add(playout);
context.PlayoutItems.Add(item);
await context.SaveChangesAsync();
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
ChannelStateResponseModel state =
(await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None))
.ShouldHaveSingleItem();
state.NowPlaying.ShouldNotBeNull();
state.NowPlaying.Title.ShouldBe("Live Source");
}
[Test]
public async Task Handle_Should_Resolve_Mirror_Channel_NowPlaying_From_Source_With_Offset()
{
TimeSpan offset = TimeSpan.FromHours(1);
DateTime sourceStart = Now.AddMinutes(-70);
DateTime sourceFinish = Now.AddMinutes(-40);
await using TvContext context = _db.CreateContext();
Channel source = MakeChannel(10, "10");
Channel mirror = MakeChannel(11, "11");
mirror.PlayoutSource = ChannelPlayoutSource.Mirror;
mirror.MirrorSourceChannelId = source.Id;
mirror.PlayoutOffset = offset;
var movie = new Movie
{
Id = 110,
MovieMetadata = [new MovieMetadata { Title = "Offset Feature" }]
};
var playout = new Playout { Id = 111, Channel = source, ChannelId = source.Id, Items = [] };
var item = new PlayoutItem
{
Id = 112,
MediaItem = movie,
MediaItemId = movie.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = sourceStart,
Finish = sourceFinish,
ChapterTitle = string.Empty
};
context.Channels.AddRange(source, mirror);
context.Movies.Add(movie);
context.Playouts.Add(playout);
context.PlayoutItems.Add(item);
await context.SaveChangesAsync();
var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter);
List<ChannelStateResponseModel> result =
await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None);
ChannelStateResponseModel mirrorState = result.Single(s => s.ChannelId == mirror.Id);
mirrorState.NowPlaying.ShouldNotBeNull();
mirrorState.NowPlaying.Title.ShouldBe("Offset Feature");
mirrorState.NowPlaying.StartUtc.ShouldBe(new DateTimeOffset(sourceStart + offset, TimeSpan.Zero));
mirrorState.NowPlaying.FinishUtc.ShouldBe(new DateTimeOffset(sourceFinish + offset, TimeSpan.Zero));
// the source's own item is 40+ minutes in the past with no offset, so its own row is off-air
ChannelStateResponseModel sourceState = result.Single(s => s.ChannelId == source.Id);
sourceState.NowPlaying.ShouldBeNull();
}
private async Task SeedChannelWithMovie(DateTime start, DateTime finish)
{
await using TvContext context = _db.CreateContext();
Channel channel = MakeChannel(7, "7.1");
var movie = new Movie
{
Id = 10,
MovieMetadata = [new MovieMetadata { Title = "Retro Cartoons" }]
};
var playout = new Playout
{
Id = 20,
Channel = channel,
ChannelId = channel.Id,
Items = []
};
var item = new PlayoutItem
{
Id = 30,
MediaItem = movie,
MediaItemId = movie.Id,
Playout = playout,
PlayoutId = playout.Id,
Start = start,
Finish = finish,
ChapterTitle = string.Empty
};
context.Channels.Add(channel);
context.Movies.Add(movie);
context.Playouts.Add(playout);
context.PlayoutItems.Add(item);
await context.SaveChangesAsync();
}
private static Channel MakeChannel(int id, string number) =>
new(Guid.NewGuid())
{
Id = id,
Number = number,
SortNumber = id,
Name = $"Channel {number}",
Group = "Test",
Categories = string.Empty,
PreferredAudioLanguageCode = string.Empty
};
}
@@ -0,0 +1,111 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Application.Channels;
[TestFixture]
public class UpdateChannelNumbersHandlerTests : ChannelHandlerTestBase
{
private UpdateChannelNumbersHandler MakeHandler() => new(Db.Factory, Worker);
[Test]
public async Task Should_Renumber_All_Channels()
{
await SeedChannel(1, "5");
await SeedChannel(2, "6");
Option<BaseError> result = await MakeHandler().Handle(
new UpdateChannelNumbers(
[
new ChannelSortViewModel { Id = 1, Number = "10" },
new ChannelSortViewModel { Id = 2, Number = "11.1" }
]),
CancellationToken.None);
result.IsNone.ShouldBeTrue();
await using TvContext context = Db.CreateContext();
var channels = await context.Channels
.OrderBy(c => c.Id)
.Select(c => new { c.Number, c.SortNumber })
.ToListAsync();
channels[0].Number.ShouldBe("10");
channels[0].SortNumber.ShouldBe(10);
channels[1].Number.ShouldBe("11.1");
channels[1].SortNumber.ShouldBe(11.1);
}
[Test]
public async Task Should_Return_NotFound_And_Not_Renumber_When_Any_Channel_Is_Missing()
{
await SeedChannel(1, "5");
Option<BaseError> result = await MakeHandler().Handle(
new UpdateChannelNumbers(
[
new ChannelSortViewModel { Id = 1, Number = "10" },
new ChannelSortViewModel { Id = 99, Number = "11" }
]),
CancellationToken.None);
BaseError error = ErrorOf(result);
error.ShouldBeOfType<NotFoundError>();
await using TvContext context = Db.CreateContext();
string number = await context.Channels.Where(c => c.Id == 1).Select(c => c.Number).SingleAsync();
number.ShouldBe("5");
}
[Test]
public async Task Should_Reject_Duplicate_Numbers_And_Not_Renumber()
{
await SeedChannel(1, "5");
await SeedChannel(2, "6");
Option<BaseError> result = await MakeHandler().Handle(
new UpdateChannelNumbers(
[
new ChannelSortViewModel { Id = 1, Number = "10" },
new ChannelSortViewModel { Id = 2, Number = "10" }
]),
CancellationToken.None);
BaseError error = ErrorOf(result);
error.ShouldNotBeOfType<NotFoundError>();
error.Value.ShouldContain("unique");
await using TvContext context = Db.CreateContext();
List<string> numbers = await context.Channels.OrderBy(c => c.Id).Select(c => c.Number).ToListAsync();
numbers.ShouldBe(["5", "6"]);
}
[Test]
public async Task Should_Reject_Invalid_Number_And_Not_Renumber()
{
await SeedChannel(1, "5");
Option<BaseError> result = await MakeHandler().Handle(
new UpdateChannelNumbers([new ChannelSortViewModel { Id = 1, Number = "10.123" }]),
CancellationToken.None);
BaseError error = ErrorOf(result);
error.ShouldNotBeOfType<NotFoundError>();
error.Value.ShouldContain("Invalid channel number");
await using TvContext context = Db.CreateContext();
string number = await context.Channels.Where(c => c.Id == 1).Select(c => c.Number).SingleAsync();
number.ShouldBe("5");
}
private static BaseError ErrorOf(Option<BaseError> result) =>
result.Match(
Some: error => error,
None: () => throw new AssertionException("Expected an error"));
}
@@ -0,0 +1,189 @@
using ErsatzTV.Application.FFmpegProfiles;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.FFmpeg;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Application.FFmpegProfiles;
[TestFixture]
public class FFmpegProfileHandlerTests
{
private InMemoryTvContext _db = null!;
private IConfigElementRepository _configElementRepository = null!;
private ISearchTargets _searchTargets = null!;
[SetUp]
public async Task SetUp()
{
_db = await InMemoryTvContext.CreateAsync();
_configElementRepository = Substitute.For<IConfigElementRepository>();
_configElementRepository.GetValue<int>(Arg.Any<ConfigElementKey>(), Arg.Any<CancellationToken>())
.Returns(Option<int>.None);
_searchTargets = Substitute.For<ISearchTargets>();
}
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
[Test]
public async Task Create_Should_Return_NotFoundError_When_Resolution_Missing()
{
var handler = new CreateFFmpegProfileHandler(_db.Factory, _searchTargets);
Either<BaseError, CreateFFmpegProfileResult> result =
await handler.Handle(MakeCreate(resolutionId: 999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task Update_Should_Return_NotFoundError_When_Profile_Missing()
{
var handler = new UpdateFFmpegProfileHandler(_db.Factory, _searchTargets);
Either<BaseError, UpdateFFmpegProfileResult> result =
await handler.Handle(MakeUpdate(999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task Update_Should_Return_NotFoundError_When_Resolution_Missing()
{
await SeedProfile(1);
var handler = new UpdateFFmpegProfileHandler(_db.Factory, _searchTargets);
Either<BaseError, UpdateFFmpegProfileResult> result =
await handler.Handle(MakeUpdate(1, resolutionId: 999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task Delete_Should_Return_NotFoundError_When_Profile_Missing()
{
var handler = new DeleteFFmpegProfileHandler(_db.Factory, _configElementRepository, _searchTargets);
Either<BaseError, Unit> result = await handler.Handle(new DeleteFFmpegProfile(999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
private async Task SeedProfile(int id)
{
await using TvContext context = _db.CreateContext();
context.FFmpegProfiles.Add(new FFmpegProfile
{
Id = id,
Name = "Default",
ThreadCount = 1,
NormalizeAudio = true,
NormalizeVideo = true,
HardwareAcceleration = HardwareAccelerationKind.None,
VaapiDisplay = "drm",
VaapiDriver = VaapiDriver.Default,
VaapiDevice = "/dev/dri/renderD128",
ResolutionId = 1,
ScalingBehavior = ScalingBehavior.ScaleAndPad,
PadMode = FilterMode.Software,
VideoFormat = FFmpegProfileVideoFormat.H264,
VideoProfile = string.Empty,
VideoPreset = string.Empty,
BitDepth = FFmpegProfileBitDepth.EightBit,
VideoBitrate = 2_000,
VideoBufferSize = 4_000,
TonemapAlgorithm = FFmpegProfileTonemapAlgorithm.Linear,
AudioFormat = FFmpegProfileAudioFormat.Aac,
AudioBitrate = 192,
AudioBufferSize = 384,
NormalizeLoudnessMode = NormalizeLoudnessMode.Off,
AudioChannels = 2,
AudioSampleRate = 48_000,
NormalizeFramerate = false,
NormalizeColors = false,
DeinterlaceVideo = false
});
await context.SaveChangesAsync();
}
private static CreateFFmpegProfile MakeCreate(int resolutionId) =>
new(
"Default",
1,
true,
true,
HardwareAccelerationKind.None,
"drm",
VaapiDriver.Default,
"/dev/dri/renderD128",
null,
resolutionId,
ScalingBehavior.ScaleAndPad,
FilterMode.Software,
FFmpegProfileVideoFormat.H264,
string.Empty,
string.Empty,
false,
FFmpegProfileBitDepth.EightBit,
2_000,
4_000,
FFmpegProfileTonemapAlgorithm.Linear,
FFmpegProfileAudioFormat.Aac,
192,
384,
NormalizeLoudnessMode.Off,
null,
2,
48_000,
false,
false,
false);
private static UpdateFFmpegProfile MakeUpdate(int id, int resolutionId = 1) =>
new(
id,
"Default",
1,
true,
true,
HardwareAccelerationKind.None,
"drm",
VaapiDriver.Default,
"/dev/dri/renderD128",
null,
resolutionId,
ScalingBehavior.ScaleAndPad,
FilterMode.Software,
FFmpegProfileVideoFormat.H264,
string.Empty,
string.Empty,
false,
FFmpegProfileBitDepth.EightBit,
2_000,
4_000,
FFmpegProfileTonemapAlgorithm.Linear,
FFmpegProfileAudioFormat.Aac,
192,
384,
NormalizeLoudnessMode.Off,
null,
2,
48_000,
false,
false,
false);
}
@@ -0,0 +1,104 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using MediatR;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Testably.Abstractions.Testing;
using Unit = LanguageExt.Unit;
using Channel = System.Threading.Channels.Channel;
namespace ErsatzTV.Tests.Application.Playouts;
[TestFixture]
public class PlayoutHandlerTests
{
private InMemoryTvContext _db = null!;
private ChannelWriter<IBackgroundServiceRequest> _worker = null!;
[SetUp]
public async Task SetUp()
{
_db = await InMemoryTvContext.CreateAsync();
_worker = Channel.CreateUnbounded<IBackgroundServiceRequest>().Writer;
}
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
[Test]
public async Task CreateClassic_Should_Return_NotFoundError_When_Channel_Missing()
{
var handler = new CreateClassicPlayoutHandler(_worker, _db.Factory);
Either<BaseError, CreatePlayoutResponse> result =
await handler.Handle(new CreateClassicPlayout(999, 1), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task CreateClassic_Should_Return_NotFoundError_When_Schedule_Missing()
{
int channelId = await SeedChannel();
var handler = new CreateClassicPlayoutHandler(_worker, _db.Factory);
Either<BaseError, CreatePlayoutResponse> result =
await handler.Handle(new CreateClassicPlayout(channelId, 999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task Delete_Should_Return_NotFoundError_When_Playout_Missing()
{
var handler = new DeletePlayoutHandler(
_worker,
_db.Factory,
new MockFileSystem(),
Substitute.For<IMediator>());
Either<BaseError, Unit> result = await handler.Handle(new DeletePlayout(999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
private async Task<int> SeedChannel()
{
await using TvContext context = _db.CreateContext();
var channel = new ErsatzTV.Core.Domain.Channel(Guid.NewGuid())
{
Number = "101",
SortNumber = 101,
Name = "Handler",
Group = string.Empty,
Categories = string.Empty,
StreamingMode = StreamingMode.HttpLiveStreamingSegmenter,
Playouts = [],
Artwork = [],
StreamSelector = string.Empty,
PreferredAudioLanguageCode = string.Empty,
PreferredAudioTitle = string.Empty,
PreferredSubtitleLanguageCode = string.Empty,
MusicVideoCreditsTemplate = string.Empty,
PlayoutSource = ChannelPlayoutSource.Generated,
PlayoutMode = ChannelPlayoutMode.Continuous,
IsEnabled = true,
ShowInEpg = true
};
context.Channels.Add(channel);
await context.SaveChangesAsync();
return channel.Id;
}
}
@@ -0,0 +1,217 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using NUnit.Framework;
using Shouldly;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Application.ProgramSchedules;
[TestFixture]
public class ProgramScheduleHandlerTests
{
private InMemoryTvContext _db = null!;
private ChannelWriter<IBackgroundServiceRequest> _worker = null!;
[SetUp]
public async Task SetUp()
{
_db = await InMemoryTvContext.CreateAsync();
_worker = System.Threading.Channels.Channel.CreateUnbounded<IBackgroundServiceRequest>().Writer;
}
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
[Test]
public async Task Update_Should_Return_NotFoundError_When_Schedule_Missing()
{
var handler = new UpdateProgramScheduleHandler(_db.Factory, _worker);
Either<BaseError, UpdateProgramScheduleResult> result =
await handler.Handle(MakeUpdate(999, "Missing"), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task Delete_Should_Return_NotFoundError_When_Schedule_Missing()
{
var handler = new DeleteProgramScheduleHandler(_db.Factory);
Either<BaseError, Unit> result =
await handler.Handle(new DeleteProgramSchedule(999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task AddItem_Should_Return_NotFoundError_When_Schedule_Missing()
{
var handler = new AddProgramScheduleItemHandler(_db.Factory, _worker);
Either<BaseError, ProgramScheduleItemViewModel> result =
await handler.Handle(MakeAdd(999, CollectionType.SearchQuery), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task AddItem_Should_Return_ValidationError_When_Collection_Type_Is_Invalid()
{
int scheduleId = await SeedSchedule();
var handler = new AddProgramScheduleItemHandler(_db.Factory, _worker);
Either<BaseError, ProgramScheduleItemViewModel> result =
await handler.Handle(MakeAdd(scheduleId, CollectionType.Collection), CancellationToken.None);
BaseError error = LeftOf(result);
error.ShouldNotBeOfType<NotFoundError>();
error.Value.ShouldContain("[Collection] is required");
}
[Test]
public async Task ReplaceItems_Should_Return_NotFoundError_When_Schedule_Missing()
{
var handler = new ReplaceProgramScheduleItemsHandler(_db.Factory, _worker);
Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>> result =
await handler.Handle(
new ReplaceProgramScheduleItems(999, [MakeReplace(0)]),
CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
[Test]
public async Task DeleteItem_Should_Return_NotFoundError_When_Item_Missing()
{
int scheduleId = await SeedSchedule();
var handler = new DeleteProgramScheduleItemHandler(_db.Factory, _worker);
Either<BaseError, Unit> result =
await handler.Handle(new DeleteProgramScheduleItem(scheduleId, 999), CancellationToken.None);
LeftOf(result).ShouldBeOfType<NotFoundError>();
}
private async Task<int> SeedSchedule()
{
await using TvContext context = _db.CreateContext();
var schedule = new ProgramSchedule
{
Name = "Handlers",
Items = [],
Playouts = [],
ProgramScheduleAlternates = []
};
context.ProgramSchedules.Add(schedule);
await context.SaveChangesAsync();
return schedule.Id;
}
private static UpdateProgramSchedule MakeUpdate(int scheduleId, string name) =>
new(
scheduleId,
name,
KeepMultiPartEpisodesTogether: true,
TreatCollectionsAsShows: true,
ShuffleScheduleItems: false,
RandomStartPoint: false,
FixedStartTimeBehavior.Flexible);
private static AddProgramScheduleItem MakeAdd(int scheduleId, CollectionType collectionType) =>
new(
scheduleId,
StartType.Dynamic,
StartTime: null,
FixedStartTimeBehavior: null,
PlayoutMode.One,
collectionType,
CollectionId: null,
MultiCollectionId: null,
SmartCollectionId: null,
RerunCollectionId: null,
MediaItemId: null,
PlaylistId: null,
SearchTitle: "News",
SearchQuery: "news",
PlaybackOrder.Shuffle,
MarathonGroupBy.None,
MarathonShuffleGroups: false,
MarathonShuffleItems: false,
MarathonBatchSize: null,
FillWithGroupMode.None,
MultipleMode.Count,
MultipleCount: "1",
PlayoutDuration: null,
TailMode.None,
DiscardToFillAttempts: null,
CustomTitle: null,
GuideMode.Normal,
PreRollFillerId: null,
MidRollFillerId: null,
PostRollFillerId: null,
TailFillerId: null,
FallbackFillerId: null,
WatermarkIds: [],
GraphicsElementIds: [],
PreferredAudioLanguageCode: null,
PreferredAudioTitle: null,
PreferredSubtitleLanguageCode: null,
SubtitleMode: null);
private static ReplaceProgramScheduleItem MakeReplace(int index)
{
AddProgramScheduleItem add = MakeAdd(1, CollectionType.SearchQuery);
return new ReplaceProgramScheduleItem(
index,
add.StartType,
add.StartTime,
add.FixedStartTimeBehavior,
add.PlayoutMode,
add.CollectionType,
add.CollectionId,
add.MultiCollectionId,
add.SmartCollectionId,
add.RerunCollectionId,
add.MediaItemId,
add.PlaylistId,
add.SearchTitle,
add.SearchQuery,
add.PlaybackOrder,
add.MarathonGroupBy,
add.MarathonShuffleGroups,
add.MarathonShuffleItems,
add.MarathonBatchSize,
add.FillWithGroupMode,
add.MultipleMode,
add.MultipleCount,
add.PlayoutDuration,
add.TailMode,
add.DiscardToFillAttempts,
add.CustomTitle,
add.GuideMode,
add.PreRollFillerId,
add.MidRollFillerId,
add.PostRollFillerId,
add.TailFillerId,
add.FallbackFillerId,
add.WatermarkIds,
add.GraphicsElementIds,
add.PreferredAudioLanguageCode,
add.PreferredAudioTitle,
add.PreferredSubtitleLanguageCode,
add.SubtitleMode);
}
private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
}
@@ -0,0 +1,122 @@
using System.Reflection;
using ErsatzTV;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Filters;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class ApiControllerSecurityTests
{
private static readonly bool ApiKeyAuthorizationFilterIsGlobal = IsApiKeyAuthorizationFilterRegisteredGlobally();
[Test]
public void Every_Mutating_Api_Action_Should_Be_Globally_Protected_Or_Explicitly_Exempt()
{
Type[] apiControllers =
[
typeof(ChannelController),
typeof(CollectionController),
typeof(FFmpegProfileController),
typeof(LibrariesController),
typeof(MaintenanceController),
typeof(PlayoutController),
typeof(ScannerController),
typeof(ScheduleController),
typeof(ScriptedScheduleController),
typeof(SessionController),
typeof(SmartCollectionController)
];
foreach (Type controllerType in apiControllers)
{
bool controllerSkipsApiKey = controllerType
.GetCustomAttributes<SkipApiKeyAuthorizationAttribute>(inherit: true)
.Any();
foreach (MethodInfo action in controllerType
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
bool isMutating = action
.GetCustomAttributes<HttpMethodAttribute>(inherit: true)
.SelectMany(a => a.HttpMethods)
.Any(m => m is "POST" or "PUT" or "PATCH" or "DELETE");
if (!isMutating)
{
continue;
}
bool actionSkipsApiKey = action
.GetCustomAttributes<SkipApiKeyAuthorizationAttribute>(inherit: true)
.Any();
(controllerSkipsApiKey || actionSkipsApiKey || IsGloballyProtected())
.ShouldBeTrue($"{controllerType.Name}.{action.Name} must be covered by global API write auth or explicitly exempt");
}
}
}
[Test]
public void ScannerController_Should_Be_Only_Api_Key_Exempt_Api_Controller()
{
Type[] exemptControllers = typeof(ScannerController)
.Assembly
.GetTypes()
.Where(t => t.Namespace == typeof(ScannerController).Namespace)
.Where(t => t.GetCustomAttributes<ApiControllerAttribute>(inherit: true).Any())
.Where(t => t.GetCustomAttributes<SkipApiKeyAuthorizationAttribute>(inherit: true).Any())
.ToArray();
exemptControllers.ShouldBe([typeof(ScannerController)]);
}
[Test]
public void Startup_Should_Register_ApiKeyAuthorizationFilter_Globally()
{
ApiKeyAuthorizationFilterIsGlobal.ShouldBeTrue();
}
private static bool IsGloballyProtected() => ApiKeyAuthorizationFilterIsGlobal;
private static bool IsApiKeyAuthorizationFilterRegisteredGlobally()
{
var settings = new Dictionary<string, string?>
{
["provider"] = "sqlite",
["ConnectionStrings:Data"] = "Data Source=:memory:"
};
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(settings)
.Build();
var environment = Substitute.For<IWebHostEnvironment>();
environment.ApplicationName.Returns("ErsatzTV");
environment.EnvironmentName.Returns("Development");
environment.ContentRootPath.Returns(TestContext.CurrentContext.TestDirectory);
environment.WebRootPath.Returns(TestContext.CurrentContext.TestDirectory);
environment.ContentRootFileProvider.Returns(new NullFileProvider());
environment.WebRootFileProvider.Returns(new NullFileProvider());
var services = new ServiceCollection();
new Startup(configuration, environment).ConfigureServices(services);
using ServiceProvider provider = services.BuildServiceProvider();
MvcOptions options = provider.GetRequiredService<IOptions<MvcOptions>>().Value;
return options.Filters
.OfType<ServiceFilterAttribute>()
.Any(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
}
}
@@ -17,6 +17,12 @@ public class ApiErrorResponseMetadataTests
[TestCase(typeof(ChannelController), nameof(ChannelController.Update), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ChannelController), nameof(ChannelController.Delete), StatusCodes.Status404NotFound)]
[TestCase(typeof(ChannelController), nameof(ChannelController.Delete), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ChannelController), nameof(ChannelController.BulkRenumber), StatusCodes.Status404NotFound)]
[TestCase(typeof(ChannelController), nameof(ChannelController.BulkRenumber), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ChannelController), nameof(ChannelController.BulkMoveToGroup), StatusCodes.Status404NotFound)]
[TestCase(typeof(ChannelController), nameof(ChannelController.BulkMoveToGroup), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ChannelController), nameof(ChannelController.BulkDelete), StatusCodes.Status404NotFound)]
[TestCase(typeof(ChannelController), nameof(ChannelController.BulkDelete), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ChannelController), nameof(ChannelController.ResetPlayout), StatusCodes.Status404NotFound)]
[TestCase(typeof(CollectionController), nameof(CollectionController.GetById), StatusCodes.Status404NotFound)]
[TestCase(typeof(CollectionController), nameof(CollectionController.Create), StatusCodes.Status404NotFound)]
@@ -36,6 +42,35 @@ public class ApiErrorResponseMetadataTests
[TestCase(typeof(SmartCollectionController), nameof(SmartCollectionController.Update), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(SmartCollectionController), nameof(SmartCollectionController.Delete), StatusCodes.Status404NotFound)]
[TestCase(typeof(SmartCollectionController), nameof(SmartCollectionController.Delete), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.GetById), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.Create), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.Create), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.Update), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.Update), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.Delete), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.Delete), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.GetItems), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.AddItem), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.AddItem), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.ReplaceItems), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.ReplaceItems), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.DeleteItem), StatusCodes.Status404NotFound)]
[TestCase(typeof(ScheduleController), nameof(ScheduleController.DeleteItem), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(PlayoutController), nameof(PlayoutController.GetById), StatusCodes.Status404NotFound)]
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status404NotFound)]
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Delete), StatusCodes.Status404NotFound)]
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Delete), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.GetById), StatusCodes.Status404NotFound)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.AddOne), StatusCodes.Status404NotFound)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.AddOne), StatusCodes.Status401Unauthorized)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.AddOne), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.UpdateOne), StatusCodes.Status404NotFound)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.UpdateOne), StatusCodes.Status401Unauthorized)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.UpdateOne), StatusCodes.Status422UnprocessableEntity)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.DeleteProfileAsync), StatusCodes.Status404NotFound)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.DeleteProfileAsync), StatusCodes.Status401Unauthorized)]
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.DeleteProfileAsync), StatusCodes.Status422UnprocessableEntity)]
public void Api_Error_Response_Metadata_Should_Document_ProblemDetails(
Type controllerType,
string actionName,
@@ -50,4 +85,5 @@ public class ApiErrorResponseMetadataTests
metadata.ShouldNotBeNull($"{controllerType.Name}.{actionName} should document HTTP {statusCode}");
metadata.Type.ShouldBe(typeof(ProblemDetails));
}
}
@@ -1,62 +0,0 @@
using System.Linq;
using System.Reflection;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Controllers;
/// <summary>
/// Guards the API-key write-path contract for <see cref="ChannelController" />: every mutating
/// action (POST/PUT/PATCH/DELETE) must be covered by <see cref="ApiKeyAuthorizationFilter" />.
/// The filter is applied at the controller level, so this also protects any future write endpoint
/// added to the controller (regression net for the ResetPlayout bypass).
/// </summary>
[TestFixture]
public class ChannelControllerSecurityTests
{
[Test]
public void Controller_Should_Apply_ApiKeyAuthorizationFilter()
{
ServiceFilterAttribute? filter = typeof(ChannelController)
.GetCustomAttributes<ServiceFilterAttribute>(inherit: true)
.SingleOrDefault(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
filter.ShouldNotBeNull("ChannelController must carry the ApiKeyAuthorizationFilter at the class level");
}
[Test]
public void Every_Mutating_Action_Should_Be_Protected()
{
MethodInfo[] actions = typeof(ChannelController)
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
bool controllerHasFilter = typeof(ChannelController)
.GetCustomAttributes<ServiceFilterAttribute>(inherit: true)
.Any(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
foreach (MethodInfo action in actions)
{
bool isMutating = action
.GetCustomAttributes<HttpMethodAttribute>(inherit: true)
.SelectMany(a => a.HttpMethods)
.Any(m =>
m is "POST" or "PUT" or "PATCH" or "DELETE");
if (!isMutating)
{
continue;
}
bool actionHasFilter = action
.GetCustomAttributes<ServiceFilterAttribute>(inherit: true)
.Any(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
(controllerHasFilter || actionHasFilter)
.ShouldBeTrue($"Mutating action {action.Name} is not protected by ApiKeyAuthorizationFilter");
}
}
}
@@ -6,6 +6,7 @@ using ErsatzTV.Application.Playouts;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using LanguageExt;
@@ -34,6 +35,25 @@ public class ChannelControllerTests
_controller = new ChannelController(writer, _mediator);
}
[Test]
public async Task GetState_Should_Return_200_With_Channel_State()
{
var state = new ChannelStateResponseModel(
7,
"7.1",
true,
new ChannelNowPlayingResponseModel(
"Retro Cartoons",
new DateTimeOffset(2026, 7, 2, 17, 0, 0, TimeSpan.Zero),
new DateTimeOffset(2026, 7, 2, 17, 30, 0, TimeSpan.Zero)));
_mediator.Send(Arg.Any<GetChannelStatesForApi>(), Arg.Any<CancellationToken>())
.Returns([state]);
List<ChannelStateResponseModel> result = await _controller.GetState(CancellationToken.None);
result.ShouldBe(new List<ChannelStateResponseModel> { state });
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
@@ -125,6 +145,95 @@ public class ChannelControllerTests
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task BulkRenumber_Should_Return_204_And_Map_Request()
{
_mediator.Send(Arg.Any<UpdateChannelNumbers>(), Arg.Any<CancellationToken>())
.Returns(Option<BaseError>.None);
IActionResult result = await _controller.BulkRenumber(
new BulkRenumberChannelsRequest([new BulkRenumberChannelRequest(1, "10")]),
CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<UpdateChannelNumbers>(
c => c.Channels.Count == 1 && c.Channels[0].Id == 1 && c.Channels[0].Number == "10"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task BulkRenumber_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<UpdateChannelNumbers>(), Arg.Any<CancellationToken>())
.Returns(Option<BaseError>.Some(BaseError.New("bad")));
IActionResult result = await _controller.BulkRenumber(
new BulkRenumberChannelsRequest([new BulkRenumberChannelRequest(1, "bad")]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task BulkMoveToGroup_Should_Return_204_And_Map_Request()
{
_mediator.Send(Arg.Any<BulkMoveChannelsToGroup>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.BulkMoveToGroup(
new BulkMoveChannelsToGroupRequest([1, 2], "Movies"),
CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<BulkMoveChannelsToGroup>(
c => c.ChannelIds.SequenceEqual(new[] { 1, 2 }) && c.Group == "Movies"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task BulkMoveToGroup_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<BulkMoveChannelsToGroup>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(new NotFoundError("missing")));
IActionResult result = await _controller.BulkMoveToGroup(
new BulkMoveChannelsToGroupRequest([99], "Movies"),
CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task BulkDelete_Should_Return_204_And_Map_Request()
{
_mediator.Send(Arg.Any<BulkDeleteChannels>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.BulkDelete(
new BulkDeleteChannelsRequest([1, 2]),
CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<BulkDeleteChannels>(c => c.ChannelIds.SequenceEqual(new[] { 1, 2 })),
Arg.Any<CancellationToken>());
}
[Test]
public async Task BulkDelete_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<BulkDeleteChannels>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(new NotFoundError("missing")));
IActionResult result = await _controller.BulkDelete(
new BulkDeleteChannelsRequest([99]),
CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task GetById_Should_Return_200_For_Some()
{
@@ -1,56 +0,0 @@
using System.Reflection;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class CollectionControllerSecurityTests
{
[TestCase(typeof(CollectionController))]
[TestCase(typeof(SmartCollectionController))]
public void Controller_Should_Apply_ApiKeyAuthorizationFilter(Type controllerType)
{
ServiceFilterAttribute? filter = controllerType
.GetCustomAttributes<ServiceFilterAttribute>(inherit: true)
.SingleOrDefault(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
filter.ShouldNotBeNull($"{controllerType.Name} must carry ApiKeyAuthorizationFilter at the class level");
}
[TestCase(typeof(CollectionController))]
[TestCase(typeof(SmartCollectionController))]
public void Every_Mutating_Action_Should_Be_Protected(Type controllerType)
{
MethodInfo[] actions = controllerType
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
bool controllerHasFilter = controllerType
.GetCustomAttributes<ServiceFilterAttribute>(inherit: true)
.Any(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
foreach (MethodInfo action in actions)
{
bool isMutating = action
.GetCustomAttributes<HttpMethodAttribute>(inherit: true)
.SelectMany(a => a.HttpMethods)
.Any(m => m is "POST" or "PUT" or "PATCH" or "DELETE");
if (!isMutating)
{
continue;
}
bool actionHasFilter = action
.GetCustomAttributes<ServiceFilterAttribute>(inherit: true)
.Any(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
(controllerHasFilter || actionHasFilter)
.ShouldBeTrue($"Mutating action {controllerType.Name}.{action.Name} is not protected");
}
}
}
@@ -0,0 +1,280 @@
using System.Reflection;
using ErsatzTV.Application.FFmpegProfiles;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.FFmpegProfiles;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.FFmpeg;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class FFmpegProfileControllerTests
{
private FFmpegProfileController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new FFmpegProfileController(_mediator);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute("GET", "/api/ffmpeg/profiles");
ShouldHaveActionRoute("GET", "/api/ffmpeg/profiles/{id:int}");
ShouldHaveActionRoute("POST", "/api/ffmpeg/profiles");
ShouldHaveActionRoute("PUT", "/api/ffmpeg/profiles/{id:int}");
ShouldHaveActionRoute("DELETE", "/api/ffmpeg/profiles/{id:int}");
}
[Test]
public void Mutations_Should_Use_Request_Dtos_For_Wire_Contract()
{
ParameterInfo createRequest = typeof(FFmpegProfileController)
.GetMethod(nameof(FFmpegProfileController.AddOne))!
.GetParameters()
.Single(p => p.Name == "request");
ParameterInfo updateRequest = typeof(FFmpegProfileController)
.GetMethod(nameof(FFmpegProfileController.UpdateOne))!
.GetParameters()
.Single(p => p.Name == "request");
createRequest.ParameterType.ShouldBe(typeof(CreateFFmpegProfileRequest));
updateRequest.ParameterType.ShouldBe(typeof(UpdateFFmpegProfileRequest));
}
[Test]
public async Task GetById_Should_Return_200_For_Some()
{
FFmpegFullProfileResponseModel vm = MakeVm(4);
_mediator.Send(Arg.Any<GetFFmpegFullProfileByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FFmpegFullProfileResponseModel>.Some(vm));
IActionResult result = await _controller.GetById(4, CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
}
[Test]
public async Task GetById_Should_Return_404_For_None()
{
_mediator.Send(Arg.Any<GetFFmpegFullProfileByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FFmpegFullProfileResponseModel>.None);
IActionResult result = await _controller.GetById(4, CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
var problemDetails = notFound.Value.ShouldBeOfType<ProblemDetails>();
problemDetails.Status.ShouldBe(404);
problemDetails.Title.ShouldBe("Resource not found");
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
_mediator.Send(Arg.Any<CreateFFmpegProfile>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, CreateFFmpegProfileResult>(new CreateFFmpegProfileResult(7)));
FFmpegFullProfileResponseModel vm = MakeVm(7);
_mediator.Send(Arg.Any<GetFFmpegFullProfileByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FFmpegFullProfileResponseModel>.Some(vm));
IActionResult result = await _controller.AddOne(MakeCreateRequest(), CancellationToken.None);
var created = result.ShouldBeOfType<CreatedResult>();
created.StatusCode.ShouldBe(201);
created.Location.ShouldBe("/api/ffmpeg/profiles/7");
created.Value.ShouldBe(vm);
}
[Test]
public async Task Create_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<CreateFFmpegProfile>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, CreateFFmpegProfileResult>(BaseError.New("bad")));
IActionResult result = await _controller.AddOne(MakeCreateRequest(), CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task Create_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<CreateFFmpegProfile>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, CreateFFmpegProfileResult>(new NotFoundError("missing")));
IActionResult result = await _controller.AddOne(MakeCreateRequest(), CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task Update_Should_Return_200_And_Map_Route_Id_To_Command()
{
_mediator.Send(Arg.Any<UpdateFFmpegProfile>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, UpdateFFmpegProfileResult>(new UpdateFFmpegProfileResult(8)));
FFmpegFullProfileResponseModel vm = MakeVm(8);
_mediator.Send(Arg.Any<GetFFmpegFullProfileByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FFmpegFullProfileResponseModel>.Some(vm));
IActionResult result = await _controller.UpdateOne(8, MakeUpdateRequest(), CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
await _mediator.Received(1).Send(
Arg.Is<UpdateFFmpegProfile>(c => c.FFmpegProfileId == 8),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Update_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<UpdateFFmpegProfile>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, UpdateFFmpegProfileResult>(new NotFoundError("missing")));
IActionResult result = await _controller.UpdateOne(99, MakeUpdateRequest(), CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task Delete_Should_Return_204_On_Success()
{
_mediator.Send(Arg.Any<DeleteFFmpegProfile>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.DeleteProfileAsync(9, CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
}
[Test]
public async Task Delete_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<DeleteFFmpegProfile>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(new NotFoundError("missing")));
IActionResult result = await _controller.DeleteProfileAsync(9, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
private static void ShouldHaveActionRoute(string httpMethod, string route)
{
bool exists = typeof(FFmpegProfileController)
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.SelectMany(m => m.GetCustomAttributes<HttpMethodAttribute>(inherit: true))
.Any(a => a.HttpMethods.Contains(httpMethod) && a.Template == route);
exists.ShouldBeTrue($"Missing route {httpMethod} {route}");
}
private static FFmpegFullProfileResponseModel MakeVm(int id) =>
new(
id,
"Default",
1,
HardwareAccelerationKind.None,
"drm",
VaapiDriver.Default,
"/dev/dri/renderD128",
null,
"HD",
ScalingBehavior.ScaleAndPad,
FFmpegProfileVideoFormat.H264,
string.Empty,
string.Empty,
false,
FFmpegProfileBitDepth.EightBit,
2_000,
4_000,
FFmpegProfileTonemapAlgorithm.Linear,
FFmpegProfileAudioFormat.Aac,
192,
384,
NormalizeLoudnessMode.Off,
2,
48_000,
false,
false);
private static CreateFFmpegProfileRequest MakeCreateRequest() =>
new(
"Default",
1,
true,
true,
HardwareAccelerationKind.None,
"drm",
VaapiDriver.Default,
"/dev/dri/renderD128",
null,
1,
ScalingBehavior.ScaleAndPad,
FilterMode.Software,
FFmpegProfileVideoFormat.H264,
string.Empty,
string.Empty,
false,
FFmpegProfileBitDepth.EightBit,
2_000,
4_000,
FFmpegProfileTonemapAlgorithm.Linear,
FFmpegProfileAudioFormat.Aac,
192,
384,
NormalizeLoudnessMode.Off,
null,
2,
48_000,
false,
false,
false);
private static UpdateFFmpegProfileRequest MakeUpdateRequest() =>
new(
"Default",
1,
true,
true,
HardwareAccelerationKind.None,
"drm",
VaapiDriver.Default,
"/dev/dri/renderD128",
null,
1,
ScalingBehavior.ScaleAndPad,
FilterMode.Software,
FFmpegProfileVideoFormat.H264,
string.Empty,
string.Empty,
false,
FFmpegProfileBitDepth.EightBit,
2_000,
4_000,
FFmpegProfileTonemapAlgorithm.Linear,
FFmpegProfileAudioFormat.Aac,
192,
384,
NormalizeLoudnessMode.Off,
null,
2,
48_000,
false,
false,
false);
}
@@ -7,6 +7,98 @@ namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class OpenApiErrorResponseContractTests
{
[Test]
public void Static_OpenApi_Should_Document_Schedule_Item_Discriminator_As_String_Enum()
{
using JsonDocument document = JsonDocument.Parse(File.ReadAllText(FindOpenApiDocument()));
JsonElement playoutMode = document.RootElement
.GetProperty("components")
.GetProperty("schemas")
.GetProperty("PlayoutMode");
playoutMode.GetProperty("type").GetString().ShouldBe("string");
playoutMode.GetProperty("enum").EnumerateArray()
.Select(e => e.GetString())
.ShouldContain("One");
}
[Test]
public void Static_OpenApi_Should_Document_Channel_List_Management_Fields()
{
using JsonDocument document = JsonDocument.Parse(File.ReadAllText(FindOpenApiDocument()));
JsonElement schema = document.RootElement
.GetProperty("components")
.GetProperty("schemas")
.GetProperty("ChannelResponseModel")
.GetProperty("properties");
schema.TryGetProperty("group", out _).ShouldBeTrue();
schema.TryGetProperty("isEnabled", out _).ShouldBeTrue();
schema.TryGetProperty("showInEpg", out _).ShouldBeTrue();
schema.TryGetProperty("sortNumber", out _).ShouldBeTrue();
schema.TryGetProperty("categories", out _).ShouldBeTrue();
}
[Test]
public void Static_OpenApi_Should_Document_Channel_State_Response()
{
using JsonDocument document = JsonDocument.Parse(File.ReadAllText(FindOpenApiDocument()));
JsonElement getState = document.RootElement
.GetProperty("paths")
.GetProperty("/api/channels/state")
.GetProperty("get");
JsonElement schema = getState
.GetProperty("responses")
.GetProperty("200")
.GetProperty("content")
.GetProperty("application/json")
.GetProperty("schema");
schema.GetProperty("type").GetString().ShouldBe("array");
schema.GetProperty("items").GetProperty("$ref").GetString()
.ShouldBe("#/components/schemas/ChannelStateResponseModel");
JsonElement stateProperties = document.RootElement
.GetProperty("components")
.GetProperty("schemas")
.GetProperty("ChannelStateResponseModel")
.GetProperty("properties");
stateProperties.TryGetProperty("channelId", out _).ShouldBeTrue();
stateProperties.TryGetProperty("channelNumber", out _).ShouldBeTrue();
stateProperties.TryGetProperty("onAir", out _).ShouldBeTrue();
stateProperties.TryGetProperty("nowPlaying", out JsonElement nowPlaying).ShouldBeTrue();
JsonElement nowPlayingOneOf = nowPlaying.GetProperty("oneOf");
nowPlayingOneOf.EnumerateArray().Count().ShouldBe(2);
nowPlayingOneOf.EnumerateArray()
.Any(s => s.TryGetProperty("type", out JsonElement type) && type.GetString() == "null")
.ShouldBeTrue();
nowPlayingOneOf.EnumerateArray()
.Any(s => s.TryGetProperty("$ref", out JsonElement schemaRef) &&
schemaRef.GetString() == "#/components/schemas/ChannelNowPlayingResponseModel")
.ShouldBeTrue();
JsonElement nowPlayingProperties = document.RootElement
.GetProperty("components")
.GetProperty("schemas")
.GetProperty("ChannelNowPlayingResponseModel")
.GetProperty("properties");
nowPlayingProperties.TryGetProperty("title", out _).ShouldBeTrue();
nowPlayingProperties.TryGetProperty("startUtc", out JsonElement startUtc).ShouldBeTrue();
nowPlayingProperties.TryGetProperty("finishUtc", out JsonElement finishUtc).ShouldBeTrue();
startUtc.GetProperty("type").GetString().ShouldBe("string");
startUtc.GetProperty("format").GetString().ShouldBe("date-time");
finishUtc.GetProperty("type").GetString().ShouldBe("string");
finishUtc.GetProperty("format").GetString().ShouldBe("date-time");
}
[TestCase("/api/channels/{id}", "get", "404")]
[TestCase("/api/channels", "post", "404")]
[TestCase("/api/channels", "post", "422")]
@@ -14,6 +106,12 @@ public class OpenApiErrorResponseContractTests
[TestCase("/api/channels/{id}", "put", "422")]
[TestCase("/api/channels/{id}", "delete", "404")]
[TestCase("/api/channels/{id}", "delete", "422")]
[TestCase("/api/channels/bulk/renumber", "post", "404")]
[TestCase("/api/channels/bulk/renumber", "post", "422")]
[TestCase("/api/channels/bulk/group", "post", "404")]
[TestCase("/api/channels/bulk/group", "post", "422")]
[TestCase("/api/channels/bulk/delete", "post", "404")]
[TestCase("/api/channels/bulk/delete", "post", "422")]
[TestCase("/api/channels/{channelNumber}/playout/reset", "post", "404")]
[TestCase("/api/collections/{id}", "get", "404")]
[TestCase("/api/collections", "post", "404")]
@@ -33,6 +131,35 @@ public class OpenApiErrorResponseContractTests
[TestCase("/api/smart-collections/{id}", "put", "422")]
[TestCase("/api/smart-collections/{id}", "delete", "404")]
[TestCase("/api/smart-collections/{id}", "delete", "422")]
[TestCase("/api/schedules/{id}", "get", "404")]
[TestCase("/api/schedules", "post", "404")]
[TestCase("/api/schedules", "post", "422")]
[TestCase("/api/schedules/{id}", "put", "404")]
[TestCase("/api/schedules/{id}", "put", "422")]
[TestCase("/api/schedules/{id}", "delete", "404")]
[TestCase("/api/schedules/{id}", "delete", "422")]
[TestCase("/api/schedules/{id}/items", "get", "404")]
[TestCase("/api/schedules/{id}/items", "post", "404")]
[TestCase("/api/schedules/{id}/items", "post", "422")]
[TestCase("/api/schedules/{id}/items", "put", "404")]
[TestCase("/api/schedules/{id}/items", "put", "422")]
[TestCase("/api/schedules/{id}/items/{itemId}", "delete", "404")]
[TestCase("/api/schedules/{id}/items/{itemId}", "delete", "422")]
[TestCase("/api/playouts/{id}", "get", "404")]
[TestCase("/api/playouts", "post", "404")]
[TestCase("/api/playouts", "post", "422")]
[TestCase("/api/playouts/{id}", "delete", "404")]
[TestCase("/api/playouts/{id}", "delete", "422")]
[TestCase("/api/ffmpeg/profiles/{id}", "get", "404")]
[TestCase("/api/ffmpeg/profiles", "post", "404")]
[TestCase("/api/ffmpeg/profiles", "post", "401")]
[TestCase("/api/ffmpeg/profiles", "post", "422")]
[TestCase("/api/ffmpeg/profiles/{id}", "put", "404")]
[TestCase("/api/ffmpeg/profiles/{id}", "put", "401")]
[TestCase("/api/ffmpeg/profiles/{id}", "put", "422")]
[TestCase("/api/ffmpeg/profiles/{id}", "delete", "404")]
[TestCase("/api/ffmpeg/profiles/{id}", "delete", "401")]
[TestCase("/api/ffmpeg/profiles/{id}", "delete", "422")]
public void Static_OpenApi_Should_Document_ProblemDetails_For_Api_Error_Responses(
string path,
string method,
@@ -0,0 +1,197 @@
using System.Reflection;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Playouts;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class PlayoutControllerTests
{
private PlayoutController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new PlayoutController(_mediator);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute(nameof(PlayoutController.GetById), "GET", "/api/playouts/{id:int}");
ShouldHaveActionRoute(nameof(PlayoutController.Create), "POST", "/api/playouts");
ShouldHaveActionRoute(nameof(PlayoutController.Delete), "DELETE", "/api/playouts/{id:int}");
}
[Test]
public void Create_Should_Use_Stable_Request_Dto()
{
MethodInfo action = typeof(PlayoutController).GetMethod(nameof(PlayoutController.Create))
?? throw new AssertionException($"Missing action {nameof(PlayoutController.Create)}");
action.GetParameters()[0].ParameterType.ShouldBe(typeof(CreatePlayoutRequest));
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
_mediator.Send(Arg.Any<CreateClassicPlayout>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, CreatePlayoutResponse>(new CreatePlayoutResponse(9)));
PlayoutNameViewModel vm = MakePlayout(9);
_mediator.Send(Arg.Any<GetPlayoutById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlayoutNameViewModel>.Some(vm));
IActionResult result = await _controller.Create(new CreatePlayoutRequest(3, 4), CancellationToken.None);
var created = result.ShouldBeOfType<CreatedResult>();
created.StatusCode.ShouldBe(201);
created.Location.ShouldBe("/api/playouts/9");
created.Value.ShouldBe(ToResponse(vm));
}
[Test]
public async Task Create_Should_Map_Request_To_Classic_Playout_Command()
{
_mediator.Send(Arg.Any<CreateClassicPlayout>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, CreatePlayoutResponse>(new CreatePlayoutResponse(9)));
_mediator.Send(Arg.Any<GetPlayoutById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlayoutNameViewModel>.Some(MakePlayout(9)));
await _controller.Create(new CreatePlayoutRequest(3, 4), CancellationToken.None);
await _mediator.Received(1).Send(
Arg.Is<CreateClassicPlayout>(c => c.ChannelId == 3 && c.ProgramScheduleId == 4),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Create_Should_Return_404_For_NotFoundError_With_ProblemDetails()
{
_mediator.Send(Arg.Any<CreateClassicPlayout>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, CreatePlayoutResponse>(new NotFoundError("missing")));
IActionResult result = await _controller.Create(new CreatePlayoutRequest(404, 4), CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
var problem = notFound.Value.ShouldBeOfType<ProblemDetails>();
problem.Status.ShouldBe(404);
problem.Title.ShouldBe("Resource not found");
}
[Test]
public async Task Create_Should_Return_422_On_Validation_Error_With_ProblemDetails()
{
_mediator.Send(Arg.Any<CreateClassicPlayout>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, CreatePlayoutResponse>(BaseError.New("bad")));
IActionResult result = await _controller.Create(new CreatePlayoutRequest(3, 4), CancellationToken.None);
var unprocessable = result.ShouldBeOfType<UnprocessableEntityObjectResult>();
var problem = unprocessable.Value.ShouldBeOfType<ProblemDetails>();
problem.Status.ShouldBe(422);
problem.Title.ShouldBe("Validation failed");
}
[Test]
public async Task Delete_Should_Return_204_On_Success()
{
_mediator.Send(Arg.Any<DeletePlayout>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.Delete(9, CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<DeletePlayout>(c => c.PlayoutId == 9),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Delete_Should_Return_404_For_NotFoundError_With_ProblemDetails()
{
_mediator.Send(Arg.Any<DeletePlayout>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(new NotFoundError("missing")));
IActionResult result = await _controller.Delete(404, CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
var problem = notFound.Value.ShouldBeOfType<ProblemDetails>();
problem.Status.ShouldBe(404);
problem.Title.ShouldBe("Resource not found");
}
[Test]
public async Task GetById_Should_Return_200_For_Some()
{
PlayoutNameViewModel vm = MakePlayout(9);
_mediator.Send(Arg.Any<GetPlayoutById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlayoutNameViewModel>.Some(vm));
IActionResult result = await _controller.GetById(9, CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(ToResponse(vm));
}
[Test]
public async Task GetById_Should_Return_404_For_None_With_ProblemDetails()
{
_mediator.Send(Arg.Any<GetPlayoutById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlayoutNameViewModel>.None);
IActionResult result = await _controller.GetById(9, CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
var problem = notFound.Value.ShouldBeOfType<ProblemDetails>();
problem.Status.ShouldBe(404);
problem.Title.ShouldBe("Resource not found");
}
private static PlayoutNameViewModel MakePlayout(int id) =>
new(
id,
PlayoutScheduleKind.Classic,
"Channel",
"101",
ChannelPlayoutMode.Continuous,
"Schedule",
string.Empty,
null,
new PlayoutBuildStatus());
private static PlayoutResponseModel ToResponse(PlayoutNameViewModel vm) =>
PlayoutResponseModel.From(
vm.PlayoutId,
vm.ScheduleKind,
vm.ChannelName,
vm.ChannelNumber,
vm.PlayoutMode,
vm.ScheduleName,
vm.ScheduleFile,
vm.DbDailyRebuildTime);
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
{
MethodInfo action = typeof(PlayoutController).GetMethod(actionName)
?? throw new AssertionException($"Missing action {actionName}");
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain(httpMethod);
attribute.Template.ShouldBe(route);
}
}
@@ -0,0 +1,383 @@
using System.Reflection;
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class ScheduleControllerTests
{
private ScheduleController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new ScheduleController(_mediator);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute(nameof(ScheduleController.GetAll), "GET", "/api/schedules");
ShouldHaveActionRoute(nameof(ScheduleController.GetById), "GET", "/api/schedules/{id:int}");
ShouldHaveActionRoute(nameof(ScheduleController.Create), "POST", "/api/schedules");
ShouldHaveActionRoute(nameof(ScheduleController.Update), "PUT", "/api/schedules/{id:int}");
ShouldHaveActionRoute(nameof(ScheduleController.Delete), "DELETE", "/api/schedules/{id:int}");
ShouldHaveActionRoute(nameof(ScheduleController.GetItems), "GET", "/api/schedules/{id:int}/items");
ShouldHaveActionRoute(nameof(ScheduleController.AddItem), "POST", "/api/schedules/{id:int}/items");
ShouldHaveActionRoute(nameof(ScheduleController.ReplaceItems), "PUT", "/api/schedules/{id:int}/items");
ShouldHaveActionRoute(
nameof(ScheduleController.DeleteItem),
"DELETE",
"/api/schedules/{id:int}/items/{itemId:int}");
}
[Test]
public void Update_Should_Use_Stable_Update_Request_Dto()
{
MethodInfo action = typeof(ScheduleController).GetMethod(nameof(ScheduleController.Update))
?? throw new AssertionException($"Missing action {nameof(ScheduleController.Update)}");
action.GetParameters()[1].ParameterType.ShouldBe(typeof(UpdateScheduleRequest));
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
_mediator.Send(Arg.Any<CreateProgramSchedule>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, CreateProgramScheduleResult>(new CreateProgramScheduleResult(5)));
ProgramScheduleViewModel vm = MakeSchedule(5, "Daily");
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.Some(vm));
IActionResult result = await _controller.Create(MakeScheduleRequest("Daily"), CancellationToken.None);
var created = result.ShouldBeOfType<CreatedResult>();
created.StatusCode.ShouldBe(201);
created.Location.ShouldBe("/api/schedules/5");
created.Value.ShouldBe(vm);
}
[Test]
public async Task Create_Should_Return_422_On_Validation_Error_With_ProblemDetails()
{
_mediator.Send(Arg.Any<CreateProgramSchedule>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, CreateProgramScheduleResult>(BaseError.New("bad")));
IActionResult result = await _controller.Create(MakeScheduleRequest(string.Empty), CancellationToken.None);
var unprocessable = result.ShouldBeOfType<UnprocessableEntityObjectResult>();
var problem = unprocessable.Value.ShouldBeOfType<ProblemDetails>();
problem.Status.ShouldBe(422);
problem.Title.ShouldBe("Validation failed");
}
[Test]
public async Task Create_Should_Map_Request_To_Command()
{
_mediator.Send(Arg.Any<CreateProgramSchedule>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, CreateProgramScheduleResult>(new CreateProgramScheduleResult(5)));
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.Some(MakeSchedule(5, "Daily")));
await _controller.Create(MakeScheduleRequest("Daily"), CancellationToken.None);
await _mediator.Received(1).Send(
Arg.Is<CreateProgramSchedule>(c =>
c.Name == "Daily" &&
c.KeepMultiPartEpisodesTogether &&
c.TreatCollectionsAsShows &&
c.ShuffleScheduleItems &&
c.RandomStartPoint &&
c.FixedStartTimeBehavior == FixedStartTimeBehavior.Flexible),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Update_Should_Return_200_And_Map_Route_Id()
{
_mediator.Send(Arg.Any<UpdateProgramSchedule>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, UpdateProgramScheduleResult>(new UpdateProgramScheduleResult(7)));
ProgramScheduleViewModel vm = MakeSchedule(7, "Updated");
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.Some(vm));
IActionResult result = await _controller.Update(7, MakeUpdateScheduleRequest("Updated"), CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
await _mediator.Received(1).Send(
Arg.Is<UpdateProgramSchedule>(c => c.ProgramScheduleId == 7 && c.Name == "Updated"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Update_Should_Return_404_For_NotFoundError_With_ProblemDetails()
{
_mediator.Send(Arg.Any<UpdateProgramSchedule>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, UpdateProgramScheduleResult>(new NotFoundError("missing")));
IActionResult result = await _controller.Update(99, MakeUpdateScheduleRequest("Missing"), CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
var problem = notFound.Value.ShouldBeOfType<ProblemDetails>();
problem.Status.ShouldBe(404);
problem.Title.ShouldBe("Resource not found");
}
[Test]
public async Task Delete_Should_Return_204_On_Success()
{
_mediator.Send(Arg.Any<DeleteProgramSchedule>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.Delete(3, CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
}
[Test]
public async Task Delete_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<DeleteProgramSchedule>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(new NotFoundError("missing")));
IActionResult result = await _controller.Delete(99, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task GetById_Should_Return_200_For_Some()
{
ProgramScheduleViewModel vm = MakeSchedule(4, "Daily");
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.Some(vm));
IActionResult result = await _controller.GetById(4, CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
}
[Test]
public async Task GetById_Should_Return_404_For_None()
{
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.None);
IActionResult result = await _controller.GetById(4, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task GetItems_Should_Return_200_With_Items()
{
List<ProgramScheduleItemViewModel> items = [MakeOneItem(11)];
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.Some(MakeSchedule(4, "Daily")));
_mediator.Send(Arg.Any<GetProgramScheduleItems>(), Arg.Any<CancellationToken>())
.Returns(items);
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(items);
}
[Test]
public async Task GetItems_Should_Return_404_When_Schedule_Missing()
{
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.None);
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task AddItem_Should_Return_201_With_Location_And_Map_Route_Id()
{
ProgramScheduleItemViewModel item = MakeOneItem(12);
_mediator.Send(Arg.Any<AddProgramScheduleItem>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, ProgramScheduleItemViewModel>(item));
IActionResult result = await _controller.AddItem(4, MakeItemRequest(PlayoutMode.One), CancellationToken.None);
var created = result.ShouldBeOfType<CreatedResult>();
created.Location.ShouldBe("/api/schedules/4/items/12");
created.Value.ShouldBe(item);
await _mediator.Received(1).Send(
Arg.Is<AddProgramScheduleItem>(c => c.ProgramScheduleId == 4 && c.PlayoutMode == PlayoutMode.One),
Arg.Any<CancellationToken>());
}
[Test]
public async Task AddItem_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<AddProgramScheduleItem>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, ProgramScheduleItemViewModel>(BaseError.New("bad")));
IActionResult result = await _controller.AddItem(4, MakeItemRequest(PlayoutMode.Duration), CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task ReplaceItems_Should_Return_200_With_Items_And_Map_Route_Id()
{
List<ProgramScheduleItemViewModel> items = [MakeOneItem(21), MakeOneItem(22)];
_mediator.Send(Arg.Any<ReplaceProgramScheduleItems>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, IEnumerable<ProgramScheduleItemViewModel>>(items));
IActionResult result = await _controller.ReplaceItems(
4,
new ReplaceScheduleItemsRequest([MakeItemRequest(PlayoutMode.One), MakeItemRequest(PlayoutMode.Multiple)]),
CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(items);
await _mediator.Received(1).Send(
Arg.Is<ReplaceProgramScheduleItems>(c =>
c.ProgramScheduleId == 4 &&
c.Items.Count == 2 &&
c.Items[0].Index == 0 &&
c.Items[1].PlayoutMode == PlayoutMode.Multiple),
Arg.Any<CancellationToken>());
}
[Test]
public async Task DeleteItem_Should_Return_204_And_Map_Route_Ids()
{
_mediator.Send(Arg.Any<DeleteProgramScheduleItem>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.DeleteItem(4, 12, CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<DeleteProgramScheduleItem>(c => c.ProgramScheduleId == 4 && c.ProgramScheduleItemId == 12),
Arg.Any<CancellationToken>());
}
private static CreateScheduleRequest MakeScheduleRequest(string name) =>
new(
name,
KeepMultiPartEpisodesTogether: true,
TreatCollectionsAsShows: true,
ShuffleScheduleItems: true,
RandomStartPoint: true,
FixedStartTimeBehavior: FixedStartTimeBehavior.Flexible);
private static UpdateScheduleRequest MakeUpdateScheduleRequest(string name) =>
new(
name,
KeepMultiPartEpisodesTogether: true,
TreatCollectionsAsShows: true,
ShuffleScheduleItems: true,
RandomStartPoint: true,
FixedStartTimeBehavior: FixedStartTimeBehavior.Flexible);
private static ScheduleItemRequest MakeItemRequest(PlayoutMode playoutMode) =>
new(
StartType.Dynamic,
StartTime: null,
FixedStartTimeBehavior: null,
playoutMode,
CollectionType.SearchQuery,
CollectionId: null,
MultiCollectionId: null,
SmartCollectionId: null,
RerunCollectionId: null,
MediaItemId: null,
PlaylistId: null,
SearchTitle: "News",
SearchQuery: "news",
PlaybackOrder: PlaybackOrder.Shuffle,
MarathonGroupBy: MarathonGroupBy.None,
MarathonShuffleGroups: false,
MarathonShuffleItems: false,
MarathonBatchSize: null,
FillWithGroupMode: FillWithGroupMode.None,
MultipleMode: MultipleMode.Count,
MultipleCount: "2",
PlayoutDuration: TimeSpan.FromMinutes(30),
TailMode: TailMode.None,
DiscardToFillAttempts: 3,
CustomTitle: null,
GuideMode: GuideMode.Normal,
PreRollFillerId: null,
MidRollFillerId: null,
PostRollFillerId: null,
TailFillerId: null,
FallbackFillerId: null,
WatermarkIds: [],
GraphicsElementIds: [],
PreferredAudioLanguageCode: null,
PreferredAudioTitle: null,
PreferredSubtitleLanguageCode: null,
SubtitleMode: null);
private static ProgramScheduleViewModel MakeSchedule(int id, string name) =>
new(id, name, true, true, false, false, FixedStartTimeBehavior.Flexible);
private static ProgramScheduleItemOneViewModel MakeOneItem(int id) =>
new(
id,
0,
StartType.Dynamic,
null,
null,
CollectionType.SearchQuery,
null,
null,
null,
null,
null,
null,
"News",
"news",
PlaybackOrder.Shuffle,
MarathonGroupBy.None,
false,
false,
null,
FillWithGroupMode.None,
null,
GuideMode.Normal,
null,
null,
null,
null,
null,
[],
[],
null,
null,
null,
null);
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
{
MethodInfo action = typeof(ScheduleController).GetMethod(actionName)
?? throw new AssertionException($"Missing action {actionName}");
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain(httpMethod);
attribute.Template.ShouldBe(route);
}
}
@@ -5,7 +5,6 @@ using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.SmartCollections;
using ErsatzTV.Core.Errors;
using ErsatzTV.Filters;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Mvc;
@@ -41,16 +40,6 @@ public class SmartCollectionControllerTests
ShouldHaveActionRoute(nameof(SmartCollectionController.Delete), "DELETE", "/api/smart-collections/{id:int}");
}
[Test]
public void Controller_Should_Apply_ApiKeyAuthorizationFilter()
{
ServiceFilterAttribute? filter = typeof(SmartCollectionController)
.GetCustomAttributes<ServiceFilterAttribute>(inherit: true)
.SingleOrDefault(a => a.ServiceType == typeof(ApiKeyAuthorizationFilter));
filter.ShouldNotBeNull("SmartCollectionController must carry ApiKeyAuthorizationFilter at the class level");
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
@@ -14,16 +14,27 @@ namespace ErsatzTV.Tests.Filters;
[TestFixture]
public class ApiKeyAuthorizationFilterTests
{
private static AuthorizationFilterContext MakeContext(string method, string? apiKeyHeader)
private static AuthorizationFilterContext MakeContext(
string method,
string? apiKeyHeader,
string path = "/api/channels",
bool skipApiKeyAuthorization = false)
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = method;
httpContext.Request.Path = path;
if (apiKeyHeader is not null)
{
httpContext.Request.Headers[ApiKeyAuthorizationFilter.HeaderName] = apiKeyHeader;
}
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var actionDescriptor = new ActionDescriptor();
if (skipApiKeyAuthorization)
{
actionDescriptor.EndpointMetadata = [new SkipApiKeyAuthorizationAttribute()];
}
var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor);
return new AuthorizationFilterContext(actionContext, new List<IFilterMetadata>());
}
@@ -60,7 +71,10 @@ public class ApiKeyAuthorizationFilterTests
{
AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null);
MakeFilter(configuredKey: "secret").OnAuthorization(context);
context.Result.ShouldBeOfType<UnauthorizedResult>();
var result = context.Result.ShouldBeOfType<UnauthorizedObjectResult>();
var problemDetails = result.Value.ShouldBeOfType<ProblemDetails>();
problemDetails.Status.ShouldBe(StatusCodes.Status401Unauthorized);
problemDetails.Title.ShouldBe("Unauthorized");
}
[Test]
@@ -68,7 +82,10 @@ public class ApiKeyAuthorizationFilterTests
{
AuthorizationFilterContext context = MakeContext("DELETE", apiKeyHeader: "wrong");
MakeFilter(configuredKey: "secret").OnAuthorization(context);
context.Result.ShouldBeOfType<UnauthorizedResult>();
var result = context.Result.ShouldBeOfType<UnauthorizedObjectResult>();
var problemDetails = result.Value.ShouldBeOfType<ProblemDetails>();
problemDetails.Status.ShouldBe(StatusCodes.Status401Unauthorized);
problemDetails.Title.ShouldBe("Unauthorized");
}
[Test]
@@ -86,4 +103,25 @@ public class ApiKeyAuthorizationFilterTests
MakeFilter(configuredKey: "secret").OnAuthorization(context);
context.Result.ShouldBeNull();
}
[Test]
public void Should_Allow_Non_Api_Mutating_Request_Even_When_Key_Configured()
{
AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null, path: "/iptv/channels.m3u");
MakeFilter(configuredKey: "secret").OnAuthorization(context);
context.Result.ShouldBeNull();
}
[Test]
public void Should_Allow_Api_Mutating_Request_When_Endpoint_Skips_Api_Key_Authorization()
{
AuthorizationFilterContext context = MakeContext(
"POST",
apiKeyHeader: null,
path: "/api/scan/0f8fad5b-d9cb-469f-a165-70867728950e/progress",
skipApiKeyAuthorization: true);
MakeFilter(configuredKey: "secret").OnAuthorization(context);
context.Result.ShouldBeNull();
}
}
@@ -0,0 +1,130 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Testably.Abstractions.Testing;
using Unit = LanguageExt.Unit;
using Channel = System.Threading.Channels.Channel;
namespace ErsatzTV.Tests.Integration;
[TestFixture]
public class PlayoutLifecycleIntegrationTests
{
private InMemoryTvContext _db = null!;
private Channel<IBackgroundServiceRequest> _worker = null!;
[SetUp]
public async Task SetUp()
{
_db = await InMemoryTvContext.CreateAsync();
_worker = Channel.CreateUnbounded<IBackgroundServiceRequest>();
}
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
[Test]
public async Task CreateClassic_Should_Link_Channel_And_Schedule_And_Enqueue_Build()
{
(int channelId, int scheduleId) = await SeedChannelAndSchedule();
var handler = new CreateClassicPlayoutHandler(_worker.Writer, _db.Factory);
Either<BaseError, CreatePlayoutResponse> result =
await handler.Handle(new CreateClassicPlayout(channelId, scheduleId), CancellationToken.None);
CreatePlayoutResponse response = result.Match(
Right: r => r,
Left: error => throw new AssertionException(error.Value));
await using TvContext context = _db.CreateContext();
Playout playout = await context.Playouts.SingleAsync();
playout.Id.ShouldBe(response.PlayoutId);
playout.ChannelId.ShouldBe(channelId);
playout.ProgramScheduleId.ShouldBe(scheduleId);
playout.ScheduleKind.ShouldBe(PlayoutScheduleKind.Classic);
IBackgroundServiceRequest backgroundRequest = await _worker.Reader.ReadAsync();
backgroundRequest.ShouldBeOfType<BuildPlayout>().PlayoutId.ShouldBe(playout.Id);
}
[Test]
public async Task Delete_Should_Remove_Playout_Without_Deleting_Channel_Or_Schedule()
{
(int channelId, int scheduleId) = await SeedChannelAndSchedule();
var createHandler = new CreateClassicPlayoutHandler(_worker.Writer, _db.Factory);
int playoutId = (await createHandler.Handle(new CreateClassicPlayout(channelId, scheduleId), CancellationToken.None))
.Match(Right: r => r.PlayoutId, Left: error => throw new AssertionException(error.Value));
var deleteHandler = new DeletePlayoutHandler(
_worker.Writer,
_db.Factory,
new MockFileSystem(),
Substitute.For<IMediator>());
Either<BaseError, Unit> result = await deleteHandler.Handle(new DeletePlayout(playoutId), CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext context = _db.CreateContext();
(await context.Playouts.CountAsync()).ShouldBe(0);
(await context.Channels.CountAsync(c => c.Id == channelId)).ShouldBe(1);
(await context.ProgramSchedules.CountAsync(ps => ps.Id == scheduleId)).ShouldBe(1);
}
private async Task<(int ChannelId, int ScheduleId)> SeedChannelAndSchedule()
{
await using TvContext context = _db.CreateContext();
var channel = new ErsatzTV.Core.Domain.Channel(Guid.NewGuid())
{
Number = "101",
SortNumber = 101,
Name = "Lifecycle",
Group = string.Empty,
Categories = string.Empty,
StreamingMode = StreamingMode.HttpLiveStreamingSegmenter,
Playouts = [],
Artwork = [],
StreamSelector = string.Empty,
PreferredAudioLanguageCode = string.Empty,
PreferredAudioTitle = string.Empty,
PreferredSubtitleLanguageCode = string.Empty,
MusicVideoCreditsTemplate = string.Empty,
PlayoutSource = ChannelPlayoutSource.Generated,
PlayoutMode = ChannelPlayoutMode.Continuous,
IsEnabled = true,
ShowInEpg = true
};
var schedule = new ProgramSchedule
{
Name = "Lifecycle",
Items =
[
new ProgramScheduleItemOne
{
Index = 0,
CollectionType = CollectionType.SearchQuery,
SearchQuery = "news",
PlaybackOrder = PlaybackOrder.Shuffle,
GuideMode = GuideMode.Normal,
Watermarks = [],
GraphicsElements = []
}
],
Playouts = [],
ProgramScheduleAlternates = []
};
context.Channels.Add(channel);
context.ProgramSchedules.Add(schedule);
await context.SaveChangesAsync();
return (channel.Id, schedule.Id);
}
}
@@ -0,0 +1,188 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Integration;
[TestFixture]
public class ScheduleItemTptIntegrationTests
{
private InMemoryTvContext _db = null!;
private ChannelWriter<IBackgroundServiceRequest> _worker = null!;
[SetUp]
public async Task SetUp()
{
_db = await InMemoryTvContext.CreateAsync();
_worker = System.Threading.Channels.Channel.CreateUnbounded<IBackgroundServiceRequest>().Writer;
}
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
[Test]
public async Task AddProgramScheduleItem_Should_Create_Tpt_Subtype_Row_For_Each_PlayoutMode()
{
int scheduleId = await SeedSchedule();
var handler = new AddProgramScheduleItemHandler(_db.Factory, _worker);
foreach (PlayoutMode playoutMode in new[]
{
PlayoutMode.One,
PlayoutMode.Multiple,
PlayoutMode.Flood,
PlayoutMode.Duration
})
{
Either<BaseError, ProgramScheduleItemViewModel> result =
await handler.Handle(MakeAdd(scheduleId, playoutMode), CancellationToken.None);
result.IsRight.ShouldBeTrue();
}
await using TvContext context = _db.CreateContext();
(await CountRows(context, "ProgramScheduleOneItem")).ShouldBe(1);
(await CountRows(context, "ProgramScheduleMultipleItem")).ShouldBe(1);
(await CountRows(context, "ProgramScheduleFloodItem")).ShouldBe(1);
(await CountRows(context, "ProgramScheduleDurationItem")).ShouldBe(1);
}
[Test]
public async Task ReplaceProgramScheduleItems_Should_Create_Tpt_Subtype_Rows_For_Replaced_Items()
{
int scheduleId = await SeedSchedule();
var handler = new ReplaceProgramScheduleItemsHandler(_db.Factory, _worker);
Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>> result =
await handler.Handle(
new ReplaceProgramScheduleItems(
scheduleId,
[
MakeReplace(0, PlayoutMode.One),
MakeReplace(1, PlayoutMode.Multiple),
MakeReplace(2, PlayoutMode.Flood),
MakeReplace(3, PlayoutMode.Duration)
]),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext context = _db.CreateContext();
(await CountRows(context, "ProgramScheduleOneItem")).ShouldBe(1);
(await CountRows(context, "ProgramScheduleMultipleItem")).ShouldBe(1);
(await CountRows(context, "ProgramScheduleFloodItem")).ShouldBe(1);
(await CountRows(context, "ProgramScheduleDurationItem")).ShouldBe(1);
}
private async Task<int> SeedSchedule()
{
await using TvContext context = _db.CreateContext();
var schedule = new ProgramSchedule
{
Name = "Integration",
Items = [],
Playouts = [],
ProgramScheduleAlternates = []
};
context.ProgramSchedules.Add(schedule);
await context.SaveChangesAsync();
return schedule.Id;
}
private static AddProgramScheduleItem MakeAdd(int scheduleId, PlayoutMode playoutMode) =>
new(
scheduleId,
StartType.Dynamic,
StartTime: null,
FixedStartTimeBehavior: null,
playoutMode,
CollectionType.SearchQuery,
CollectionId: null,
MultiCollectionId: null,
SmartCollectionId: null,
RerunCollectionId: null,
MediaItemId: null,
PlaylistId: null,
SearchTitle: "News",
SearchQuery: "news",
PlaybackOrder: PlaybackOrder.Shuffle,
MarathonGroupBy: MarathonGroupBy.None,
MarathonShuffleGroups: false,
MarathonShuffleItems: false,
MarathonBatchSize: null,
FillWithGroupMode: FillWithGroupMode.None,
MultipleMode: MultipleMode.Count,
MultipleCount: "2",
PlayoutDuration: TimeSpan.FromMinutes(30),
TailMode: TailMode.None,
DiscardToFillAttempts: 3,
CustomTitle: null,
GuideMode: GuideMode.Normal,
PreRollFillerId: null,
MidRollFillerId: null,
PostRollFillerId: null,
TailFillerId: null,
FallbackFillerId: null,
WatermarkIds: [],
GraphicsElementIds: [],
PreferredAudioLanguageCode: null,
PreferredAudioTitle: null,
PreferredSubtitleLanguageCode: null,
SubtitleMode: null);
private static ReplaceProgramScheduleItem MakeReplace(int index, PlayoutMode playoutMode)
{
AddProgramScheduleItem add = MakeAdd(1, playoutMode);
return new ReplaceProgramScheduleItem(
index,
add.StartType,
add.StartTime,
add.FixedStartTimeBehavior,
add.PlayoutMode,
add.CollectionType,
add.CollectionId,
add.MultiCollectionId,
add.SmartCollectionId,
add.RerunCollectionId,
add.MediaItemId,
add.PlaylistId,
add.SearchTitle,
add.SearchQuery,
add.PlaybackOrder,
add.MarathonGroupBy,
add.MarathonShuffleGroups,
add.MarathonShuffleItems,
add.MarathonBatchSize,
add.FillWithGroupMode,
add.MultipleMode,
add.MultipleCount,
add.PlayoutDuration,
add.TailMode,
add.DiscardToFillAttempts,
add.CustomTitle,
add.GuideMode,
add.PreRollFillerId,
add.MidRollFillerId,
add.PostRollFillerId,
add.TailFillerId,
add.FallbackFillerId,
add.WatermarkIds,
add.GraphicsElementIds,
add.PreferredAudioLanguageCode,
add.PreferredAudioTitle,
add.PreferredSubtitleLanguageCode,
add.SubtitleMode);
}
private static Task<int> CountRows(TvContext context, string tableName) =>
context.Database.SqlQueryRaw<int>($"SELECT COUNT(*) AS Value FROM {tableName}").SingleAsync();
}
+45
View File
@@ -0,0 +1,45 @@
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests;
[TestFixture]
public class StartupSpaHostingTests
{
private static readonly string StartupSource = File.ReadAllText(FindStartupPath());
[Test]
public void Startup_Should_Mount_ChicoryTv_Spa_At_App_Path()
{
StartupSource.ShouldContain("ctx.Request.Path.StartsWithSegments(\"/app\")");
StartupSource.ShouldContain("MapWhen(");
StartupSource.ShouldContain("SpaStaticFileRoot");
StartupSource.ShouldContain("RequestPath = \"/app\"");
StartupSource.ShouldContain("appIndexFile");
}
[Test]
public void Startup_Should_Not_Send_App_Routes_To_Blazor_Fallback()
{
StartupSource.ShouldContain("!IsSpaPath(ctx.Request.Path)");
StartupSource.ShouldContain("bool IsSpaPath(PathString path)");
}
private static string FindStartupPath()
{
DirectoryInfo? directory = new(TestContext.CurrentContext.TestDirectory);
while (directory is not null)
{
string candidate = Path.Combine(directory.FullName, "ErsatzTV", "Startup.cs");
if (File.Exists(candidate))
{
return candidate;
}
directory = directory.Parent;
}
throw new FileNotFoundException("Could not find ErsatzTV/Startup.cs");
}
}
@@ -35,7 +35,12 @@ public abstract class ChannelHandlerTestBase
await context.SaveChangesAsync();
}
protected async Task SeedChannel(int id, string number, string name = "Test", int ffmpegProfileId = 1)
protected async Task SeedChannel(
int id,
string number,
string name = "Test",
int ffmpegProfileId = 1,
string group = "ErsatzTV")
{
await using TvContext context = Db.CreateContext();
context.Channels.Add(
@@ -44,7 +49,7 @@ public abstract class ChannelHandlerTestBase
Id = id,
Number = number,
Name = name,
Group = "ErsatzTV",
Group = group,
Categories = string.Empty,
FFmpegProfileId = ffmpegProfileId,
StreamSelector = string.Empty,
+54 -6
View File
@@ -8,7 +8,6 @@ using ErsatzTV.Core;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Extensions;
using ErsatzTV.Filters;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -16,17 +15,19 @@ using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
// Apply the optional API-key control at the controller level so that EVERY mutating action
// (including future ones) is covered by default; the filter no-ops on read methods (GET) and
// when Api:WriteKey is unset, preserving the open LAN behavior. This is fail-safe: a developer
// adding a new write endpoint here cannot accidentally leave it unauthenticated.
[ServiceFilter(typeof(ApiKeyAuthorizationFilter))]
public class ChannelController(ChannelWriter<IBackgroundServiceRequest> workerChannel, IMediator mediator)
{
[HttpGet("/api/channels")]
[EndpointGroupName("general")]
public async Task<List<ChannelResponseModel>> GetAll() => await mediator.Send(new GetAllChannelsForApi());
[HttpGet("/api/channels/state")]
[Tags("Channels")]
[EndpointSummary("Get channel runtime state")]
[EndpointGroupName("general")]
public async Task<List<ChannelStateResponseModel>> GetState(CancellationToken cancellationToken) =>
await mediator.Send(new GetChannelStatesForApi(DateTime.UtcNow), cancellationToken);
[HttpGet("/api/channels/{id:int}", Name = "GetChannelById")]
[Tags("Channels")]
[EndpointSummary("Get a channel by id")]
@@ -93,6 +94,53 @@ public class ChannelController(ChannelWriter<IBackgroundServiceRequest> workerCh
return result.ToDeletedResult();
}
[HttpPost("/api/channels/bulk/renumber")]
[Tags("Channels")]
[EndpointSummary("Renumber channels")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> BulkRenumber(
[Required] [FromBody] BulkRenumberChannelsRequest request,
CancellationToken cancellationToken)
{
Option<BaseError> result = await mediator.Send(request.ToCommand(), cancellationToken);
return result.Match<IActionResult>(
Some: error => error.ToErrorResult(),
None: () => new NoContentResult());
}
[HttpPost("/api/channels/bulk/group")]
[Tags("Channels")]
[EndpointSummary("Move channels to a group")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> BulkMoveToGroup(
[Required] [FromBody] BulkMoveChannelsToGroupRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(), cancellationToken);
return result.ToDeletedResult();
}
[HttpPost("/api/channels/bulk/delete")]
[Tags("Channels")]
[EndpointSummary("Delete channels")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> BulkDelete(
[Required] [FromBody] BulkDeleteChannelsRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(), cancellationToken);
return result.ToDeletedResult();
}
[HttpPost("/api/channels/{channelNumber}/playout/reset")]
[Tags("Channels")]
[EndpointSummary("Reset channel playout")]
@@ -3,7 +3,6 @@ using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Extensions;
using ErsatzTV.Filters;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -11,7 +10,6 @@ using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
[ServiceFilter(typeof(ApiKeyAuthorizationFilter))]
public class CollectionController(IMediator mediator) : ControllerBase
{
[HttpGet("/api/collections")]
@@ -1,44 +1,104 @@
using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.FFmpegProfiles;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.FFmpegProfiles;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
[EndpointGroupName("general")]
public class FFmpegProfileController(IMediator mediator) : ControllerBase
{
[HttpGet("/api/ffmpeg/profiles", Name="GetFFmpegProfiles")]
[HttpGet("/api/ffmpeg/profiles", Name = "GetFFmpegProfiles")]
[Tags("FFmpeg Profiles")]
[EndpointSummary("Get all FFmpeg profiles")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<FFmpegFullProfileResponseModel>), StatusCodes.Status200OK)]
public async Task<List<FFmpegFullProfileResponseModel>> GetAll(CancellationToken cancellationToken) =>
await mediator.Send(new GetAllFFmpegProfilesForApi(), cancellationToken);
[HttpPost("/api/ffmpeg/profiles/new", Name="CreateFFmpegProfile")]
[HttpGet("/api/ffmpeg/profiles/{id:int}", Name = "GetFFmpegProfileById")]
[Tags("FFmpeg Profiles")]
[EndpointSummary("Get an FFmpeg profile by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(FFmpegFullProfileResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<FFmpegFullProfileResponseModel> result =
await mediator.Send(new GetFFmpegFullProfileByIdForApi(id), cancellationToken);
return result.ToGetResult();
}
[HttpPost("/api/ffmpeg/profiles", Name = "CreateFFmpegProfile")]
[Tags("FFmpeg Profiles")]
[EndpointSummary("Create an FFmpeg profile")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(FFmpegFullProfileResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> AddOne(
[Required] [FromBody]
CreateFFmpegProfile request,
CreateFFmpegProfileRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, CreateFFmpegProfileResult> result = await mediator.Send(request, cancellationToken);
return result.Match<IActionResult>(Ok, error => Problem(error.ToString()));
Either<BaseError, CreateFFmpegProfileResult> result = await mediator.Send(request.ToCommand(), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async created =>
{
Option<FFmpegFullProfileResponseModel> profile =
await mediator.Send(new GetFFmpegFullProfileByIdForApi(created.FFmpegProfileId), cancellationToken);
return profile.Match(
Some: vm => (IActionResult)new CreatedResult($"/api/ffmpeg/profiles/{vm.Id}", vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpPut("/api/ffmpeg/profiles/update", Name="UpdateFFmpegProfile")]
[HttpPut("/api/ffmpeg/profiles/{id:int}", Name = "UpdateFFmpegProfile")]
[Tags("FFmpeg Profiles")]
[EndpointSummary("Update an FFmpeg profile")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(FFmpegFullProfileResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> UpdateOne(
int id,
[Required] [FromBody]
UpdateFFmpegProfile request,
UpdateFFmpegProfileRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, UpdateFFmpegProfileResult> result = await mediator.Send(request, cancellationToken);
return result.Match<IActionResult>(Ok, error => Problem(error.ToString()));
Either<BaseError, UpdateFFmpegProfileResult> result =
await mediator.Send(request.ToCommand(id), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async updated =>
{
Option<FFmpegFullProfileResponseModel> profile =
await mediator.Send(new GetFFmpegFullProfileByIdForApi(updated.FFmpegProfileId), cancellationToken);
return profile.Match(
Some: vm => (IActionResult)new OkObjectResult(vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpDelete("/api/ffmpeg/delete/{id:int}", Name="DeleteFFmpegProfile")]
[HttpDelete("/api/ffmpeg/profiles/{id:int}", Name = "DeleteFFmpegProfile")]
[Tags("FFmpeg Profiles")]
[EndpointSummary("Delete an FFmpeg profile")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> DeleteProfileAsync(int id, CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(new DeleteFFmpegProfile(id), cancellationToken);
return result.Match<IActionResult>(_ => Ok(), error => Conflict(error.ToString()));
return result.ToDeletedResult();
}
}
@@ -0,0 +1,75 @@
using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Playouts;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
public class PlayoutController(IMediator mediator) : ControllerBase
{
[HttpGet("/api/playouts/{id:int}", Name = "GetPlayoutById")]
[Tags("Playouts")]
[EndpointSummary("Get a playout by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PlayoutResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> result = await mediator.Send(new GetPlayoutById(id), cancellationToken);
return result.Map(ToResponse).ToGetResult();
}
[HttpPost("/api/playouts")]
[Tags("Playouts")]
[EndpointSummary("Create a classic playout")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PlayoutResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required] [FromBody] CreatePlayoutRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, CreatePlayoutResponse> result = await mediator.Send(request.ToCommand(), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async created =>
{
Option<PlayoutNameViewModel> playout =
await mediator.Send(new GetPlayoutById(created.PlayoutId), cancellationToken);
return playout.Match(
Some: vm => (IActionResult)new CreatedResult($"/api/playouts/{vm.PlayoutId}", ToResponse(vm)),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpDelete("/api/playouts/{id:int}")]
[Tags("Playouts")]
[EndpointSummary("Delete a playout")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(new DeletePlayout(id), cancellationToken);
return result.ToDeletedResult();
}
private static PlayoutResponseModel ToResponse(PlayoutNameViewModel vm) =>
PlayoutResponseModel.From(
vm.PlayoutId,
vm.ScheduleKind,
vm.ChannelName,
vm.ChannelNumber,
vm.PlayoutMode,
vm.ScheduleName,
vm.ScheduleFile,
vm.DbDailyRebuildTime);
}
@@ -0,0 +1,21 @@
using ErsatzTV.Application.Channels;
namespace ErsatzTV.Controllers.Api.Requests;
public record BulkRenumberChannelRequest(int Id, string Number);
public record BulkRenumberChannelsRequest(List<BulkRenumberChannelRequest> Channels)
{
public UpdateChannelNumbers ToCommand() =>
new(Channels.Select(c => new ChannelSortViewModel { Id = c.Id, Number = c.Number }).ToList());
}
public record BulkMoveChannelsToGroupRequest(List<int> ChannelIds, string Group)
{
public BulkMoveChannelsToGroup ToCommand() => new(ChannelIds, Group);
}
public record BulkDeleteChannelsRequest(List<int> ChannelIds)
{
public BulkDeleteChannels ToCommand() => new(ChannelIds);
}
@@ -0,0 +1,71 @@
using ErsatzTV.Application.FFmpegProfiles;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.FFmpeg;
namespace ErsatzTV.Controllers.Api.Requests;
public record CreateFFmpegProfileRequest(
string Name,
int ThreadCount,
bool NormalizeAudio,
bool NormalizeVideo,
HardwareAccelerationKind HardwareAcceleration,
string VaapiDisplay,
VaapiDriver VaapiDriver,
string VaapiDevice,
int? QsvExtraHardwareFrames,
int ResolutionId,
ScalingBehavior ScalingBehavior,
FilterMode PadMode,
FFmpegProfileVideoFormat VideoFormat,
string VideoProfile,
string VideoPreset,
bool AllowBFrames,
FFmpegProfileBitDepth BitDepth,
int VideoBitrate,
int VideoBufferSize,
FFmpegProfileTonemapAlgorithm TonemapAlgorithm,
FFmpegProfileAudioFormat AudioFormat,
int AudioBitrate,
int AudioBufferSize,
NormalizeLoudnessMode NormalizeLoudnessMode,
double? TargetLoudness,
int AudioChannels,
int AudioSampleRate,
bool NormalizeFramerate,
bool NormalizeColors,
bool DeinterlaceVideo)
{
public CreateFFmpegProfile ToCommand() =>
new(
Name,
ThreadCount,
NormalizeAudio,
NormalizeVideo,
HardwareAcceleration,
VaapiDisplay,
VaapiDriver,
VaapiDevice,
QsvExtraHardwareFrames,
ResolutionId,
ScalingBehavior,
PadMode,
VideoFormat,
VideoProfile,
VideoPreset,
AllowBFrames,
BitDepth,
VideoBitrate,
VideoBufferSize,
TonemapAlgorithm,
AudioFormat,
AudioBitrate,
AudioBufferSize,
NormalizeLoudnessMode,
TargetLoudness,
AudioChannels,
AudioSampleRate,
NormalizeFramerate,
NormalizeColors,
DeinterlaceVideo);
}
@@ -0,0 +1,8 @@
using ErsatzTV.Application.Playouts;
namespace ErsatzTV.Controllers.Api.Requests;
public record CreatePlayoutRequest(int ChannelId, int ProgramScheduleId)
{
public CreateClassicPlayout ToCommand() => new(ChannelId, ProgramScheduleId);
}
@@ -0,0 +1,22 @@
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Core.Scheduling;
namespace ErsatzTV.Controllers.Api.Requests;
public record CreateScheduleRequest(
string Name,
bool KeepMultiPartEpisodesTogether,
bool TreatCollectionsAsShows,
bool ShuffleScheduleItems,
bool RandomStartPoint,
FixedStartTimeBehavior FixedStartTimeBehavior)
{
public CreateProgramSchedule ToCreateCommand() =>
new(
Name,
KeepMultiPartEpisodesTogether,
TreatCollectionsAsShows,
ShuffleScheduleItems,
RandomStartPoint,
FixedStartTimeBehavior);
}
@@ -0,0 +1,11 @@
using ErsatzTV.Application.ProgramSchedules;
namespace ErsatzTV.Controllers.Api.Requests;
public record ReplaceScheduleItemsRequest(List<ScheduleItemRequest> Items)
{
public ReplaceProgramScheduleItems ToCommand(int scheduleId) =>
new(
scheduleId,
(Items ?? []).Select((item, index) => item.ToReplaceCommand(index)).ToList());
}
@@ -0,0 +1,127 @@
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Scheduling;
namespace ErsatzTV.Controllers.Api.Requests;
public record ScheduleItemRequest(
StartType StartType,
TimeSpan? StartTime,
FixedStartTimeBehavior? FixedStartTimeBehavior,
PlayoutMode PlayoutMode,
CollectionType CollectionType,
int? CollectionId,
int? MultiCollectionId,
int? SmartCollectionId,
int? RerunCollectionId,
int? MediaItemId,
int? PlaylistId,
string SearchTitle,
string SearchQuery,
PlaybackOrder PlaybackOrder,
MarathonGroupBy MarathonGroupBy,
bool MarathonShuffleGroups,
bool MarathonShuffleItems,
int? MarathonBatchSize,
FillWithGroupMode FillWithGroupMode,
MultipleMode MultipleMode,
string MultipleCount,
TimeSpan? PlayoutDuration,
TailMode TailMode,
int? DiscardToFillAttempts,
string CustomTitle,
GuideMode GuideMode,
int? PreRollFillerId,
int? MidRollFillerId,
int? PostRollFillerId,
int? TailFillerId,
int? FallbackFillerId,
List<int> WatermarkIds,
List<int> GraphicsElementIds,
string PreferredAudioLanguageCode,
string PreferredAudioTitle,
string PreferredSubtitleLanguageCode,
ChannelSubtitleMode? SubtitleMode)
{
public AddProgramScheduleItem ToAddCommand(int scheduleId) =>
new(
scheduleId,
StartType,
StartTime,
FixedStartTimeBehavior,
PlayoutMode,
CollectionType,
CollectionId,
MultiCollectionId,
SmartCollectionId,
RerunCollectionId,
MediaItemId,
PlaylistId,
SearchTitle,
SearchQuery,
PlaybackOrder,
MarathonGroupBy,
MarathonShuffleGroups,
MarathonShuffleItems,
MarathonBatchSize,
FillWithGroupMode,
MultipleMode,
MultipleCount,
PlayoutDuration,
TailMode,
DiscardToFillAttempts,
CustomTitle,
GuideMode,
PreRollFillerId,
MidRollFillerId,
PostRollFillerId,
TailFillerId,
FallbackFillerId,
WatermarkIds ?? [],
GraphicsElementIds ?? [],
PreferredAudioLanguageCode,
PreferredAudioTitle,
PreferredSubtitleLanguageCode,
SubtitleMode);
public ReplaceProgramScheduleItem ToReplaceCommand(int index) =>
new(
index,
StartType,
StartTime,
FixedStartTimeBehavior,
PlayoutMode,
CollectionType,
CollectionId,
MultiCollectionId,
SmartCollectionId,
RerunCollectionId,
MediaItemId,
PlaylistId,
SearchTitle,
SearchQuery,
PlaybackOrder,
MarathonGroupBy,
MarathonShuffleGroups,
MarathonShuffleItems,
MarathonBatchSize,
FillWithGroupMode,
MultipleMode,
MultipleCount,
PlayoutDuration,
TailMode,
DiscardToFillAttempts,
CustomTitle,
GuideMode,
PreRollFillerId,
MidRollFillerId,
PostRollFillerId,
TailFillerId,
FallbackFillerId,
WatermarkIds ?? [],
GraphicsElementIds ?? [],
PreferredAudioLanguageCode,
PreferredAudioTitle,
PreferredSubtitleLanguageCode,
SubtitleMode);
}
@@ -0,0 +1,72 @@
using ErsatzTV.Application.FFmpegProfiles;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.FFmpeg;
namespace ErsatzTV.Controllers.Api.Requests;
public record UpdateFFmpegProfileRequest(
string Name,
int ThreadCount,
bool NormalizeAudio,
bool NormalizeVideo,
HardwareAccelerationKind HardwareAcceleration,
string VaapiDisplay,
VaapiDriver VaapiDriver,
string VaapiDevice,
int? QsvExtraHardwareFrames,
int ResolutionId,
ScalingBehavior ScalingBehavior,
FilterMode PadMode,
FFmpegProfileVideoFormat VideoFormat,
string VideoProfile,
string VideoPreset,
bool AllowBFrames,
FFmpegProfileBitDepth BitDepth,
int VideoBitrate,
int VideoBufferSize,
FFmpegProfileTonemapAlgorithm TonemapAlgorithm,
FFmpegProfileAudioFormat AudioFormat,
int AudioBitrate,
int AudioBufferSize,
NormalizeLoudnessMode NormalizeLoudnessMode,
double? TargetLoudness,
int AudioChannels,
int AudioSampleRate,
bool NormalizeFramerate,
bool NormalizeColors,
bool DeinterlaceVideo)
{
public UpdateFFmpegProfile ToCommand(int id) =>
new(
id,
Name,
ThreadCount,
NormalizeAudio,
NormalizeVideo,
HardwareAcceleration,
VaapiDisplay,
VaapiDriver,
VaapiDevice,
QsvExtraHardwareFrames,
ResolutionId,
ScalingBehavior,
PadMode,
VideoFormat,
VideoProfile,
VideoPreset,
AllowBFrames,
BitDepth,
VideoBitrate,
VideoBufferSize,
TonemapAlgorithm,
AudioFormat,
AudioBitrate,
AudioBufferSize,
NormalizeLoudnessMode,
TargetLoudness,
AudioChannels,
AudioSampleRate,
NormalizeFramerate,
NormalizeColors,
DeinterlaceVideo);
}
@@ -0,0 +1,23 @@
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Core.Scheduling;
namespace ErsatzTV.Controllers.Api.Requests;
public record UpdateScheduleRequest(
string Name,
bool KeepMultiPartEpisodesTogether,
bool TreatCollectionsAsShows,
bool ShuffleScheduleItems,
bool RandomStartPoint,
FixedStartTimeBehavior FixedStartTimeBehavior)
{
public UpdateProgramSchedule ToCommand(int id) =>
new(
id,
Name,
KeepMultiPartEpisodesTogether,
TreatCollectionsAsShows,
ShuffleScheduleItems,
RandomStartPoint,
FixedStartTimeBehavior);
}
@@ -2,12 +2,14 @@ using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.Search;
using ErsatzTV.Core.Interfaces.Metadata;
using ErsatzTV.Filters;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
[SkipApiKeyAuthorization]
[Route("api/scan/{scanId:guid}")]
public class ScannerController(
IScannerProxyService scannerProxyService,
@@ -0,0 +1,165 @@
using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
public class ScheduleController(IMediator mediator) : ControllerBase
{
[HttpGet("/api/schedules")]
[Tags("Schedules")]
[EndpointSummary("Get all schedules")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<ProgramScheduleViewModel>), StatusCodes.Status200OK)]
public async Task<List<ProgramScheduleViewModel>> GetAll(CancellationToken cancellationToken) =>
await mediator.Send(new GetAllProgramSchedules(), cancellationToken);
[HttpGet("/api/schedules/{id:int}", Name = "GetScheduleById")]
[Tags("Schedules")]
[EndpointSummary("Get a schedule by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(ProgramScheduleViewModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<ProgramScheduleViewModel> result = await mediator.Send(new GetProgramScheduleById(id), cancellationToken);
return result.ToGetResult();
}
[HttpPost("/api/schedules")]
[Tags("Schedules")]
[EndpointSummary("Create a schedule")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(ProgramScheduleViewModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required] [FromBody] CreateScheduleRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, CreateProgramScheduleResult> result =
await mediator.Send(request.ToCreateCommand(), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async created =>
{
Option<ProgramScheduleViewModel> schedule =
await mediator.Send(new GetProgramScheduleById(created.ProgramScheduleId), cancellationToken);
return schedule.Match(
Some: vm => (IActionResult)new CreatedResult($"/api/schedules/{vm.Id}", vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpPut("/api/schedules/{id:int}")]
[Tags("Schedules")]
[EndpointSummary("Update a schedule")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(ProgramScheduleViewModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required] [FromBody] UpdateScheduleRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, UpdateProgramScheduleResult> result =
await mediator.Send(request.ToCommand(id), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
Option<ProgramScheduleViewModel> schedule =
await mediator.Send(new GetProgramScheduleById(id), cancellationToken);
return schedule.Match(
Some: vm => (IActionResult)new OkObjectResult(vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpDelete("/api/schedules/{id:int}")]
[Tags("Schedules")]
[EndpointSummary("Delete a schedule")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(new DeleteProgramSchedule(id), cancellationToken);
return result.ToDeletedResult();
}
[HttpGet("/api/schedules/{id:int}/items")]
[Tags("Schedules")]
[EndpointSummary("Get schedule items")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<ProgramScheduleItemViewModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetItems(int id, CancellationToken cancellationToken)
{
Option<ProgramScheduleViewModel> schedule = await mediator.Send(new GetProgramScheduleById(id), cancellationToken);
if (schedule.IsNone)
{
return ApiResults.NotFoundProblem();
}
List<ProgramScheduleItemViewModel> items =
await mediator.Send(new GetProgramScheduleItems(id), cancellationToken);
return new OkObjectResult(items);
}
[HttpPost("/api/schedules/{id:int}/items")]
[Tags("Schedules")]
[EndpointSummary("Add a schedule item")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(ProgramScheduleItemViewModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> AddItem(
int id,
[Required] [FromBody] ScheduleItemRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, ProgramScheduleItemViewModel> result =
await mediator.Send(request.ToAddCommand(id), cancellationToken);
return result.ToCreatedResult(item => $"/api/schedules/{id}/items/{item.Id}", item => item);
}
[HttpPut("/api/schedules/{id:int}/items")]
[Tags("Schedules")]
[EndpointSummary("Replace schedule items")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(IEnumerable<ProgramScheduleItemViewModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> ReplaceItems(
int id,
[Required] [FromBody] ReplaceScheduleItemsRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>> result =
await mediator.Send(request.ToCommand(id), cancellationToken);
return result.ToUpdatedResult();
}
[HttpDelete("/api/schedules/{id:int}/items/{itemId:int}")]
[Tags("Schedules")]
[EndpointSummary("Delete a schedule item")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> DeleteItem(int id, int itemId, CancellationToken cancellationToken)
{
Either<BaseError, Unit> result =
await mediator.Send(new DeleteProgramScheduleItem(id, itemId), cancellationToken);
return result.ToDeletedResult();
}
}
@@ -4,7 +4,6 @@ using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.SmartCollections;
using ErsatzTV.Extensions;
using ErsatzTV.Filters;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -12,7 +11,6 @@ using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
[ServiceFilter(typeof(ApiKeyAuthorizationFilter))]
public class SmartCollectionController(IMediator mediator) : ControllerBase
{
[HttpGet("/api/smart-collections")]
+35 -5
View File
@@ -6,12 +6,12 @@ using Microsoft.Extensions.Primitives;
namespace ErsatzTV.Filters;
/// <summary>
/// Optional API-key authorization for mutating JSON API endpoints (slice #2a).
/// Optional API-key authorization for mutating JSON API endpoints.
/// Reads the configured key from <c>Api:WriteKey</c>. When that key is empty the filter is
/// a no-op (preserving the current open LAN behavior); when it is set, mutating requests
/// (POST/PUT/PATCH/DELETE) must present a matching <c>X-Api-Key</c> header or receive 401.
/// This is fully independent of <see cref="JwtHelper" /> and only applies to the actions it
/// decorates — it never affects /iptv/* or any read endpoint.
/// under <c>/api/*</c> (POST/PUT/PATCH/DELETE) must present a matching <c>X-Api-Key</c>
/// header or receive 401. This is fully independent of <see cref="JwtHelper" /> and never
/// affects /iptv/* or any read endpoint.
/// </summary>
public class ApiKeyAuthorizationFilter(IConfiguration configuration) : IAuthorizationFilter
{
@@ -20,6 +20,11 @@ public class ApiKeyAuthorizationFilter(IConfiguration configuration) : IAuthoriz
public void OnAuthorization(AuthorizationFilterContext context)
{
if (ShouldSkipApiKeyAuthorization(context))
{
return;
}
string configuredKey = configuration[ConfigurationKey];
// empty key => API-key auth disabled, endpoint is open
@@ -42,7 +47,32 @@ public class ApiKeyAuthorizationFilter(IConfiguration configuration) : IAuthoriz
if (!context.HttpContext.Request.Headers.TryGetValue(HeaderName, out StringValues provided)
|| !string.Equals(provided.ToString(), configuredKey, StringComparison.Ordinal))
{
context.Result = new UnauthorizedResult();
context.Result = new UnauthorizedObjectResult(new ProblemDetails
{
Status = StatusCodes.Status401Unauthorized,
Title = "Unauthorized",
Detail = "A valid API key is required for write requests."
});
}
}
private static bool ShouldSkipApiKeyAuthorization(AuthorizationFilterContext context)
{
if (context.Filters.OfType<SkipApiKeyAuthorizationAttribute>().Any()
|| context.ActionDescriptor.EndpointMetadata.OfType<SkipApiKeyAuthorizationAttribute>().Any())
{
return true;
}
if (!context.HttpContext.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
{
return true;
}
string method = context.HttpContext.Request.Method;
return !HttpMethods.IsPost(method)
&& !HttpMethods.IsPut(method)
&& !HttpMethods.IsPatch(method)
&& !HttpMethods.IsDelete(method);
}
}
@@ -0,0 +1,9 @@
using Microsoft.AspNetCore.Mvc.Filters;
namespace ErsatzTV.Filters;
/// <summary>
/// Marks an internal API endpoint as exempt from global API-key write authorization.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class SkipApiKeyAuthorizationAttribute : Attribute, IFilterMetadata;
+88 -2
View File
@@ -4,6 +4,7 @@ using System.IO.Abstractions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Threading.Channels;
using BlazorSortable;
@@ -118,6 +119,35 @@ public class Startup
private IWebHostEnvironment CurrentEnvironment { get; }
private static void UseStringEnumSchemas(OpenApiDocument document)
{
if (document.Components?.Schemas is null)
{
return;
}
Dictionary<string, Type> enumTypes = typeof(Core.Domain.PlayoutMode).Assembly.GetTypes()
.Where(type => type.IsEnum)
.GroupBy(type => type.Name)
.ToDictionary(group => group.Key, group => group.First());
foreach ((string schemaName, IOpenApiSchema schema) in document.Components.Schemas)
{
if (schema is not OpenApiSchema openApiSchema ||
!enumTypes.TryGetValue(schemaName, out Type enumType))
{
continue;
}
openApiSchema.Type = JsonSchemaType.String;
openApiSchema.Format = null;
openApiSchema.Enum = Enum.GetNames(enumType)
.Select(name => JsonValue.Create(name))
.Cast<JsonNode>()
.ToList();
}
}
[SuppressMessage("Performance", "CA1861:Avoid constant arrays as arguments")]
public void ConfigureServices(IServiceCollection services)
{
@@ -133,7 +163,17 @@ public class Startup
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(FileSystemLayout.DataProtectionFolder));
services.AddOpenApi("v1", options => { options.ShouldInclude += a => a.GroupName == "general"; });
services.AddOpenApi(
"v1",
options =>
{
options.ShouldInclude += a => a.GroupName == "general";
options.AddDocumentTransformer((document, _, _) =>
{
UseStringEnumSchemas(document);
return Task.CompletedTask;
});
});
services.AddOpenApi(
"scripted-schedule-tagged",
@@ -298,6 +338,7 @@ public class Startup
options.OutputFormatters.Insert(0, new ChannelGuideOutputFormatter());
options.OutputFormatters.Insert(0, new DeviceXmlOutputFormatter());
options.OutputFormatters.Insert(0, new HdhrJsonOutputFormatter());
options.Filters.AddService<ApiKeyAuthorizationFilter>();
})
.AddNewtonsoftJson(opt =>
{
@@ -640,7 +681,42 @@ public class Startup
});
app.MapWhen(
ctx => !IsIptvPath(ctx.Request.Path),
ctx => ctx.Request.Path.StartsWithSegments("/app"),
spa =>
{
string spaStaticFileRoot = SpaStaticFileRoot();
IFileProvider spaFileProvider = Directory.Exists(spaStaticFileRoot)
? new PhysicalFileProvider(spaStaticFileRoot)
: new NullFileProvider();
spa.UseStaticFiles(
new StaticFileOptions
{
FileProvider = spaFileProvider,
RequestPath = "/app"
});
spa.Run(
async context =>
{
Microsoft.Extensions.FileProviders.IFileInfo appIndexFile =
spaFileProvider.GetFileInfo("index.html");
if (!appIndexFile.Exists)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.ContentLength = appIndexFile.Length;
await using Stream stream = appIndexFile.CreateReadStream();
await stream.CopyToAsync(context.Response.Body);
});
});
app.MapWhen(
ctx => !IsIptvPath(ctx.Request.Path) && !IsSpaPath(ctx.Request.Path),
blazor =>
{
blazor.UseRouting();
@@ -695,6 +771,16 @@ public class Startup
path.StartsWithSegments("/lineup.json") ||
path.StartsWithSegments("/lineup_status.json");
}
bool IsSpaPath(PathString path) => path.StartsWithSegments("/app");
string SpaStaticFileRoot()
{
string webRootPath = CurrentEnvironment.WebRootPath ??
Path.Combine(CurrentEnvironment.ContentRootPath, "wwwroot");
return Path.Combine(webRootPath, "app");
}
}
private static void CustomServices(IServiceCollection services)
File diff suppressed because it is too large Load Diff
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./support.js"></script>
</head>
<body>
<x-dc>
</x-dc>
</body>
</html>
+17
View File
@@ -0,0 +1,17 @@
---
name: chicorytv-design
description: Use this skill to generate well-branded interfaces and assets for ChicoryTV, either for production or throwaway prototypes/mocks/etc. Contains essential design guidelines, colors, type, fonts, assets, and UI kit components for prototyping.
user-invocable: true
---
Read the README.md file within this skill, and explore the other available files.
If creating visual artifacts (slides, mocks, throwaway prototypes, etc), copy assets out and create static HTML files for the user to view. If working on production code, you can copy assets and read the rules here to become an expert in designing with this brand.
If the user invokes this skill without any other guidance, ask them what they want to build or design, ask some questions, and act as an expert designer who outputs HTML artifacts _or_ production code, depending on the need.
Quick map:
- `readme.md` — brand context, content & visual foundations, iconography, file index.
- `styles.css` — the single entry point; link it and use the CSS custom properties.
- `tokens/` — color, type, spacing, radius/elevation/motion tokens + font loading.
- `components/` — React primitives (forms, data-display, feedback, navigation).
- `templates/chicorytv-admin/` — full admin shell to start from / copy screens out of (incl. the library-to-lineup Channel Builder).
- `assets/` — chicory-flower mark, wordmark, app icon.
+470
View File
@@ -0,0 +1,470 @@
{
"plugins": [
"react",
"import"
],
"rules": {
"react/forbid-elements": [
"warn",
{
"forbid": []
}
],
"no-restricted-imports": [
"warn",
{
"patterns": [
{
"group": [
"components/data-display/**",
"components/feedback/**",
"components/forms/**",
"components/navigation/**",
"design_handoff_channel_builder/**"
],
"message": "Import design-system components from 'index.js', not component internals."
}
]
}
],
"no-restricted-syntax": [
"warn",
{
"selector": "Literal[value=/#[0-9a-fA-F]{3,8}\\b/]",
"message": "Raw hex color — use a design-system color token via var()."
},
{
"selector": "Literal[value=/\\b\\d+px\\b/]",
"message": "Raw px value — use a design-system spacing token via var()."
},
{
"selector": "Literal[value=/font-family\\s*:\\s*(?!['\\\"]?(?:Geist|Geist Mono))/i]",
"message": "Font not provided by the design system. Available: Geist, Geist Mono."
},
{
"selector": "JSXOpeningElement[name.name='Badge'] > JSXAttribute > JSXIdentifier[name!=/^(?:children|tone|solid|dot|style|key|ref|className|style|children)$/]",
"message": "<Badge> doesn't accept that prop. Declared props: children, tone, solid, dot, style."
},
{
"selector": "JSXOpeningElement[name.name='Badge'] > JSXAttribute[name.name='tone'] > Literal[value!=/^(?:neutral|accent|ok|warn|error)$/]",
"message": "<Badge> tone must be one of 'neutral' | 'accent' | 'ok' | 'warn' | 'error'."
},
{
"selector": "JSXOpeningElement[name.name='Button'] > JSXAttribute > JSXIdentifier[name!=/^(?:children|variant|size|startIcon|endIcon|disabled|loading|fullWidth|type|onClick|style|key|ref|className|style|children)$/]",
"message": "<Button> doesn't accept that prop. Declared props: children, variant, size, startIcon, endIcon, disabled, loading, fullWidth, type, onClick, style."
},
{
"selector": "JSXOpeningElement[name.name='Button'] > JSXAttribute[name.name='variant'] > Literal[value!=/^(?:primary|secondary|ghost|danger)$/]",
"message": "<Button> variant must be one of 'primary' | 'secondary' | 'ghost' | 'danger'."
},
{
"selector": "JSXOpeningElement[name.name='Button'] > JSXAttribute[name.name='size'] > Literal[value!=/^(?:sm|md)$/]",
"message": "<Button> size must be one of 'sm' | 'md'."
},
{
"selector": "JSXOpeningElement[name.name='Button'] > JSXAttribute[name.name='type'] > Literal[value!=/^(?:button|submit|reset)$/]",
"message": "<Button> type must be one of 'button' | 'submit' | 'reset'."
},
{
"selector": "JSXOpeningElement[name.name='Card'] > JSXAttribute > JSXIdentifier[name!=/^(?:title|subtitle|actions|children|padded|inset|style|key|ref|className|style|children)$/]",
"message": "<Card> doesn't accept that prop. Declared props: title, subtitle, actions, children, padded, inset, style."
},
{
"selector": "JSXOpeningElement[name.name='ChannelLogo'] > JSXAttribute > JSXIdentifier[name!=/^(?:name|src|size|radius|style|key|ref|className|style|children)$/]",
"message": "<ChannelLogo> doesn't accept that prop. Declared props: name, src, size, radius, style."
},
{
"selector": "JSXOpeningElement[name.name='Checkbox'] > JSXAttribute > JSXIdentifier[name!=/^(?:checked|onChange|label|indeterminate|disabled|style|key|ref|className|style|children)$/]",
"message": "<Checkbox> doesn't accept that prop. Declared props: checked, onChange, label, indeterminate, disabled, style."
},
{
"selector": "JSXOpeningElement[name.name='IconButton'] > JSXAttribute > JSXIdentifier[name!=/^(?:children|size|variant|active|disabled|title|onClick|style|key|ref|className|style|children)$/]",
"message": "<IconButton> doesn't accept that prop. Declared props: children, size, variant, active, disabled, title, onClick, style."
},
{
"selector": "JSXOpeningElement[name.name='IconButton'] > JSXAttribute[name.name='size'] > Literal[value!=/^(?:sm|md)$/]",
"message": "<IconButton> size must be one of 'sm' | 'md'."
},
{
"selector": "JSXOpeningElement[name.name='IconButton'] > JSXAttribute[name.name='variant'] > Literal[value!=/^(?:ghost|solid)$/]",
"message": "<IconButton> variant must be one of 'ghost' | 'solid'."
},
{
"selector": "JSXOpeningElement[name.name='Input'] > JSXAttribute > JSXIdentifier[name!=/^(?:label|value|onChange|placeholder|leadingIcon|trailing|error|disabled|size|type|fullWidth|style|key|ref|className|style|children)$/]",
"message": "<Input> doesn't accept that prop. Declared props: label, value, onChange, placeholder, leadingIcon, trailing, error, disabled, size, type, fullWidth, style."
},
{
"selector": "JSXOpeningElement[name.name='Input'] > JSXAttribute[name.name='size'] > Literal[value!=/^(?:sm|md)$/]",
"message": "<Input> size must be one of 'sm' | 'md'."
},
{
"selector": "JSXOpeningElement[name.name='NavItem'] > JSXAttribute > JSXIdentifier[name!=/^(?:icon|label|active|badge|badgeTone|href|onClick|style|key|ref|className|style|children)$/]",
"message": "<NavItem> doesn't accept that prop. Declared props: icon, label, active, badge, badgeTone, href, onClick, style."
},
{
"selector": "JSXOpeningElement[name.name='NavItem'] > JSXAttribute[name.name='badgeTone'] > Literal[value!=/^(?:warn|error|accent)$/]",
"message": "<NavItem> badgeTone must be one of 'warn' | 'error' | 'accent'."
},
{
"selector": "JSXOpeningElement[name.name='ProgressBar'] > JSXAttribute > JSXIdentifier[name!=/^(?:value|tone|height|showLabel|style|key|ref|className|style|children)$/]",
"message": "<ProgressBar> doesn't accept that prop. Declared props: value, tone, height, showLabel, style."
},
{
"selector": "JSXOpeningElement[name.name='ProgressBar'] > JSXAttribute[name.name='tone'] > Literal[value!=/^(?:accent|ok|warn|error)$/]",
"message": "<ProgressBar> tone must be one of 'accent' | 'ok' | 'warn' | 'error'."
},
{
"selector": "JSXOpeningElement[name.name='SelectOption'] > JSXAttribute > JSXIdentifier[name!=/^(?:value|label|key|ref|className|style|children)$/]",
"message": "<SelectOption> doesn't accept that prop. Declared props: value, label."
},
{
"selector": "JSXOpeningElement[name.name='Spinner'] > JSXAttribute > JSXIdentifier[name!=/^(?:size|tone|stroke|style|key|ref|className|style|children)$/]",
"message": "<Spinner> doesn't accept that prop. Declared props: size, tone, stroke, style."
},
{
"selector": "JSXOpeningElement[name.name='Spinner'] > JSXAttribute[name.name='tone'] > Literal[value!=/^(?:accent|muted|ok)$/]",
"message": "<Spinner> tone must be one of 'accent' | 'muted' | 'ok'."
},
{
"selector": "JSXOpeningElement[name.name='Stat'] > JSXAttribute > JSXIdentifier[name!=/^(?:label|value|unit|delta|deltaTone|icon|style|key|ref|className|style|children)$/]",
"message": "<Stat> doesn't accept that prop. Declared props: label, value, unit, delta, deltaTone, icon, style."
},
{
"selector": "JSXOpeningElement[name.name='Stat'] > JSXAttribute[name.name='deltaTone'] > Literal[value!=/^(?:up|down|neutral)$/]",
"message": "<Stat> deltaTone must be one of 'up' | 'down' | 'neutral'."
},
{
"selector": "JSXOpeningElement[name.name='StatusDot'] > JSXAttribute > JSXIdentifier[name!=/^(?:status|pulse|size|label|style|key|ref|className|style|children)$/]",
"message": "<StatusDot> doesn't accept that prop. Declared props: status, pulse, size, label, style."
},
{
"selector": "JSXOpeningElement[name.name='StatusDot'] > JSXAttribute[name.name='status'] > Literal[value!=/^(?:live|ok|warn|error|idle)$/]",
"message": "<StatusDot> status must be one of 'live' | 'ok' | 'warn' | 'error' | 'idle'."
},
{
"selector": "JSXOpeningElement[name.name='Switch'] > JSXAttribute > JSXIdentifier[name!=/^(?:checked|onChange|label|disabled|size|style|key|ref|className|style|children)$/]",
"message": "<Switch> doesn't accept that prop. Declared props: checked, onChange, label, disabled, size, style."
},
{
"selector": "JSXOpeningElement[name.name='Switch'] > JSXAttribute[name.name='size'] > Literal[value!=/^(?:sm|md)$/]",
"message": "<Switch> size must be one of 'sm' | 'md'."
},
{
"selector": "JSXOpeningElement[name.name='TabItem'] > JSXAttribute > JSXIdentifier[name!=/^(?:value|label|icon|count|key|ref|className|style|children)$/]",
"message": "<TabItem> doesn't accept that prop. Declared props: value, label, icon, count."
},
{
"selector": "JSXOpeningElement[name.name='Tag'] > JSXAttribute > JSXIdentifier[name!=/^(?:children|onRemove|icon|tone|style|key|ref|className|style|children)$/]",
"message": "<Tag> doesn't accept that prop. Declared props: children, onRemove, icon, tone, style."
},
{
"selector": "JSXOpeningElement[name.name='Tag'] > JSXAttribute[name.name='tone'] > Literal[value!=/^(?:neutral|accent)$/]",
"message": "<Tag> tone must be one of 'neutral' | 'accent'."
},
{
"selector": "JSXOpeningElement[name.name='Toast'] > JSXAttribute > JSXIdentifier[name!=/^(?:tone|title|message|onClose|style|key|ref|className|style|children)$/]",
"message": "<Toast> doesn't accept that prop. Declared props: tone, title, message, onClose, style."
},
{
"selector": "JSXOpeningElement[name.name='Toast'] > JSXAttribute[name.name='tone'] > Literal[value!=/^(?:info|ok|warn|error)$/]",
"message": "<Toast> tone must be one of 'info' | 'ok' | 'warn' | 'error'."
},
{
"selector": "JSXOpeningElement[name.name='Tooltip'] > JSXAttribute > JSXIdentifier[name!=/^(?:label|placement|children|style|key|ref|className|style|children)$/]",
"message": "<Tooltip> doesn't accept that prop. Declared props: label, placement, children, style."
},
{
"selector": "JSXOpeningElement[name.name='Tooltip'] > JSXAttribute[name.name='placement'] > Literal[value!=/^(?:top|bottom|left|right)$/]",
"message": "<Tooltip> placement must be one of 'top' | 'bottom' | 'left' | 'right'."
}
]
},
"overrides": [
{
"files": [
"**/index.js"
],
"rules": {
"no-restricted-imports": "off"
}
}
],
"x-omelette": {
"components": {
"Badge": {
"replaces": []
},
"Button": {
"replaces": []
},
"Card": {
"replaces": []
},
"ChannelLogo": {
"replaces": []
},
"Checkbox": {
"replaces": []
},
"IconButton": {
"replaces": []
},
"Input": {
"replaces": []
},
"NavItem": {
"replaces": []
},
"ProgressBar": {
"replaces": []
},
"SelectOption": {
"replaces": []
},
"Spinner": {
"replaces": []
},
"Stat": {
"replaces": []
},
"StatusDot": {
"replaces": []
},
"Switch": {
"replaces": []
},
"TabItem": {
"replaces": []
},
"Tag": {
"replaces": []
},
"Toast": {
"replaces": []
},
"Tooltip": {
"replaces": []
}
},
"tokens": [
"--action-primary",
"--action-primary-hover",
"--action-primary-press",
"--border-control",
"--border-hairline",
"--control-h",
"--control-h-sm",
"--ctv-accent",
"--ctv-accent-hover",
"--ctv-accent-press",
"--ctv-accent-ring",
"--ctv-accent-soft",
"--ctv-bg",
"--ctv-bg-sunken",
"--ctv-border",
"--ctv-border-strong",
"--ctv-error",
"--ctv-error-soft",
"--ctv-live",
"--ctv-live-soft",
"--ctv-ok",
"--ctv-ok-soft",
"--ctv-secondary",
"--ctv-secondary-soft",
"--ctv-surface",
"--ctv-surface-2",
"--ctv-surface-3",
"--ctv-text",
"--ctv-text-faint",
"--ctv-text-muted",
"--ctv-warn",
"--ctv-warn-soft",
"--dur-base",
"--dur-fast",
"--dur-slow",
"--ease-out",
"--ease-standard",
"--focus-ring",
"--font-mono",
"--font-sans",
"--gap-inline",
"--leading-normal",
"--leading-snug",
"--leading-tight",
"--numeric-feature",
"--pad-card",
"--pad-cell-x",
"--pad-cell-y",
"--pad-control-x",
"--pad-control-y",
"--pad-page",
"--radius-lg",
"--radius-md",
"--radius-pill",
"--radius-sm",
"--radius-xs",
"--ring-focus",
"--row-h",
"--shadow-lg",
"--shadow-md",
"--shadow-none",
"--shadow-pop",
"--shadow-sm",
"--sidebar-w",
"--space-0",
"--space-1",
"--space-10",
"--space-11",
"--space-12",
"--space-2",
"--space-3",
"--space-4",
"--space-5",
"--space-6",
"--space-7",
"--space-8",
"--space-9",
"--status-error",
"--status-live",
"--status-ok",
"--status-warn",
"--surface-app",
"--surface-card",
"--surface-raised",
"--surface-selected",
"--text-2xl",
"--text-2xs",
"--text-3xl",
"--text-disabled",
"--text-lg",
"--text-md",
"--text-on-accent",
"--text-primary",
"--text-secondary",
"--text-sm",
"--text-xl",
"--text-xs",
"--topbar-h",
"--tracking-caps",
"--tracking-normal",
"--tracking-tight",
"--tracking-wide",
"--weight-bold",
"--weight-medium",
"--weight-normal",
"--weight-semibold"
],
"tokenKinds": {
"--ctv-bg": "color",
"--ctv-bg-sunken": "color",
"--ctv-surface": "color",
"--ctv-surface-2": "color",
"--ctv-surface-3": "color",
"--ctv-border": "color",
"--ctv-border-strong": "color",
"--ctv-text": "font",
"--ctv-text-muted": "font",
"--ctv-text-faint": "font",
"--ctv-accent": "color",
"--ctv-accent-hover": "color",
"--ctv-accent-press": "color",
"--ctv-accent-soft": "color",
"--ctv-accent-ring": "color",
"--ctv-secondary": "color",
"--ctv-secondary-soft": "color",
"--ctv-ok": "color",
"--ctv-ok-soft": "color",
"--ctv-warn": "color",
"--ctv-warn-soft": "color",
"--ctv-error": "color",
"--ctv-error-soft": "color",
"--ctv-live": "color",
"--ctv-live-soft": "color",
"--surface-app": "color",
"--surface-card": "color",
"--surface-raised": "color",
"--surface-selected": "color",
"--border-hairline": "color",
"--border-control": "color",
"--text-primary": "font",
"--text-secondary": "font",
"--text-disabled": "font",
"--text-on-accent": "font",
"--action-primary": "color",
"--action-primary-hover": "color",
"--action-primary-press": "color",
"--focus-ring": "color",
"--status-ok": "color",
"--status-warn": "color",
"--status-error": "color",
"--status-live": "color",
"--font-sans": "font",
"--font-mono": "font",
"--text-2xs": "font",
"--text-xs": "font",
"--text-sm": "font",
"--text-md": "font",
"--text-lg": "font",
"--text-xl": "font",
"--text-2xl": "font",
"--text-3xl": "font",
"--weight-normal": "font",
"--weight-medium": "font",
"--weight-semibold": "font",
"--weight-bold": "font",
"--leading-tight": "font",
"--leading-snug": "font",
"--leading-normal": "font",
"--tracking-tight": "font",
"--tracking-normal": "font",
"--tracking-wide": "font",
"--tracking-caps": "font",
"--numeric-feature": "other",
"--space-0": "spacing",
"--space-1": "spacing",
"--space-2": "spacing",
"--space-3": "spacing",
"--space-4": "spacing",
"--space-5": "spacing",
"--space-6": "spacing",
"--space-7": "spacing",
"--space-8": "spacing",
"--space-9": "spacing",
"--space-10": "spacing",
"--space-11": "spacing",
"--space-12": "spacing",
"--gap-inline": "spacing",
"--pad-control-x": "spacing",
"--pad-control-y": "spacing",
"--pad-card": "spacing",
"--pad-cell-x": "spacing",
"--pad-cell-y": "spacing",
"--pad-page": "spacing",
"--sidebar-w": "spacing",
"--topbar-h": "spacing",
"--row-h": "spacing",
"--control-h": "spacing",
"--control-h-sm": "spacing",
"--radius-xs": "radius",
"--radius-sm": "radius",
"--radius-md": "radius",
"--radius-lg": "radius",
"--radius-pill": "radius",
"--shadow-none": "shadow",
"--shadow-sm": "shadow",
"--shadow-md": "shadow",
"--shadow-lg": "shadow",
"--shadow-pop": "shadow",
"--ring-focus": "color",
"--ease-standard": "other",
"--ease-out": "other",
"--dur-fast": "other",
"--dur-base": "other",
"--dur-slow": "other"
},
"fontFamilies": [
"Geist",
"Geist Mono"
]
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" fill="none">
<g transform="translate(32 32)">
<rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(0)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(22.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(45)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(67.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(90)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(112.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(135)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(157.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(180)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(202.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(225)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(247.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(270)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(292.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(315)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(337.5)"></rect>
<circle r="8.5" fill="#0F1115"></circle>
<circle r="5" fill="#5B7CFA"></circle>
<circle r="2" fill="#0F1115"></circle>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" fill="none">
<rect width="64" height="64" rx="14" fill="#171A21"></rect>
<g transform="translate(32 32) scale(0.82)">
<rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(0)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(22.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(45)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(67.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(90)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(112.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(135)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(157.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(180)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(202.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(225)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(247.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(270)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(292.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(315)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(337.5)"></rect>
<circle r="8.5" fill="#171A21"></circle>
<circle r="5" fill="#5B7CFA"></circle>
<circle r="2" fill="#171A21"></circle>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 48" width="250" height="48" fill="none">
<g transform="translate(24 24) scale(0.62)">
<rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(0)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(22.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(45)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(67.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(90)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(112.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(135)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(157.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(180)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(202.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(225)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(247.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(270)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(292.5)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#5B7CFA" transform="rotate(315)"></rect><rect x="-3.1" y="-30" width="6.2" height="20" rx="3.1" fill="#8AA1FC" transform="rotate(337.5)"></rect>
<circle r="8.5" fill="#0F1115"></circle>
<circle r="5" fill="#5B7CFA"></circle>
<circle r="2" fill="#0F1115"></circle>
</g>
<text x="52" y="32" font-family="Geist, system-ui, sans-serif" font-size="24" font-weight="600" letter-spacing="-0.5" fill="#E6E9EF">Chicory<tspan fill="#5B7CFA">TV</tspan></text>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

+17
View File
@@ -0,0 +1,17 @@
import * as React from "react";
export interface BadgeProps {
children?: React.ReactNode;
/** Semantic color. `accent` doubles as the live/on-air tone. */
tone?: "neutral" | "accent" | "ok" | "warn" | "error";
/** Filled instead of tinted-soft. */
solid?: boolean;
/** Leading status dot. */
dot?: boolean;
style?: React.CSSProperties;
}
/**
* Compact status/label badge — streaming mode, HLS/MPEG-TS, health status.
*/
export function Badge(props: BadgeProps): JSX.Element;
@@ -0,0 +1,39 @@
import React from "react";
const tones = {
neutral: { fg: "var(--text-secondary)", bg: "var(--ctv-surface-3)", bd: "var(--border-hairline)" },
accent: { fg: "var(--ctv-accent)", bg: "var(--ctv-accent-soft)", bd: "rgba(91,124,250,0.35)" },
ok: { fg: "var(--status-ok)", bg: "var(--ctv-ok-soft)", bd: "rgba(63,185,132,0.35)" },
warn: { fg: "var(--status-warn)", bg: "var(--ctv-warn-soft)", bd: "rgba(224,168,61,0.35)" },
error: { fg: "var(--status-error)", bg: "var(--ctv-error-soft)", bd: "rgba(229,72,77,0.35)" },
};
/**
* Small status/label badge. Soft (tinted) or solid.
*/
export function Badge({ children, tone = "neutral", solid = false, dot = false, style = {} }) {
const t = tones[tone] || tones.neutral;
const solidBg = { neutral: "var(--ctv-surface-3)", accent: "var(--ctv-accent)", ok: "var(--status-ok)", warn: "var(--status-warn)", error: "var(--status-error)" };
return (
<span
style={{
display: "inline-flex",
alignItems: "center",
gap: "5px",
height: "20px",
padding: dot ? "0 8px 0 6px" : "0 8px",
borderRadius: "var(--radius-xs)",
font: `var(--weight-medium) var(--text-2xs)/1 var(--font-sans)`,
letterSpacing: "0.02em",
color: solid ? (tone === "warn" ? "#1A1206" : "#fff") : t.fg,
background: solid ? solidBg[tone] : t.bg,
border: solid ? "1px solid transparent" : `1px solid ${t.bd}`,
whiteSpace: "nowrap",
...style,
}}
>
{dot && <span style={{ width: 6, height: 6, borderRadius: "50%", background: solid ? "rgba(255,255,255,0.9)" : t.fg }} />}
{children}
</span>
);
}
@@ -0,0 +1,11 @@
**Badge** — small status/label pill. Soft (tinted) by default; `solid` for stronger emphasis. Tones map to the status system; `accent` is also the live/on-air tone.
```jsx
<Badge tone="accent" dot>Live</Badge>
<Badge tone="ok">Healthy</Badge>
<Badge tone="warn">Not normalizing</Badge>
<Badge tone="neutral">HLS Segmenter</Badge>
<Badge tone="error" solid>Error</Badge>
```
Props: `tone` (neutral·accent·ok·warn·error), `solid`, `dot`.
+23
View File
@@ -0,0 +1,23 @@
import * as React from "react";
/**
* @startingPoint section="Layout" subtitle="Card surface with header + actions" viewport="700x260"
*/
export interface CardProps {
title?: React.ReactNode;
subtitle?: React.ReactNode;
/** Right-aligned header actions (buttons, menu). */
actions?: React.ReactNode;
children?: React.ReactNode;
/** Body padding — turn off for flush tables/lists. */
padded?: boolean;
/** Sunken well background instead of card surface. */
inset?: boolean;
style?: React.CSSProperties;
}
/**
* Panel surface with optional header row; the base container for dashboard
* widgets, forms and detail panes.
*/
export function Card(props: CardProps): JSX.Element;
@@ -0,0 +1,38 @@
import React from "react";
/**
* Surface container. Optional header (title + actions) and body padding.
*/
export function Card({ title, subtitle, actions = null, children, padded = true, inset = false, style = {} }) {
return (
<div
style={{
background: inset ? "var(--ctv-bg-sunken)" : "var(--surface-card)",
border: "1px solid var(--border-hairline)",
borderRadius: "var(--radius-md)",
overflow: "hidden",
...style,
}}
>
{(title || actions) && (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "12px",
padding: "13px 16px",
borderBottom: "1px solid var(--border-hairline)",
}}
>
<div style={{ minWidth: 0 }}>
{title && <div style={{ font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>{title}</div>}
{subtitle && <div style={{ marginTop: 3, font: "var(--text-xs)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{subtitle}</div>}
</div>
{actions && <div style={{ display: "flex", alignItems: "center", gap: "8px", flex: "0 0 auto" }}>{actions}</div>}
</div>
)}
<div style={{ padding: padded ? "16px" : 0 }}>{children}</div>
</div>
);
}
@@ -0,0 +1,10 @@
**Card** — the panel surface behind dashboard widgets, forms and detail panes. Header row is optional; set `padded={false}` when the body is a flush table or list.
```jsx
<Card title="Recent activity" actions={<Button size="sm" variant="ghost">View all</Button>}>
</Card>
<Card padded={false}><ChannelTable/></Card>
```
Props: `title`, `subtitle`, `actions`, `padded`, `inset`.
+17
View File
@@ -0,0 +1,17 @@
import * as React from "react";
export interface ChannelLogoProps {
/** Channel name — seeds the generated initials + color when no image. */
name?: string;
/** Logo image URL; falls back to a generated chip when absent. */
src?: string | null;
size?: number;
radius?: string;
style?: React.CSSProperties;
}
/**
* Square channel logo; shows the uploaded image or a deterministic
* initials chip keyed to the channel name (like ErsatzTV's generated logos).
*/
export function ChannelLogo(props: ChannelLogoProps): JSX.Element;
@@ -0,0 +1,51 @@
import React from "react";
const palette = [
["#5B7CFA", "#2E3A66"], ["#3FB984", "#1E4536"], ["#E0A83D", "#4A3818"],
["#E5484D", "#4A1F21"], ["#B06CF0", "#38235A"], ["#48B0C8", "#193E47"],
];
function hashIndex(str) {
let h = 0;
for (let i = 0; i < str.length; i++) h = (h * 31 + str.charCodeAt(i)) >>> 0;
return h % palette.length;
}
/**
* Channel logo tile. Renders an image when given, else a generated
* initials chip keyed to the channel name — mirrors ErsatzTV's logo/gen.
*/
export function ChannelLogo({ name = "", src = null, size = 40, radius = "var(--radius-sm)", style = {} }) {
const [fg, bg] = palette[hashIndex(name)];
const initials = name
.split(/[\s\-|:]+/)
.filter(Boolean)
.slice(0, 2)
.map((w) => w[0])
.join("")
.toUpperCase() || "?";
return (
<span
style={{
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
width: size,
height: size,
flex: "0 0 auto",
overflow: "hidden",
borderRadius: radius,
background: src ? "var(--ctv-bg-sunken)" : bg,
border: "1px solid var(--border-hairline)",
...style,
}}
>
{src ? (
<img src={src} alt={name} style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }} />
) : (
<span style={{ font: `var(--weight-semibold) ${Math.round(size * 0.34)}px/1 var(--font-mono)`, color: fg, letterSpacing: "0.02em" }}>{initials}</span>
)}
</span>
);
}

Some files were not shown because too many files have changed in this diff Show More