feat(api): filler preset + watermark editor CRUD; ffmpeg profile round-trip (#159)

Backend plumbing for the SPA transcoding editors (#143 blocker):

- FFmpeg profile response DTO round-trip: add NormalizeAudio, NormalizeVideo,
  PadMode, TargetLoudness, NormalizeColors, ResolutionId (keep Resolution name
  for compat); DeinterlaceVideo now bool (was bool?). #nullable enable on the DTO.
- New GET /api/ffmpeg/hardware-acceleration-kinds wrapping
  GetSupportedHardwareAccelerationKinds (returns enum names as strings).
- Filler preset CRUD: GET-by-id/POST/PUT/DELETE on FillerPresetController with
  full request/response DTOs; new FillerPresetFullResponseModel +
  GetFillerPresetByIdForApi. CreateFillerPreset now returns the new id
  (CreateFillerPresetResult) to match sibling Create commands and enable a
  201+Location; updated the one Blazor call site.
- Watermark CRUD: GET-by-id/POST/PUT/DELETE on WatermarkController with full
  DTOs (path+contentType, all 15 fields); new WatermarkFullResponseModel +
  GetWatermarkByIdForApi.
- Startup: register WatermarkLocation/WatermarkSize as OpenAPI string enums
  (they live in ErsatzTV.FFmpeg.State and were documented as ints, mismatching
  the Newtonsoft StringEnumConverter runtime serialization).
- Tests: full CRUD controller tests for filler + watermark; contract-test
  entries (404/401/422) for the new mutating endpoints; regenerated v1.json.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-07 14:06:26 +02:00
co-authored by Claude Fable 5
parent 6e091c98ae
commit 46c8c2e2dc
27 changed files with 2392 additions and 75 deletions
@@ -52,13 +52,17 @@ internal static class Mapper
ffmpegProfile.Id,
ffmpegProfile.Name,
ffmpegProfile.ThreadCount,
ffmpegProfile.NormalizeAudio,
ffmpegProfile.NormalizeVideo,
ffmpegProfile.HardwareAcceleration,
ffmpegProfile.VaapiDisplay,
ffmpegProfile.VaapiDriver,
ffmpegProfile.VaapiDevice,
ffmpegProfile.QsvExtraHardwareFrames,
ffmpegProfile.ResolutionId,
ffmpegProfile.Resolution.Name,
ffmpegProfile.ScalingBehavior,
ffmpegProfile.PadMode,
ffmpegProfile.VideoFormat,
ffmpegProfile.VideoProfile,
ffmpegProfile.VideoPreset,
@@ -71,8 +75,10 @@ internal static class Mapper
ffmpegProfile.AudioBitrate,
ffmpegProfile.AudioBufferSize,
ffmpegProfile.NormalizeLoudnessMode,
ffmpegProfile.TargetLoudness,
ffmpegProfile.AudioChannels,
ffmpegProfile.AudioSampleRate,
ffmpegProfile.NormalizeFramerate,
ffmpegProfile.DeinterlaceVideo);
ffmpegProfile.NormalizeColors,
ffmpegProfile.DeinterlaceVideo == true);
}
@@ -20,4 +20,6 @@ public record CreateFillerPreset(
int? PlaylistId,
string Expression,
bool UseChaptersAsMediaItems
) : IRequest<Either<BaseError, Unit>>;
) : IRequest<Either<BaseError, CreateFillerPresetResult>>;
public record CreateFillerPresetResult(int FillerPresetId) : EntityIdResult(FillerPresetId);
@@ -6,23 +6,25 @@ using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Filler;
public class CreateFillerPresetHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<CreateFillerPreset, Either<BaseError, Unit>>
: IRequestHandler<CreateFillerPreset, Either<BaseError, CreateFillerPresetResult>>
{
public async Task<Either<BaseError, Unit>> Handle(CreateFillerPreset request, CancellationToken cancellationToken)
public async Task<Either<BaseError, CreateFillerPresetResult>> Handle(
CreateFillerPreset request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, FillerPreset> validation = await Validate(dbContext, request);
return await validation.Apply(fp => Persist(dbContext, fp, cancellationToken));
}
private static async Task<Unit> Persist(
private static async Task<CreateFillerPresetResult> Persist(
TvContext dbContext,
FillerPreset fillerPreset,
CancellationToken cancellationToken)
{
await dbContext.FillerPresets.AddAsync(fillerPreset, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
return Unit.Default;
return new CreateFillerPresetResult(fillerPreset.Id);
}
private static Task<Validation<BaseError, FillerPreset>> Validate(
+19
View File
@@ -8,6 +8,25 @@ internal static class Mapper
internal static FillerPresetResponseModel ProjectToResponseModel(FillerPreset fillerPreset) =>
new(fillerPreset.Id, fillerPreset.Name);
internal static FillerPresetFullResponseModel ProjectToFullResponseModel(FillerPreset fillerPreset) =>
new(
fillerPreset.Id,
fillerPreset.Name,
fillerPreset.FillerKind,
fillerPreset.FillerMode,
fillerPreset.Duration,
fillerPreset.Count,
fillerPreset.PadToNearestMinute,
fillerPreset.AllowWatermarks,
fillerPreset.CollectionType,
fillerPreset.CollectionId,
fillerPreset.MediaItemId,
fillerPreset.MultiCollectionId,
fillerPreset.SmartCollectionId,
fillerPreset.PlaylistId,
fillerPreset.Expression,
fillerPreset.UseChaptersAsMediaItems);
internal static FillerPresetViewModel ProjectToViewModel(FillerPreset fillerPreset) =>
new(
fillerPreset.Id,
@@ -0,0 +1,5 @@
using ErsatzTV.Core.Api.Filler;
namespace ErsatzTV.Application.Filler;
public record GetFillerPresetByIdForApi(int Id) : IRequest<Option<FillerPresetFullResponseModel>>;
@@ -0,0 +1,22 @@
using ErsatzTV.Core.Api.Filler;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.Filler.Mapper;
namespace ErsatzTV.Application.Filler;
public class GetFillerPresetByIdForApiHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<GetFillerPresetByIdForApi, Option<FillerPresetFullResponseModel>>
{
public async Task<Option<FillerPresetFullResponseModel>> Handle(
GetFillerPresetByIdForApi request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
return await dbContext.FillerPresets
.AsNoTracking()
.SelectOneAsync(fp => fp.Id, fp => fp.Id == request.Id, cancellationToken)
.MapT(ProjectToFullResponseModel);
}
}
+20
View File
@@ -9,6 +9,26 @@ internal static class Mapper
internal static WatermarkResponseModel ProjectToResponseModel(ChannelWatermark watermark) =>
new(watermark.Id, watermark.Name);
internal static WatermarkFullResponseModel ProjectToFullResponseModel(ChannelWatermark watermark) =>
new(
watermark.Id,
watermark.Name,
watermark.Mode,
watermark.ImageSource,
watermark.Image,
watermark.OriginalContentType,
watermark.Location,
watermark.Size,
watermark.WidthPercent,
watermark.HorizontalMarginPercent,
watermark.VerticalMarginPercent,
watermark.FrequencyMinutes,
watermark.DurationSeconds,
watermark.Opacity,
watermark.OpacityExpression,
watermark.ZIndex,
watermark.PlaceWithinSourceContent);
public static WatermarkViewModel ProjectToViewModel(ChannelWatermark watermark) =>
new(
watermark.Id,
@@ -0,0 +1,5 @@
using ErsatzTV.Core.Api.Watermarks;
namespace ErsatzTV.Application.Watermarks;
public record GetWatermarkByIdForApi(int Id) : IRequest<Option<WatermarkFullResponseModel>>;
@@ -0,0 +1,22 @@
using ErsatzTV.Core.Api.Watermarks;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.Watermarks.Mapper;
namespace ErsatzTV.Application.Watermarks;
public class GetWatermarkByIdForApiHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<GetWatermarkByIdForApi, Option<WatermarkFullResponseModel>>
{
public async Task<Option<WatermarkFullResponseModel>> Handle(
GetWatermarkByIdForApi request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
return await dbContext.ChannelWatermarks
.AsNoTracking()
.SelectOneAsync(w => w.Id, w => w.Id == request.Id, cancellationToken)
.MapT(ProjectToFullResponseModel);
}
}
@@ -1,4 +1,5 @@
using ErsatzTV.Core.Domain;
#nullable enable
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.FFmpeg;
namespace ErsatzTV.Core.Api.FFmpegProfiles;
@@ -7,13 +8,17 @@ public record FFmpegFullProfileResponseModel(
int Id,
string Name,
int ThreadCount,
bool NormalizeAudio,
bool NormalizeVideo,
HardwareAccelerationKind HardwareAcceleration,
string VaapiDisplay,
VaapiDriver VaapiDriver,
string VaapiDevice,
int? QsvExtraHardwareFrames,
int ResolutionId,
string Resolution,
ScalingBehavior ScalingBehavior,
FilterMode PadMode,
FFmpegProfileVideoFormat VideoFormat,
string VideoProfile,
string VideoPreset,
@@ -26,7 +31,9 @@ public record FFmpegFullProfileResponseModel(
int AudioBitrate,
int AudioBufferSize,
NormalizeLoudnessMode NormalizeLoudnessMode,
double? TargetLoudness,
int AudioChannels,
int AudioSampleRate,
bool NormalizeFramerate,
bool? DeinterlaceVideo);
bool NormalizeColors,
bool DeinterlaceVideo);
@@ -0,0 +1,23 @@
#nullable enable
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
namespace ErsatzTV.Core.Api.Filler;
public record FillerPresetFullResponseModel(
int Id,
string Name,
FillerKind FillerKind,
FillerMode FillerMode,
TimeSpan? Duration,
int? Count,
int? PadToNearestMinute,
bool AllowWatermarks,
CollectionType CollectionType,
int? CollectionId,
int? MediaItemId,
int? MultiCollectionId,
int? SmartCollectionId,
int? PlaylistId,
string? Expression,
bool UseChaptersAsMediaItems);
@@ -0,0 +1,24 @@
#nullable enable
using ErsatzTV.Core.Domain;
using ErsatzTV.FFmpeg.State;
namespace ErsatzTV.Core.Api.Watermarks;
public record WatermarkFullResponseModel(
int Id,
string Name,
ChannelWatermarkMode Mode,
ChannelWatermarkImageSource ImageSource,
string? Image,
string? ImageContentType,
WatermarkLocation Location,
WatermarkSize Size,
double Width,
double HorizontalMargin,
double VerticalMargin,
int FrequencyMinutes,
int DurationSeconds,
int Opacity,
string? OpacityExpression,
int ZIndex,
bool PlaceWithinSourceContent);
@@ -188,13 +188,17 @@ public class FFmpegProfileControllerTests
id,
"Default",
1,
true,
true,
HardwareAccelerationKind.None,
"drm",
VaapiDriver.Default,
"/dev/dri/renderD128",
null,
1,
"HD",
ScalingBehavior.ScaleAndPad,
FilterMode.Software,
FFmpegProfileVideoFormat.H264,
string.Empty,
string.Empty,
@@ -207,9 +211,11 @@ public class FFmpegProfileControllerTests
192,
384,
NormalizeLoudnessMode.Off,
null,
2,
48_000,
false,
true,
false);
private static CreateFFmpegProfileRequest MakeCreateRequest() =>
@@ -1,21 +1,27 @@
using System.Reflection;
using ErsatzTV.Application.Filler;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Filler;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
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 FillerPresetControllerTests
{
private FillerPresetController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
@@ -23,15 +29,33 @@ public class FillerPresetControllerTests
_controller = new FillerPresetController(_mediator);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Route()
{
MethodInfo action = typeof(FillerPresetController).GetMethod(nameof(FillerPresetController.GetAll))
?? throw new AssertionException("Missing action GetAll");
private FillerPresetController _controller = null!;
private IMediator _mediator = null!;
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain("GET");
attribute.Template.ShouldBe("/api/filler-presets");
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute("GET", "/api/filler-presets");
ShouldHaveActionRoute("GET", "/api/filler-presets/{id:int}");
ShouldHaveActionRoute("POST", "/api/filler-presets");
ShouldHaveActionRoute("PUT", "/api/filler-presets/{id:int}");
ShouldHaveActionRoute("DELETE", "/api/filler-presets/{id:int}");
}
[Test]
public void Mutations_Should_Use_Request_Dtos_For_Wire_Contract()
{
ParameterInfo createRequest = typeof(FillerPresetController)
.GetMethod(nameof(FillerPresetController.Create))!
.GetParameters()
.Single(p => p.Name == "request");
ParameterInfo updateRequest = typeof(FillerPresetController)
.GetMethod(nameof(FillerPresetController.Update))!
.GetParameters()
.Single(p => p.Name == "request");
createRequest.ParameterType.ShouldBe(typeof(CreateFillerPresetRequest));
updateRequest.ParameterType.ShouldBe(typeof(UpdateFillerPresetRequest));
}
[Test]
@@ -51,13 +75,170 @@ public class FillerPresetControllerTests
}
[Test]
public async Task GetAll_Should_Return_Empty_List_When_None_Exist()
public async Task GetById_Should_Return_200_For_Some()
{
_mediator.Send(Arg.Any<GetAllFillerPresetsForApi>(), Arg.Any<CancellationToken>())
.Returns([]);
FillerPresetFullResponseModel vm = MakeVm(4);
_mediator.Send(Arg.Any<GetFillerPresetByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FillerPresetFullResponseModel>.Some(vm));
List<FillerPresetResponseModel> result = await _controller.GetAll(CancellationToken.None);
IActionResult result = await _controller.GetById(4, CancellationToken.None);
result.ShouldBeEmpty();
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
}
[Test]
public async Task GetById_Should_Return_404_For_None()
{
_mediator.Send(Arg.Any<GetFillerPresetByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FillerPresetFullResponseModel>.None);
IActionResult result = await _controller.GetById(4, CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
var problemDetails = notFound.Value.ShouldBeOfType<ProblemDetails>();
problemDetails.Status.ShouldBe(404);
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
_mediator.Send(Arg.Any<CreateFillerPreset>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, CreateFillerPresetResult>(new CreateFillerPresetResult(7)));
FillerPresetFullResponseModel vm = MakeVm(7);
_mediator.Send(Arg.Any<GetFillerPresetByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FillerPresetFullResponseModel>.Some(vm));
IActionResult result = await _controller.Create(MakeCreateRequest(), CancellationToken.None);
var created = result.ShouldBeOfType<CreatedResult>();
created.StatusCode.ShouldBe(201);
created.Location.ShouldBe("/api/filler-presets/7");
created.Value.ShouldBe(vm);
}
[Test]
public async Task Create_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<CreateFillerPreset>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, CreateFillerPresetResult>(BaseError.New("bad")));
IActionResult result = await _controller.Create(MakeCreateRequest(), CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task Update_Should_Return_200_And_Map_Route_Id_To_Command()
{
_mediator.Send(Arg.Any<UpdateFillerPreset>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
FillerPresetFullResponseModel vm = MakeVm(8);
_mediator.Send(Arg.Any<GetFillerPresetByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<FillerPresetFullResponseModel>.Some(vm));
IActionResult result = await _controller.Update(8, MakeUpdateRequest(), CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
await _mediator.Received(1).Send(
Arg.Is<UpdateFillerPreset>(c => c.Id == 8),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Update_Should_Return_422_For_Error()
{
_mediator.Send(Arg.Any<UpdateFillerPreset>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(BaseError.New("nope")));
IActionResult result = await _controller.Update(99, MakeUpdateRequest(), CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task Delete_Should_Return_204_On_Success()
{
_mediator.Send(Arg.Any<DeleteFillerPreset>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.Delete(9, CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
}
[Test]
public async Task Delete_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<DeleteFillerPreset>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(new NotFoundError("missing")));
IActionResult result = await _controller.Delete(9, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
private static void ShouldHaveActionRoute(string httpMethod, string route)
{
bool exists = typeof(FillerPresetController)
.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 FillerPresetFullResponseModel MakeVm(int id) =>
new(
id,
"Intro",
FillerKind.PreRoll,
FillerMode.Count,
null,
3,
null,
true,
CollectionType.Collection,
5,
null,
null,
null,
null,
null,
false);
private static CreateFillerPresetRequest MakeCreateRequest() =>
new(
"Intro",
FillerKind.PreRoll,
FillerMode.Count,
null,
3,
null,
true,
CollectionType.Collection,
5,
null,
null,
null,
null,
null,
false);
private static UpdateFillerPresetRequest MakeUpdateRequest() =>
new(
"Intro",
FillerKind.PreRoll,
FillerMode.Count,
null,
3,
null,
true,
CollectionType.Collection,
5,
null,
null,
null,
null,
null,
false);
}
@@ -174,6 +174,26 @@ public class OpenApiErrorResponseContractTests
[TestCase("/api/ffmpeg/profiles/{id}", "delete", "404")]
[TestCase("/api/ffmpeg/profiles/{id}", "delete", "401")]
[TestCase("/api/ffmpeg/profiles/{id}", "delete", "422")]
[TestCase("/api/filler-presets/{id}", "get", "404")]
[TestCase("/api/filler-presets", "post", "401")]
[TestCase("/api/filler-presets", "post", "404")]
[TestCase("/api/filler-presets", "post", "422")]
[TestCase("/api/filler-presets/{id}", "put", "401")]
[TestCase("/api/filler-presets/{id}", "put", "404")]
[TestCase("/api/filler-presets/{id}", "put", "422")]
[TestCase("/api/filler-presets/{id}", "delete", "401")]
[TestCase("/api/filler-presets/{id}", "delete", "404")]
[TestCase("/api/filler-presets/{id}", "delete", "422")]
[TestCase("/api/watermarks/{id}", "get", "404")]
[TestCase("/api/watermarks", "post", "401")]
[TestCase("/api/watermarks", "post", "404")]
[TestCase("/api/watermarks", "post", "422")]
[TestCase("/api/watermarks/{id}", "put", "401")]
[TestCase("/api/watermarks/{id}", "put", "404")]
[TestCase("/api/watermarks/{id}", "put", "422")]
[TestCase("/api/watermarks/{id}", "delete", "401")]
[TestCase("/api/watermarks/{id}", "delete", "404")]
[TestCase("/api/watermarks/{id}", "delete", "422")]
[TestCase("/api/settings/ffmpeg", "put", "401")]
[TestCase("/api/settings/ffmpeg", "put", "422")]
[TestCase("/api/settings/playout", "put", "401")]
@@ -1,21 +1,27 @@
using System.Reflection;
using ErsatzTV.Application.Watermarks;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Watermarks;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.FFmpeg.State;
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 WatermarkControllerTests
{
private WatermarkController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
@@ -23,15 +29,33 @@ public class WatermarkControllerTests
_controller = new WatermarkController(_mediator);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Route()
{
MethodInfo action = typeof(WatermarkController).GetMethod(nameof(WatermarkController.GetAll))
?? throw new AssertionException("Missing action GetAll");
private WatermarkController _controller = null!;
private IMediator _mediator = null!;
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain("GET");
attribute.Template.ShouldBe("/api/watermarks");
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute("GET", "/api/watermarks");
ShouldHaveActionRoute("GET", "/api/watermarks/{id:int}");
ShouldHaveActionRoute("POST", "/api/watermarks");
ShouldHaveActionRoute("PUT", "/api/watermarks/{id:int}");
ShouldHaveActionRoute("DELETE", "/api/watermarks/{id:int}");
}
[Test]
public void Mutations_Should_Use_Request_Dtos_For_Wire_Contract()
{
ParameterInfo createRequest = typeof(WatermarkController)
.GetMethod(nameof(WatermarkController.Create))!
.GetParameters()
.Single(p => p.Name == "request");
ParameterInfo updateRequest = typeof(WatermarkController)
.GetMethod(nameof(WatermarkController.Update))!
.GetParameters()
.Single(p => p.Name == "request");
createRequest.ParameterType.ShouldBe(typeof(CreateWatermarkRequest));
updateRequest.ParameterType.ShouldBe(typeof(UpdateWatermarkRequest));
}
[Test]
@@ -51,13 +75,173 @@ public class WatermarkControllerTests
}
[Test]
public async Task GetAll_Should_Return_Empty_List_When_None_Exist()
public async Task GetById_Should_Return_200_For_Some()
{
_mediator.Send(Arg.Any<GetAllWatermarksForApi>(), Arg.Any<CancellationToken>())
.Returns([]);
WatermarkFullResponseModel vm = MakeVm(4);
_mediator.Send(Arg.Any<GetWatermarkByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<WatermarkFullResponseModel>.Some(vm));
List<WatermarkResponseModel> result = await _controller.GetAll(CancellationToken.None);
IActionResult result = await _controller.GetById(4, CancellationToken.None);
result.ShouldBeEmpty();
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
}
[Test]
public async Task GetById_Should_Return_404_For_None()
{
_mediator.Send(Arg.Any<GetWatermarkByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<WatermarkFullResponseModel>.None);
IActionResult result = await _controller.GetById(4, CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
var problemDetails = notFound.Value.ShouldBeOfType<ProblemDetails>();
problemDetails.Status.ShouldBe(404);
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
_mediator.Send(Arg.Any<CreateWatermark>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, CreateWatermarkResult>(new CreateWatermarkResult(7)));
WatermarkFullResponseModel vm = MakeVm(7);
_mediator.Send(Arg.Any<GetWatermarkByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<WatermarkFullResponseModel>.Some(vm));
IActionResult result = await _controller.Create(MakeCreateRequest(), CancellationToken.None);
var created = result.ShouldBeOfType<CreatedResult>();
created.StatusCode.ShouldBe(201);
created.Location.ShouldBe("/api/watermarks/7");
created.Value.ShouldBe(vm);
}
[Test]
public async Task Create_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<CreateWatermark>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, CreateWatermarkResult>(BaseError.New("bad")));
IActionResult result = await _controller.Create(MakeCreateRequest(), CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task Update_Should_Return_200_And_Map_Route_Id_To_Command()
{
_mediator.Send(Arg.Any<UpdateWatermark>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, UpdateWatermarkResult>(new UpdateWatermarkResult(8)));
WatermarkFullResponseModel vm = MakeVm(8);
_mediator.Send(Arg.Any<GetWatermarkByIdForApi>(), Arg.Any<CancellationToken>())
.Returns(Option<WatermarkFullResponseModel>.Some(vm));
IActionResult result = await _controller.Update(8, MakeUpdateRequest(), CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(vm);
await _mediator.Received(1).Send(
Arg.Is<UpdateWatermark>(c => c.Id == 8),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Update_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<UpdateWatermark>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, UpdateWatermarkResult>(new NotFoundError("missing")));
IActionResult result = await _controller.Update(99, MakeUpdateRequest(), CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task Delete_Should_Return_204_On_Success()
{
_mediator.Send(Arg.Any<DeleteWatermark>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.Delete(9, CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
}
[Test]
public async Task Delete_Should_Return_404_For_NotFoundError()
{
_mediator.Send(Arg.Any<DeleteWatermark>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(new NotFoundError("missing")));
IActionResult result = await _controller.Delete(9, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
private static void ShouldHaveActionRoute(string httpMethod, string route)
{
bool exists = typeof(WatermarkController)
.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 WatermarkFullResponseModel MakeVm(int id) =>
new(
id,
"Corner Logo",
ChannelWatermarkMode.Permanent,
ChannelWatermarkImageSource.Custom,
"abc.png",
"image/png",
WatermarkLocation.BottomRight,
WatermarkSize.Scaled,
15,
5,
5,
15,
10,
80,
null,
0,
false);
private static CreateWatermarkRequest MakeCreateRequest() =>
new(
"Corner Logo",
ChannelWatermarkMode.Permanent,
ChannelWatermarkImageSource.Custom,
"abc.png",
"image/png",
WatermarkLocation.BottomRight,
WatermarkSize.Scaled,
15,
5,
5,
15,
10,
80,
null,
0,
false);
private static UpdateWatermarkRequest MakeUpdateRequest() =>
new(
"Corner Logo",
ChannelWatermarkMode.Permanent,
ChannelWatermarkImageSource.Custom,
"abc.png",
"image/png",
WatermarkLocation.BottomRight,
WatermarkSize.Scaled,
15,
5,
5,
15,
10,
80,
null,
0,
false);
}
@@ -3,6 +3,7 @@ using ErsatzTV.Application.FFmpegProfiles;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.FFmpegProfiles;
using ErsatzTV.Core.Domain;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
@@ -21,6 +22,18 @@ public class FFmpegProfileController(IMediator mediator) : ControllerBase
public async Task<List<FFmpegFullProfileResponseModel>> GetAll(CancellationToken cancellationToken) =>
await mediator.Send(new GetAllFFmpegProfilesForApi(), cancellationToken);
[HttpGet("/api/ffmpeg/hardware-acceleration-kinds", Name = "GetSupportedHardwareAccelerationKinds")]
[Tags("FFmpeg Profiles")]
[EndpointSummary("Get supported hardware acceleration kinds")]
[EndpointDescription(
"Returns the hardware-acceleration kinds available on this host (probed from the configured " +
"FFmpeg binary). Always includes None; falls back to just None when FFmpeg is unavailable.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<HardwareAccelerationKind>), StatusCodes.Status200OK)]
public async Task<List<HardwareAccelerationKind>> GetHardwareAccelerationKinds(CancellationToken cancellationToken) =>
// returns the enum values directly; the API serializes enums as their string names
await mediator.Send(new GetSupportedHardwareAccelerationKinds(), cancellationToken);
[HttpGet("/api/ffmpeg/profiles/{id:int}", Name = "GetFFmpegProfileById")]
[Tags("FFmpeg Profiles")]
[EndpointSummary("Get an FFmpeg profile by id")]
@@ -1,5 +1,9 @@
using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.Filler;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Filler;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -16,4 +20,83 @@ public class FillerPresetController(IMediator mediator) : ControllerBase
[ProducesResponseType(typeof(List<FillerPresetResponseModel>), StatusCodes.Status200OK)]
public async Task<List<FillerPresetResponseModel>> GetAll(CancellationToken cancellationToken) =>
await mediator.Send(new GetAllFillerPresetsForApi(), cancellationToken);
[HttpGet("/api/filler-presets/{id:int}", Name = "GetFillerPresetById")]
[Tags("Filler Presets")]
[EndpointSummary("Get a filler preset by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(FillerPresetFullResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<FillerPresetFullResponseModel> result =
await mediator.Send(new GetFillerPresetByIdForApi(id), cancellationToken);
return result.ToGetResult();
}
[HttpPost("/api/filler-presets", Name = "CreateFillerPreset")]
[Tags("Filler Presets")]
[EndpointSummary("Create a filler preset")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(FillerPresetFullResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required] [FromBody] CreateFillerPresetRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, CreateFillerPresetResult> result =
await mediator.Send(request.ToCommand(), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async created =>
{
Option<FillerPresetFullResponseModel> fillerPreset =
await mediator.Send(new GetFillerPresetByIdForApi(created.FillerPresetId), cancellationToken);
return fillerPreset.Match(
Some: vm => (IActionResult)new CreatedResult($"/api/filler-presets/{vm.Id}", vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpPut("/api/filler-presets/{id:int}", Name = "UpdateFillerPreset")]
[Tags("Filler Presets")]
[EndpointSummary("Update a filler preset")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(FillerPresetFullResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required] [FromBody] UpdateFillerPresetRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
Option<FillerPresetFullResponseModel> fillerPreset =
await mediator.Send(new GetFillerPresetByIdForApi(id), cancellationToken);
return fillerPreset.Match(
Some: vm => (IActionResult)new OkObjectResult(vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpDelete("/api/filler-presets/{id:int}", Name = "DeleteFillerPreset")]
[Tags("Filler Presets")]
[EndpointSummary("Delete a filler preset")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[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 DeleteFillerPreset(id), cancellationToken);
return result.ToDeletedResult();
}
}
@@ -0,0 +1,42 @@
#nullable enable
using ErsatzTV.Application.Filler;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
namespace ErsatzTV.Controllers.Api.Requests;
public record CreateFillerPresetRequest(
string Name,
FillerKind FillerKind,
FillerMode FillerMode,
TimeSpan? Duration,
int? Count,
int? PadToNearestMinute,
bool AllowWatermarks,
CollectionType CollectionType,
int? CollectionId,
int? MediaItemId,
int? MultiCollectionId,
int? SmartCollectionId,
int? PlaylistId,
string? Expression,
bool UseChaptersAsMediaItems)
{
public CreateFillerPreset ToCommand() =>
new(
Name,
FillerKind,
FillerMode,
Duration,
Count,
PadToNearestMinute,
AllowWatermarks,
CollectionType,
CollectionId,
MediaItemId,
MultiCollectionId,
SmartCollectionId,
PlaylistId,
Expression ?? string.Empty,
UseChaptersAsMediaItems);
}
@@ -0,0 +1,44 @@
#nullable enable
using ErsatzTV.Application.Artworks;
using ErsatzTV.Application.Watermarks;
using ErsatzTV.Core.Domain;
using ErsatzTV.FFmpeg.State;
namespace ErsatzTV.Controllers.Api.Requests;
public record CreateWatermarkRequest(
string Name,
ChannelWatermarkMode Mode,
ChannelWatermarkImageSource ImageSource,
string? Image,
string? ImageContentType,
WatermarkLocation Location,
WatermarkSize Size,
double Width,
double HorizontalMargin,
double VerticalMargin,
int FrequencyMinutes,
int DurationSeconds,
int Opacity,
string? OpacityExpression,
int ZIndex,
bool PlaceWithinSourceContent)
{
public CreateWatermark ToCommand() =>
new(
Name,
new ArtworkContentTypeModel(Image ?? string.Empty, ImageContentType ?? string.Empty),
Mode,
ImageSource,
Location,
Size,
Width,
HorizontalMargin,
VerticalMargin,
FrequencyMinutes,
DurationSeconds,
Opacity,
PlaceWithinSourceContent,
OpacityExpression ?? string.Empty,
ZIndex);
}
@@ -0,0 +1,43 @@
#nullable enable
using ErsatzTV.Application.Filler;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
namespace ErsatzTV.Controllers.Api.Requests;
public record UpdateFillerPresetRequest(
string Name,
FillerKind FillerKind,
FillerMode FillerMode,
TimeSpan? Duration,
int? Count,
int? PadToNearestMinute,
bool AllowWatermarks,
CollectionType CollectionType,
int? CollectionId,
int? MediaItemId,
int? MultiCollectionId,
int? SmartCollectionId,
int? PlaylistId,
string? Expression,
bool UseChaptersAsMediaItems)
{
public UpdateFillerPreset ToCommand(int id) =>
new(
id,
Name,
FillerKind,
FillerMode,
Duration,
Count,
PadToNearestMinute,
AllowWatermarks,
CollectionType,
CollectionId,
MediaItemId,
MultiCollectionId,
SmartCollectionId,
PlaylistId,
Expression ?? string.Empty,
UseChaptersAsMediaItems);
}
@@ -0,0 +1,45 @@
#nullable enable
using ErsatzTV.Application.Artworks;
using ErsatzTV.Application.Watermarks;
using ErsatzTV.Core.Domain;
using ErsatzTV.FFmpeg.State;
namespace ErsatzTV.Controllers.Api.Requests;
public record UpdateWatermarkRequest(
string Name,
ChannelWatermarkMode Mode,
ChannelWatermarkImageSource ImageSource,
string? Image,
string? ImageContentType,
WatermarkLocation Location,
WatermarkSize Size,
double Width,
double HorizontalMargin,
double VerticalMargin,
int FrequencyMinutes,
int DurationSeconds,
int Opacity,
string? OpacityExpression,
int ZIndex,
bool PlaceWithinSourceContent)
{
public UpdateWatermark ToCommand(int id) =>
new(
id,
Name,
new ArtworkContentTypeModel(Image ?? string.Empty, ImageContentType ?? string.Empty),
Mode,
ImageSource,
Location,
Size,
Width,
HorizontalMargin,
VerticalMargin,
FrequencyMinutes,
DurationSeconds,
Opacity,
PlaceWithinSourceContent,
OpacityExpression ?? string.Empty,
ZIndex);
}
@@ -1,5 +1,9 @@
using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.Watermarks;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Watermarks;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -16,4 +20,83 @@ public class WatermarkController(IMediator mediator) : ControllerBase
[ProducesResponseType(typeof(List<WatermarkResponseModel>), StatusCodes.Status200OK)]
public async Task<List<WatermarkResponseModel>> GetAll(CancellationToken cancellationToken) =>
await mediator.Send(new GetAllWatermarksForApi(), cancellationToken);
[HttpGet("/api/watermarks/{id:int}", Name = "GetWatermarkById")]
[Tags("Watermarks")]
[EndpointSummary("Get a watermark by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(WatermarkFullResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<WatermarkFullResponseModel> result =
await mediator.Send(new GetWatermarkByIdForApi(id), cancellationToken);
return result.ToGetResult();
}
[HttpPost("/api/watermarks", Name = "CreateWatermark")]
[Tags("Watermarks")]
[EndpointSummary("Create a watermark")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(WatermarkFullResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required] [FromBody] CreateWatermarkRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, CreateWatermarkResult> result = await mediator.Send(request.ToCommand(), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async created =>
{
Option<WatermarkFullResponseModel> watermark =
await mediator.Send(new GetWatermarkByIdForApi(created.WatermarkId), cancellationToken);
return watermark.Match(
Some: vm => (IActionResult)new CreatedResult($"/api/watermarks/{vm.Id}", vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpPut("/api/watermarks/{id:int}", Name = "UpdateWatermark")]
[Tags("Watermarks")]
[EndpointSummary("Update a watermark")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(WatermarkFullResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required] [FromBody] UpdateWatermarkRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, UpdateWatermarkResult> result =
await mediator.Send(request.ToCommand(id), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
Option<WatermarkFullResponseModel> watermark =
await mediator.Send(new GetWatermarkByIdForApi(id), cancellationToken);
return watermark.Match(
Some: vm => (IActionResult)new OkObjectResult(vm),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpDelete("/api/watermarks/{id:int}", Name = "DeleteWatermark")]
[Tags("Watermarks")]
[EndpointSummary("Delete a watermark")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
[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 DeleteWatermark(id), cancellationToken);
return result.ToDeletedResult();
}
}
+5 -3
View File
@@ -399,9 +399,11 @@
ValidationResult result = await _validator.ValidateAsync(_model, _cts.Token);
if (result.IsValid)
{
IRequest<Either<BaseError, Unit>> request = IsEdit ? _model.ToEdit() : _model.ToUpdate();
Seq<BaseError> errorMessage = (await Mediator.Send(request, _cts.Token)).LeftToSeq();
// Create/Update return different result types (Update -> Unit, Create -> CreateFillerPresetResult),
// so send each on its own branch and reduce to the shared Left error sequence.
Seq<BaseError> errorMessage = IsEdit
? (await Mediator.Send(_model.ToEdit(), _cts.Token)).LeftToSeq()
: (await Mediator.Send(_model.ToUpdate(), _cts.Token)).LeftToSeq();
errorMessage.HeadOrNone().Match(
error =>
+6 -1
View File
@@ -134,7 +134,12 @@ public class Startup
// a ReflectionTypeLoadException in environments missing optional native hardware-encoder deps.
Dictionary<string, Type> enumTypes = typeof(Core.Domain.PlayoutMode).Assembly.GetTypes()
.Where(type => type.IsEnum)
.Concat([typeof(FFmpeg.OutputFormat.OutputFormatKind), typeof(Serilog.Events.LogEventLevel)])
.Concat([
typeof(FFmpeg.OutputFormat.OutputFormatKind),
typeof(FFmpeg.State.WatermarkLocation),
typeof(FFmpeg.State.WatermarkSize),
typeof(Serilog.Events.LogEventLevel)
])
.GroupBy(type => type.Name)
.ToDictionary(group => group.Key, group => group.First());
@@ -159,7 +159,7 @@ public class FillerPresetEditViewModel
Expression,
UseChaptersAsMediaItems);
public IRequest<Either<BaseError, Unit>> ToUpdate() =>
public IRequest<Either<BaseError, CreateFillerPresetResult>> ToUpdate() =>
new CreateFillerPreset(
Name,
FillerKind,
File diff suppressed because it is too large Load Diff