@@ -25,8 +25,12 @@ public class CreateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
return Mapper.ProjectToViewModel(deco);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Deco>> Validate(TvContext dbContext, CreateDeco request) =>
|
||||
await ValidateDecoName(dbContext, request).MapT(name => new Deco
|
||||
private static async Task<Validation<BaseError, Deco>> Validate(TvContext dbContext, CreateDeco request)
|
||||
{
|
||||
Validation<BaseError, Unit> decoGroupValidation = await ValidateDecoGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateDecoName(dbContext, request);
|
||||
|
||||
return (decoGroupValidation, nameValidation).Apply((_, name) => new Deco
|
||||
{
|
||||
DecoGroupId = request.DecoGroupId,
|
||||
Name = name,
|
||||
@@ -34,6 +38,18 @@ public class CreateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
DecoWatermarks = [],
|
||||
DecoGraphicsElements = []
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateDecoGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateDeco request)
|
||||
{
|
||||
bool decoGroupExists = await dbContext.DecoGroups.AnyAsync(dg => dg.Id == request.DecoGroupId);
|
||||
|
||||
return decoGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Deco group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateDecoName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -97,6 +97,7 @@ public class UpdateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
{
|
||||
ex.CollectionType = toUpdate.CollectionType;
|
||||
ex.CollectionId = toUpdate.CollectionId;
|
||||
ex.MediaItemId = toUpdate.MediaItemId;
|
||||
ex.MultiCollectionId = toUpdate.MultiCollectionId;
|
||||
ex.SmartCollectionId = toUpdate.SmartCollectionId;
|
||||
ex.PlaylistId = toUpdate.PlaylistId;
|
||||
@@ -111,6 +112,7 @@ public class UpdateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
DecoId = existing.Id,
|
||||
CollectionType = add.CollectionType,
|
||||
CollectionId = add.CollectionId,
|
||||
MediaItemId = add.MediaItemId,
|
||||
MultiCollectionId = add.MultiCollectionId,
|
||||
SmartCollectionId = add.SmartCollectionId,
|
||||
PlaylistId = add.PlaylistId,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.MediaCollections;
|
||||
|
||||
public record PlaylistGroupResponseModel(int Id, string Name, int PlaylistCount, bool IsSystem);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.MediaCollections;
|
||||
|
||||
public record PlaylistResponseModel(int Id, int PlaylistGroupId, string Name, bool IsSystem);
|
||||
@@ -0,0 +1,17 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoBreakContentResponseModel(
|
||||
int Id,
|
||||
CollectionType CollectionType,
|
||||
int? CollectionId,
|
||||
int? MediaItemId,
|
||||
int? MultiCollectionId,
|
||||
int? SmartCollectionId,
|
||||
int? PlaylistId,
|
||||
int? PlaylistGroupId,
|
||||
string? SelectionName,
|
||||
DecoBreakPlacement Placement);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoGroupResponseModel(int Id, string Name, int DecoCount);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoListItemResponseModel(int Id, int DecoGroupId, string DecoGroupName, string Name);
|
||||
@@ -0,0 +1,34 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoResponseModel(
|
||||
int Id,
|
||||
int DecoGroupId,
|
||||
string DecoGroupName,
|
||||
string Name,
|
||||
DecoMode WatermarkMode,
|
||||
List<int> WatermarkIds,
|
||||
bool UseWatermarkDuringFiller,
|
||||
DecoMode GraphicsElementsMode,
|
||||
List<int> GraphicsElementIds,
|
||||
bool UseGraphicsElementsDuringFiller,
|
||||
DecoMode BreakContentMode,
|
||||
List<DecoBreakContentResponseModel> BreakContent,
|
||||
DecoMode DefaultFillerMode,
|
||||
CollectionType DefaultFillerCollectionType,
|
||||
int? DefaultFillerCollectionId,
|
||||
int? DefaultFillerMediaItemId,
|
||||
int? DefaultFillerMultiCollectionId,
|
||||
int? DefaultFillerSmartCollectionId,
|
||||
string? DefaultFillerSelectionName,
|
||||
bool DefaultFillerTrimToFit,
|
||||
DecoMode DeadAirFallbackMode,
|
||||
CollectionType DeadAirFallbackCollectionType,
|
||||
int? DeadAirFallbackCollectionId,
|
||||
int? DeadAirFallbackMediaItemId,
|
||||
int? DeadAirFallbackMultiCollectionId,
|
||||
int? DeadAirFallbackSmartCollectionId,
|
||||
string? DeadAirFallbackSelectionName);
|
||||
@@ -28,6 +28,7 @@ public class ApiControllerSecurityTests
|
||||
typeof(BlockController),
|
||||
typeof(ChannelController),
|
||||
typeof(CollectionController),
|
||||
typeof(DecoController),
|
||||
typeof(FFmpegProfileController),
|
||||
typeof(FillerPresetController),
|
||||
typeof(LibrariesController),
|
||||
|
||||
@@ -93,6 +93,17 @@ public class ApiErrorResponseMetadataTests
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Copy), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Copy), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.CreateGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.CreateGroup), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.DeleteGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Replace), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.UpdateDefaultDeco), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.UpdateDefaultDeco), 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)]
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
using System.Reflection;
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Controllers.Api;
|
||||
using ErsatzTV.Controllers.Api.Requests;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.Scheduling;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.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;
|
||||
|
||||
namespace ErsatzTV.Tests.Controllers;
|
||||
|
||||
[TestFixture]
|
||||
public class DecoControllerTests
|
||||
{
|
||||
private DecoController _controller = null!;
|
||||
private IMediator _mediator = null!;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_mediator = Substitute.For<IMediator>();
|
||||
_controller = new DecoController(_mediator);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
|
||||
{
|
||||
ShouldHaveActionRoute(nameof(DecoController.GetGroups), "GET", "/api/decos/groups");
|
||||
ShouldHaveActionRoute(nameof(DecoController.CreateGroup), "POST", "/api/decos/groups");
|
||||
ShouldHaveActionRoute(nameof(DecoController.DeleteGroup), "DELETE", "/api/decos/groups/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(DecoController.GetAll), "GET", "/api/decos");
|
||||
ShouldHaveActionRoute(nameof(DecoController.GetById), "GET", "/api/decos/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(DecoController.Create), "POST", "/api/decos");
|
||||
ShouldHaveActionRoute(nameof(DecoController.Delete), "DELETE", "/api/decos/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(DecoController.Replace), "PUT", "/api/decos/{id:int}");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetGroups_Should_Map_ViewModels()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllDecoGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DecoGroupViewModel> { new(3, "Bumpers", 2) });
|
||||
|
||||
List<DecoGroupResponseModel> result = await _controller.GetGroups(CancellationToken.None);
|
||||
|
||||
result.Count.ShouldBe(1);
|
||||
result[0].Id.ShouldBe(3);
|
||||
result[0].Name.ShouldBe("Bumpers");
|
||||
result[0].DecoCount.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_201_With_Location_And_Body()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateDecoGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, DecoGroupViewModel>(new DecoGroupViewModel(5, "Bumpers", 0)));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateDecoGroupRequest("Bumpers"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/decos/groups/5");
|
||||
created.Value.ShouldBeOfType<DecoGroupResponseModel>().Name.ShouldBe("Bumpers");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateDecoGroup>(c => c.Name == "Bumpers"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateDecoGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, DecoGroupViewModel>(BaseError.New("bad")));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateDecoGroupRequest(string.Empty),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_204_When_Exists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllDecoGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DecoGroupViewModel> { new(3, "Bumpers", 0) });
|
||||
_mediator.Send(Arg.Any<DeleteDecoGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BaseError>.None);
|
||||
|
||||
IActionResult result = await _controller.DeleteGroup(3, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NoContentResult>();
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<DeleteDecoGroup>(c => c.DecoGroupId == 3),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllDecoGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DecoGroupViewModel>());
|
||||
|
||||
IActionResult result = await _controller.DeleteGroup(99, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteDecoGroup>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAll_Should_Flatten_Decos_Across_Groups()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllDecoGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DecoGroupViewModel> { new(1, "A", 1), new(2, "B", 1) });
|
||||
_mediator.Send(Arg.Is<GetDecosByDecoGroupId>(q => q.DecoGroupId == 1), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DecoViewModel> { MakeDeco(10, 1, "First") });
|
||||
_mediator.Send(Arg.Is<GetDecosByDecoGroupId>(q => q.DecoGroupId == 2), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DecoViewModel> { MakeDeco(20, 2, "Second") });
|
||||
|
||||
List<DecoListItemResponseModel> result = await _controller.GetAll(CancellationToken.None);
|
||||
|
||||
result.Count.ShouldBe(2);
|
||||
result[0].Id.ShouldBe(10);
|
||||
result[0].DecoGroupId.ShouldBe(1);
|
||||
result[1].Id.ShouldBe(20);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_200_And_Map_All_Sections()
|
||||
{
|
||||
DecoViewModel deco = MakeDeco(
|
||||
4,
|
||||
2,
|
||||
"Movie Night",
|
||||
watermarkMode: DecoMode.Merge,
|
||||
breakContentMode: DecoMode.Override,
|
||||
breakContent:
|
||||
[
|
||||
new DecoBreakContentViewModel(
|
||||
7,
|
||||
CollectionType.Playlist,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
new ErsatzTV.Application.MediaCollections.PlaylistViewModel(9, 3, "Idents", false),
|
||||
DecoBreakPlacement.BlockStart)
|
||||
]);
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.Some(deco));
|
||||
|
||||
IActionResult result = await _controller.GetById(4, CancellationToken.None);
|
||||
|
||||
var body = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<DecoResponseModel>();
|
||||
body.Id.ShouldBe(4);
|
||||
body.WatermarkMode.ShouldBe(DecoMode.Merge);
|
||||
body.BreakContentMode.ShouldBe(DecoMode.Override);
|
||||
body.BreakContent.Count.ShouldBe(1);
|
||||
body.BreakContent[0].PlaylistId.ShouldBe(9);
|
||||
body.BreakContent[0].PlaylistGroupId.ShouldBe(3);
|
||||
body.BreakContent[0].SelectionName.ShouldBe("Idents");
|
||||
body.BreakContent[0].Placement.ShouldBe(DecoBreakPlacement.BlockStart);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_404_For_None()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.GetById(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_201_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateDeco>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, DecoViewModel>(MakeDeco(8, 2, "Movie Night")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateDecoRequest(2, "Movie Night"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/decos/8");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateDeco>(c => c.DecoGroupId == 2 && c.Name == "Movie Night"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateDeco>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, DecoViewModel>(BaseError.New("Deco group does not exist")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateDecoRequest(99, "Movie Night"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_Should_Return_204_When_Exists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.Some(MakeDeco(4, 2, "Movie Night")));
|
||||
_mediator.Send(Arg.Any<DeleteDeco>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BaseError>.None);
|
||||
|
||||
IActionResult result = await _controller.Delete(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Delete(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteDeco>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_200_And_Send_Full_State_With_Current_GroupId()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.Some(MakeDeco(4, 7, "Movie Night")));
|
||||
_mediator.Send(Arg.Any<UpdateDeco>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, LanguageExt.Unit>(LanguageExt.Unit.Default));
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
MakeReplaceRequest(
|
||||
"Movie Night",
|
||||
breakContentMode: DecoMode.Override,
|
||||
breakContent:
|
||||
[
|
||||
new DecoBreakContentRequest(
|
||||
0,
|
||||
CollectionType.Playlist,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
9,
|
||||
DecoBreakPlacement.BlockStart)
|
||||
]),
|
||||
CancellationToken.None);
|
||||
|
||||
var body = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<DecoResponseModel>();
|
||||
body.Id.ShouldBe(4);
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<UpdateDeco>(c =>
|
||||
c.DecoId == 4 &&
|
||||
c.DecoGroupId == 7 &&
|
||||
c.Name == "Movie Night" &&
|
||||
c.BreakContentMode == DecoMode.Override &&
|
||||
c.BreakContent.Count == 1 &&
|
||||
c.BreakContent[0].PlaylistId == 9 &&
|
||||
c.BreakContent[0].Placement == DecoBreakPlacement.BlockStart),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
MakeReplaceRequest("Movie Night"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<UpdateDeco>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_422_On_Handler_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.Some(MakeDeco(4, 7, "Movie Night")));
|
||||
_mediator.Send(Arg.Any<UpdateDeco>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, LanguageExt.Unit>(BaseError.New("Deco may only contain one [Block Start] break content")));
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
MakeReplaceRequest("Movie Night"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_422_On_Merge_Mode_Mismatch_Without_Dispatch()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetDecoById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<DecoViewModel>.Some(MakeDeco(4, 7, "Movie Night")));
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
MakeReplaceRequest("Movie Night", defaultFillerMode: DecoMode.Merge),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<UpdateDeco>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
private static DecoViewModel MakeDeco(
|
||||
int id,
|
||||
int groupId,
|
||||
string name,
|
||||
DecoMode watermarkMode = DecoMode.Inherit,
|
||||
DecoMode breakContentMode = DecoMode.Inherit,
|
||||
List<DecoBreakContentViewModel>? breakContent = null) =>
|
||||
new(
|
||||
id,
|
||||
groupId,
|
||||
"Group",
|
||||
name,
|
||||
watermarkMode,
|
||||
[],
|
||||
false,
|
||||
DecoMode.Inherit,
|
||||
[],
|
||||
false,
|
||||
breakContentMode,
|
||||
breakContent ?? [],
|
||||
DecoMode.Inherit,
|
||||
CollectionType.Collection,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
DecoMode.Inherit,
|
||||
CollectionType.Collection,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
private static ReplaceDecoRequest MakeReplaceRequest(
|
||||
string name,
|
||||
DecoMode breakContentMode = DecoMode.Inherit,
|
||||
DecoMode defaultFillerMode = DecoMode.Inherit,
|
||||
List<DecoBreakContentRequest>? breakContent = null) =>
|
||||
new(
|
||||
name,
|
||||
DecoMode.Inherit,
|
||||
[],
|
||||
false,
|
||||
DecoMode.Inherit,
|
||||
[],
|
||||
false,
|
||||
breakContentMode,
|
||||
breakContent ?? [],
|
||||
defaultFillerMode,
|
||||
CollectionType.Collection,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
DecoMode.Inherit,
|
||||
CollectionType.Collection,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
|
||||
{
|
||||
MethodInfo action = typeof(DecoController).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,237 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Controllers.Api.Requests;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.Scheduling;
|
||||
using ErsatzTV.Extensions;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api;
|
||||
|
||||
[ApiController]
|
||||
public class DecoController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
[HttpGet("/api/decos/groups", Name = "GetDecoGroups")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Get all deco groups")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<DecoGroupResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<DecoGroupResponseModel>> GetGroups(CancellationToken cancellationToken)
|
||||
{
|
||||
List<DecoGroupViewModel> groups = await mediator.Send(new GetAllDecoGroups(), cancellationToken);
|
||||
return groups.Map(ProjectToResponseModel).ToList();
|
||||
}
|
||||
|
||||
[HttpPost("/api/decos/groups")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Create a deco group")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(DecoGroupResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> CreateGroup(
|
||||
[Required] [FromBody] CreateDecoGroupRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Either<BaseError, DecoGroupViewModel> result =
|
||||
await mediator.Send(request.ToCommand(), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/decos/groups/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
[HttpDelete("/api/decos/groups/{id:int}")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Delete a deco group")]
|
||||
[EndpointDescription(
|
||||
"Deletes the deco group. The database cascade removes every deco in the group (and each deco's break " +
|
||||
"content and watermark/graphics-element assignments); any playout that used a removed deco has its " +
|
||||
"default deco cleared.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeleteGroup(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
List<DecoGroupViewModel> groups = await mediator.Send(new GetAllDecoGroups(), cancellationToken);
|
||||
if (groups.All(g => g.Id != id))
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Option<BaseError> result = await mediator.Send(new DeleteDecoGroup(id), cancellationToken);
|
||||
return result.Match<IActionResult>(
|
||||
Some: error => error.ToErrorResult(),
|
||||
None: () => new NoContentResult());
|
||||
}
|
||||
|
||||
[HttpGet("/api/decos")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Get all decos")]
|
||||
[EndpointDescription("Returns every deco as a flat list, ordered by group name then deco name.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<DecoListItemResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<DecoListItemResponseModel>> GetAll(CancellationToken cancellationToken)
|
||||
{
|
||||
List<DecoGroupViewModel> groups = await mediator.Send(new GetAllDecoGroups(), cancellationToken);
|
||||
var result = new List<DecoListItemResponseModel>();
|
||||
foreach (DecoGroupViewModel group in groups)
|
||||
{
|
||||
List<DecoViewModel> decos = await mediator.Send(new GetDecosByDecoGroupId(group.Id), cancellationToken);
|
||||
result.AddRange(decos.Map(d => new DecoListItemResponseModel(d.Id, d.DecoGroupId, d.DecoGroupName, d.Name)));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
[HttpGet("/api/decos/{id:int}", Name = "GetDecoById")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Get a deco by id")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(DecoResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<DecoViewModel> result = await mediator.Send(new GetDecoById(id), cancellationToken);
|
||||
return result.Map(ProjectToResponseModel).ToGetResult();
|
||||
}
|
||||
|
||||
[HttpPost("/api/decos")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Create a deco")]
|
||||
[EndpointDescription("Creates a deco in the given deco group. The deco inherits everything by default.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(DecoResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Create(
|
||||
[Required] [FromBody] CreateDecoRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Either<BaseError, DecoViewModel> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/decos/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
[HttpDelete("/api/decos/{id:int}")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Delete a deco")]
|
||||
[EndpointDescription(
|
||||
"Deletes the deco. Any playout that used it as its default deco has that default cleared.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<DecoViewModel> existing = await mediator.Send(new GetDecoById(id), cancellationToken);
|
||||
if (existing.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Option<BaseError> result = await mediator.Send(new DeleteDeco(id), cancellationToken);
|
||||
return result.Match<IActionResult>(
|
||||
Some: error => error.ToErrorResult(),
|
||||
None: () => new NoContentResult());
|
||||
}
|
||||
|
||||
[HttpPut("/api/decos/{id:int}")]
|
||||
[Tags("Decos")]
|
||||
[EndpointSummary("Replace a deco")]
|
||||
[EndpointDescription(
|
||||
"Replaces the full state of the deco (name and all six sections). Send the entire desired state, including " +
|
||||
"unchanged sections. Merge is only valid for the watermark and graphics-element modes. Break content allows " +
|
||||
"at most one item per placement.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(DecoResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Replace(
|
||||
int id,
|
||||
[Required] [FromBody] ReplaceDecoRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<DecoViewModel> maybeDeco = await mediator.Send(new GetDecoById(id), cancellationToken);
|
||||
if (maybeDeco.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
int decoGroupId = maybeDeco.Map(d => d.DecoGroupId).IfNone(0);
|
||||
|
||||
Either<BaseError, UpdateDeco> commandOrError = request.ToCommand(decoGroupId, id);
|
||||
return await commandOrError.Match(
|
||||
Left: error => Task.FromResult(error.ToErrorResult()),
|
||||
Right: async command =>
|
||||
{
|
||||
Either<BaseError, Unit> result = await mediator.Send(command, cancellationToken);
|
||||
return await result.Match(
|
||||
Left: error => Task.FromResult(error.ToErrorResult()),
|
||||
Right: async _ =>
|
||||
{
|
||||
Option<DecoViewModel> refreshed = await mediator.Send(new GetDecoById(id), cancellationToken);
|
||||
return refreshed.Match(
|
||||
Some: vm => (IActionResult)new OkObjectResult(ProjectToResponseModel(vm)),
|
||||
None: () => ApiResults.NotFoundProblem());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private static DecoGroupResponseModel ProjectToResponseModel(DecoGroupViewModel vm) =>
|
||||
new(vm.Id, vm.Name, vm.DecoCount);
|
||||
|
||||
private static DecoResponseModel ProjectToResponseModel(DecoViewModel vm) =>
|
||||
new(
|
||||
vm.Id,
|
||||
vm.DecoGroupId,
|
||||
vm.DecoGroupName,
|
||||
vm.Name,
|
||||
vm.WatermarkMode,
|
||||
vm.Watermarks.Map(w => w.Id).ToList(),
|
||||
vm.UseWatermarkDuringFiller,
|
||||
vm.GraphicsElementsMode,
|
||||
vm.GraphicsElements.Map(g => g.Id).ToList(),
|
||||
vm.UseGraphicsElementsDuringFiller,
|
||||
vm.BreakContentMode,
|
||||
vm.BreakContent.Map(ProjectToResponseModel).ToList(),
|
||||
vm.DefaultFillerMode,
|
||||
vm.DefaultFillerCollectionType,
|
||||
vm.DefaultFillerCollection?.Id,
|
||||
vm.DefaultFillerMediaItem?.MediaItemId,
|
||||
vm.DefaultFillerMultiCollection?.Id,
|
||||
vm.DefaultFillerSmartCollection?.Id,
|
||||
vm.DefaultFillerCollection?.Name
|
||||
?? vm.DefaultFillerMediaItem?.Name
|
||||
?? vm.DefaultFillerMultiCollection?.Name
|
||||
?? vm.DefaultFillerSmartCollection?.Name,
|
||||
vm.DefaultFillerTrimToFit,
|
||||
vm.DeadAirFallbackMode,
|
||||
vm.DeadAirFallbackCollectionType,
|
||||
vm.DeadAirFallbackCollection?.Id,
|
||||
vm.DeadAirFallbackMediaItem?.MediaItemId,
|
||||
vm.DeadAirFallbackMultiCollection?.Id,
|
||||
vm.DeadAirFallbackSmartCollection?.Id,
|
||||
vm.DeadAirFallbackCollection?.Name
|
||||
?? vm.DeadAirFallbackMediaItem?.Name
|
||||
?? vm.DeadAirFallbackMultiCollection?.Name
|
||||
?? vm.DeadAirFallbackSmartCollection?.Name);
|
||||
|
||||
private static DecoBreakContentResponseModel ProjectToResponseModel(DecoBreakContentViewModel vm) =>
|
||||
new(
|
||||
vm.Id,
|
||||
vm.CollectionType,
|
||||
vm.Collection?.Id,
|
||||
vm.MediaItem?.MediaItemId,
|
||||
vm.MultiCollection?.Id,
|
||||
vm.SmartCollection?.Id,
|
||||
vm.Playlist?.Id,
|
||||
vm.Playlist?.PlaylistGroupId,
|
||||
vm.Collection?.Name
|
||||
?? vm.MediaItem?.Name
|
||||
?? vm.MultiCollection?.Name
|
||||
?? vm.SmartCollection?.Name
|
||||
?? vm.Playlist?.Name,
|
||||
vm.Placement);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using ErsatzTV.Application.MediaCollections;
|
||||
using ErsatzTV.Core.Api.MediaCollections;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api;
|
||||
|
||||
[ApiController]
|
||||
public class PlaylistController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
[HttpGet("/api/playlists/groups", Name = "GetPlaylistGroups")]
|
||||
[Tags("Playlists")]
|
||||
[EndpointSummary("Get all playlist groups")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<PlaylistGroupResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<PlaylistGroupResponseModel>> GetGroups(CancellationToken cancellationToken)
|
||||
{
|
||||
List<PlaylistGroupViewModel> groups = await mediator.Send(new GetAllPlaylistGroups(), cancellationToken);
|
||||
return groups.Map(g => new PlaylistGroupResponseModel(g.Id, g.Name, g.PlaylistCount, g.IsSystem)).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/playlists", Name = "GetPlaylists")]
|
||||
[Tags("Playlists")]
|
||||
[EndpointSummary("Get playlists in a playlist group")]
|
||||
[EndpointDescription("Returns the playlists in the given playlist group.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<PlaylistResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<PlaylistResponseModel>> GetAll(
|
||||
[FromQuery] int playlistGroupId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
List<PlaylistViewModel> playlists =
|
||||
await mediator.Send(new GetPlaylistsByPlaylistGroupId(playlistGroupId), cancellationToken);
|
||||
return playlists.Map(p => new PlaylistResponseModel(p.Id, p.PlaylistGroupId, p.Name, p.IsSystem)).ToList();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using ErsatzTV.Application.Playouts;
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Controllers.Api.Requests;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.Playouts;
|
||||
@@ -190,6 +191,49 @@ public class PlayoutController(IMediator mediator) : ControllerBase
|
||||
_ => BaseError.New("[ScheduleFile] is only valid for Sequential, Scripted, or ExternalJson playouts")
|
||||
};
|
||||
|
||||
[HttpPut("/api/playouts/{id:int}/deco")]
|
||||
[Tags("Playouts")]
|
||||
[EndpointSummary("Set (or clear) a playout's default deco")]
|
||||
[EndpointDescription("Assigns the default deco for a block playout. Send a null decoId to clear it.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(PlayoutResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> UpdateDefaultDeco(
|
||||
int id,
|
||||
[Required] [FromBody] UpdateDefaultDecoRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
|
||||
if (maybePlayout.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
if (request.DecoId is { } decoId)
|
||||
{
|
||||
Option<DecoViewModel> maybeDeco = await mediator.Send(new GetDecoById(decoId), cancellationToken);
|
||||
if (maybeDeco.IsNone)
|
||||
{
|
||||
return BaseError.New("Deco does not exist").ToErrorResult();
|
||||
}
|
||||
}
|
||||
|
||||
Option<BaseError> result = await mediator.Send(request.ToCommand(id), cancellationToken);
|
||||
if (result.IsSome)
|
||||
{
|
||||
foreach (BaseError error in result)
|
||||
{
|
||||
return error.ToErrorResult();
|
||||
}
|
||||
}
|
||||
|
||||
Option<PlayoutNameViewModel> refreshed = await mediator.Send(new GetPlayoutById(id), cancellationToken);
|
||||
return refreshed.Match(
|
||||
Some: vm => (IActionResult)new OkObjectResult(ToResponse(vm)),
|
||||
None: () => ApiResults.NotFoundProblem());
|
||||
}
|
||||
|
||||
[HttpPost("/api/playouts/reset-all", Name = "ResetAllPlayouts")]
|
||||
[Tags("Playouts")]
|
||||
[EndpointSummary("Reset all playouts")]
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CreateDecoGroupRequest(string Name)
|
||||
{
|
||||
public CreateDecoGroup ToCommand() => new(Name);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CreateDecoRequest(int DecoGroupId, string Name)
|
||||
{
|
||||
public CreateDeco ToCommand() => new(DecoGroupId, Name);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record DecoBreakContentRequest(
|
||||
int Id,
|
||||
CollectionType CollectionType,
|
||||
int? CollectionId,
|
||||
int? MediaItemId,
|
||||
int? MultiCollectionId,
|
||||
int? SmartCollectionId,
|
||||
int? PlaylistId,
|
||||
DecoBreakPlacement Placement)
|
||||
{
|
||||
public UpdateDecoBreakContent ToUpdateItem() =>
|
||||
new(Id, CollectionType, CollectionId, MediaItemId, MultiCollectionId, SmartCollectionId, PlaylistId, Placement);
|
||||
}
|
||||
|
||||
public record ReplaceDecoRequest(
|
||||
string Name,
|
||||
DecoMode WatermarkMode,
|
||||
List<int> WatermarkIds,
|
||||
bool UseWatermarkDuringFiller,
|
||||
DecoMode GraphicsElementsMode,
|
||||
List<int> GraphicsElementIds,
|
||||
bool UseGraphicsElementsDuringFiller,
|
||||
DecoMode BreakContentMode,
|
||||
List<DecoBreakContentRequest> BreakContent,
|
||||
DecoMode DefaultFillerMode,
|
||||
CollectionType DefaultFillerCollectionType,
|
||||
int? DefaultFillerCollectionId,
|
||||
int? DefaultFillerMediaItemId,
|
||||
int? DefaultFillerMultiCollectionId,
|
||||
int? DefaultFillerSmartCollectionId,
|
||||
bool DefaultFillerTrimToFit,
|
||||
DecoMode DeadAirFallbackMode,
|
||||
CollectionType DeadAirFallbackCollectionType,
|
||||
int? DeadAirFallbackCollectionId,
|
||||
int? DeadAirFallbackMediaItemId,
|
||||
int? DeadAirFallbackMultiCollectionId,
|
||||
int? DeadAirFallbackSmartCollectionId)
|
||||
{
|
||||
public Either<BaseError, UpdateDeco> ToCommand(int decoGroupId, int decoId)
|
||||
{
|
||||
// Merge is only valid for the watermark and graphics-element sections; the handler treats
|
||||
// Merge on the other sections as "not overridden" (silently ignored), so reject it here.
|
||||
if (BreakContentMode is DecoMode.Merge)
|
||||
{
|
||||
return BaseError.New("[BreakContentMode] does not support Merge; use Inherit, Disable, or Override");
|
||||
}
|
||||
|
||||
if (DefaultFillerMode is DecoMode.Merge)
|
||||
{
|
||||
return BaseError.New("[DefaultFillerMode] does not support Merge; use Inherit, Disable, or Override");
|
||||
}
|
||||
|
||||
if (DeadAirFallbackMode is DecoMode.Merge)
|
||||
{
|
||||
return BaseError.New("[DeadAirFallbackMode] does not support Merge; use Inherit, Disable, or Override");
|
||||
}
|
||||
|
||||
return new UpdateDeco(
|
||||
decoId,
|
||||
decoGroupId,
|
||||
Name,
|
||||
WatermarkMode,
|
||||
WatermarkIds ?? [],
|
||||
UseWatermarkDuringFiller,
|
||||
GraphicsElementsMode,
|
||||
GraphicsElementIds ?? [],
|
||||
UseGraphicsElementsDuringFiller,
|
||||
BreakContentMode,
|
||||
(BreakContent ?? []).Select(bc => bc.ToUpdateItem()).ToList(),
|
||||
DefaultFillerMode,
|
||||
DefaultFillerCollectionType,
|
||||
DefaultFillerCollectionId,
|
||||
DefaultFillerMediaItemId,
|
||||
DefaultFillerMultiCollectionId,
|
||||
DefaultFillerSmartCollectionId,
|
||||
DefaultFillerTrimToFit,
|
||||
DeadAirFallbackMode,
|
||||
DeadAirFallbackCollectionType,
|
||||
DeadAirFallbackCollectionId,
|
||||
DeadAirFallbackMediaItemId,
|
||||
DeadAirFallbackMultiCollectionId,
|
||||
DeadAirFallbackSmartCollectionId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record UpdateDefaultDecoRequest(int? DecoId)
|
||||
{
|
||||
public UpdateDefaultDeco ToCommand(int playoutId) => new(playoutId, DecoId);
|
||||
}
|
||||
@@ -102,4 +102,36 @@ public class SearchController(IMediator mediator) : ControllerBase
|
||||
cancellationToken);
|
||||
return results.Map(c => new SchedulingPickerOptionResponseModel(c.Id, c.Name)).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/search/artists", Name = "SearchArtists")]
|
||||
[Tags("Search")]
|
||||
[EndpointSummary("Search artists by name")]
|
||||
[EndpointDescription("Returns matching artists as {id, name} options for scheduling editors.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<SchedulingPickerOptionResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<SchedulingPickerOptionResponseModel>> SearchArtists(
|
||||
[FromQuery] string query = "",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<NamedMediaItemViewModel> results = await mediator.Send(
|
||||
new SearchArtists(query ?? string.Empty),
|
||||
cancellationToken);
|
||||
return results.Map(a => new SchedulingPickerOptionResponseModel(a.MediaItemId, a.Name)).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/search/multi-collections", Name = "SearchMultiCollections")]
|
||||
[Tags("Search")]
|
||||
[EndpointSummary("Search multi collections by name")]
|
||||
[EndpointDescription("Returns matching multi collections as {id, name} options for scheduling editors.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<SchedulingPickerOptionResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<SchedulingPickerOptionResponseModel>> SearchMultiCollections(
|
||||
[FromQuery] string query = "",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<MultiCollectionViewModel> results = await mediator.Send(
|
||||
new SearchMultiCollections(query ?? string.Empty),
|
||||
cancellationToken);
|
||||
return results.Map(c => new SchedulingPickerOptionResponseModel(c.Id, c.Name)).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,7 @@ import {
|
||||
ArrowDownWideNarrow,
|
||||
Bell,
|
||||
Boxes,
|
||||
Palette,
|
||||
CalendarClock,
|
||||
CalendarDays,
|
||||
Cast,
|
||||
@@ -73,6 +74,7 @@ import { TrashScreen } from './screens/TrashScreen';
|
||||
import { TroubleshootingScreen } from './screens/TroubleshootingScreen';
|
||||
import { WatermarksScreen } from './screens/WatermarksScreen';
|
||||
import { BlocksScreen } from './screens/BlocksScreen';
|
||||
import { DecosScreen } from './screens/DecosScreen';
|
||||
import { TemplatesScreen } from './screens/TemplatesScreen';
|
||||
import { navigateToPath } from './routing';
|
||||
import {
|
||||
@@ -155,6 +157,7 @@ type ScreenId =
|
||||
| 'schedules'
|
||||
| 'blocks'
|
||||
| 'templates'
|
||||
| 'decos'
|
||||
| 'playouts'
|
||||
| 'media'
|
||||
| 'search'
|
||||
@@ -282,6 +285,19 @@ const routes: ScreenRoute[] = [
|
||||
placeholder: 'Templates workspace',
|
||||
allowSubPaths: true
|
||||
},
|
||||
{
|
||||
// The editor lives at a sub-path (/app/decos/{id}); DecosScreen owns parsing the id suffix.
|
||||
id: 'decos',
|
||||
path: '/app/decos',
|
||||
label: 'Decos',
|
||||
title: 'Decos',
|
||||
kicker: 'Programming',
|
||||
description: 'Group decos and configure watermark, graphics, break content, and filler overrides.',
|
||||
icon: <Palette aria-hidden="true" size={16} />,
|
||||
primaryAction: 'New Group',
|
||||
placeholder: 'Decos workspace',
|
||||
allowSubPaths: true
|
||||
},
|
||||
{
|
||||
id: 'playouts',
|
||||
path: '/app/playouts',
|
||||
@@ -447,6 +463,7 @@ const primaryNavIds: ScreenId[] = [
|
||||
'schedules',
|
||||
'blocks',
|
||||
'templates',
|
||||
'decos',
|
||||
'playouts'
|
||||
];
|
||||
const mediaNavIds: ScreenId[] = [
|
||||
@@ -3419,6 +3436,10 @@ function ScreenContent({
|
||||
return <TemplatesScreen key={window.location.pathname} />;
|
||||
}
|
||||
|
||||
if (route.id === 'decos') {
|
||||
return <DecosScreen key={window.location.pathname} />;
|
||||
}
|
||||
|
||||
if (route.id === 'playouts') {
|
||||
return <PlayoutsScreen />;
|
||||
}
|
||||
|
||||
@@ -83,6 +83,14 @@ export function searchSmartCollections(query: string): Promise<SchedulingPickerO
|
||||
return searchOptions('/api/search/smart-collections', query);
|
||||
}
|
||||
|
||||
export function searchArtists(query: string): Promise<SchedulingPickerOption[]> {
|
||||
return searchOptions('/api/search/artists', query);
|
||||
}
|
||||
|
||||
export function searchMultiCollections(query: string): Promise<SchedulingPickerOption[]> {
|
||||
return searchOptions('/api/search/multi-collections', query);
|
||||
}
|
||||
|
||||
export function messageFromBlockError(error: unknown, fallback = 'Unable to load blocks'): string {
|
||||
if (error instanceof ApiError) {
|
||||
return error.detail ?? error.message;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createDeco,
|
||||
createDecoGroup,
|
||||
deleteDeco,
|
||||
deleteDecoGroup,
|
||||
getDeco,
|
||||
getDecoGroups,
|
||||
getDecos,
|
||||
replaceDeco,
|
||||
type ReplaceDecoRequest
|
||||
} from './decos';
|
||||
import { searchArtists, searchMultiCollections } from './blocks';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
function noContent(): Response {
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
const sampleReplace: ReplaceDecoRequest = {
|
||||
name: 'Movie Night',
|
||||
watermarkMode: 'Merge',
|
||||
watermarkIds: [1, 2],
|
||||
useWatermarkDuringFiller: false,
|
||||
graphicsElementsMode: 'Inherit',
|
||||
graphicsElementIds: [],
|
||||
useGraphicsElementsDuringFiller: false,
|
||||
breakContentMode: 'Override',
|
||||
breakContent: [
|
||||
{
|
||||
id: 0,
|
||||
collectionType: 'Playlist',
|
||||
collectionId: null,
|
||||
mediaItemId: null,
|
||||
multiCollectionId: null,
|
||||
smartCollectionId: null,
|
||||
playlistId: 9,
|
||||
placement: 'BlockStart'
|
||||
}
|
||||
],
|
||||
defaultFillerMode: 'Inherit',
|
||||
defaultFillerCollectionType: 'Collection',
|
||||
defaultFillerCollectionId: null,
|
||||
defaultFillerMediaItemId: null,
|
||||
defaultFillerMultiCollectionId: null,
|
||||
defaultFillerSmartCollectionId: null,
|
||||
defaultFillerTrimToFit: false,
|
||||
deadAirFallbackMode: 'Inherit',
|
||||
deadAirFallbackCollectionType: 'Collection',
|
||||
deadAirFallbackCollectionId: null,
|
||||
deadAirFallbackMediaItemId: null,
|
||||
deadAirFallbackMultiCollectionId: null,
|
||||
deadAirFallbackSmartCollectionId: null
|
||||
};
|
||||
|
||||
describe('decos api client', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('getDecoGroups fetches all deco groups', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([{ id: 1, name: 'Bumpers', decoCount: 0 }]));
|
||||
await expect(getDecoGroups()).resolves.toHaveLength(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos/groups', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('createDecoGroup POSTs to the groups route', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 5, name: 'Bumpers', decoCount: 0 }, 201));
|
||||
await createDecoGroup({ name: 'Bumpers' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos/groups', expect.objectContaining({ method: 'POST' }));
|
||||
});
|
||||
|
||||
it('deleteDecoGroup DELETEs the group route', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
|
||||
await deleteDecoGroup(3);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos/groups/3', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
|
||||
it('getDecos fetches the flat list', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
|
||||
await getDecos();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('getDeco fetches a single deco', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4 }));
|
||||
await getDeco(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos/4', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('createDeco POSTs to the decos route', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 8 }, 201));
|
||||
await createDeco({ decoGroupId: 2, name: 'Movie Night' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos', expect.objectContaining({ method: 'POST' }));
|
||||
});
|
||||
|
||||
it('deleteDeco DELETEs the deco route', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
|
||||
await deleteDeco(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos/4', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
|
||||
it('replaceDeco PUTs the full state', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4 }));
|
||||
await replaceDeco(4, sampleReplace);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/decos/4', expect.objectContaining({ method: 'PUT' }));
|
||||
const init = fetchMock.mock.calls[0][1];
|
||||
const sent = JSON.parse(String(init?.body));
|
||||
expect(sent.breakContent[0].playlistId).toBe(9);
|
||||
});
|
||||
|
||||
it('searchArtists and searchMultiCollections hit their picker routes', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockImplementation(() => Promise.resolve(jsonResponse([])));
|
||||
await searchArtists('bowie');
|
||||
await searchMultiCollections('mix');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/search/artists?query=bowie', expect.objectContaining({ method: 'GET' }));
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/search/multi-collections?query=mix',
|
||||
expect.objectContaining({ method: 'GET' })
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ApiError, request } from './client';
|
||||
import type { components } from './generated/v1';
|
||||
|
||||
export type DecoGroup = components['schemas']['DecoGroupResponseModel'];
|
||||
export type DecoListItem = components['schemas']['DecoListItemResponseModel'];
|
||||
export type Deco = components['schemas']['DecoResponseModel'];
|
||||
export type DecoBreakContent = components['schemas']['DecoBreakContentResponseModel'];
|
||||
export type CreateDecoGroupRequest = components['schemas']['CreateDecoGroupRequest'];
|
||||
export type CreateDecoRequest = components['schemas']['CreateDecoRequest'];
|
||||
export type ReplaceDecoRequest = components['schemas']['ReplaceDecoRequest'];
|
||||
export type DecoBreakContentRequest = components['schemas']['DecoBreakContentRequest'];
|
||||
|
||||
// Deco groups
|
||||
|
||||
export function getDecoGroups(): Promise<DecoGroup[]> {
|
||||
return request<DecoGroup[]>('/api/decos/groups');
|
||||
}
|
||||
|
||||
export function createDecoGroup(body: CreateDecoGroupRequest): Promise<DecoGroup> {
|
||||
return request<DecoGroup>('/api/decos/groups', { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function deleteDecoGroup(id: number): Promise<void> {
|
||||
return request<void>(`/api/decos/groups/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
// Decos
|
||||
|
||||
export function getDecos(): Promise<DecoListItem[]> {
|
||||
return request<DecoListItem[]>('/api/decos');
|
||||
}
|
||||
|
||||
export function getDeco(id: number): Promise<Deco> {
|
||||
return request<Deco>(`/api/decos/${id}`);
|
||||
}
|
||||
|
||||
export function createDeco(body: CreateDecoRequest): Promise<Deco> {
|
||||
return request<Deco>('/api/decos', { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function deleteDeco(id: number): Promise<void> {
|
||||
return request<void>(`/api/decos/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function replaceDeco(id: number, body: ReplaceDecoRequest): Promise<Deco> {
|
||||
return request<Deco>(`/api/decos/${id}`, { body, method: 'PUT' });
|
||||
}
|
||||
|
||||
export function messageFromDecoError(error: unknown, fallback = 'Unable to load decos'): string {
|
||||
if (error instanceof ApiError) {
|
||||
return error.detail ?? error.message;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
Vendored
+110
@@ -351,6 +351,13 @@ export interface components {
|
||||
};
|
||||
"CreateCollectionRequest": {
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateDecoGroupRequest": {
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateDecoRequest": {
|
||||
"decoGroupId": number;
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateFFmpegProfileRequest": {
|
||||
"name": null | string;
|
||||
@@ -447,6 +454,70 @@ export interface components {
|
||||
"opacityExpression": null | string;
|
||||
"zIndex": number;
|
||||
"placeWithinSourceContent": boolean;
|
||||
};
|
||||
"DecoBreakContentRequest": {
|
||||
"id": number;
|
||||
"collectionType": components["schemas"]["CollectionType"];
|
||||
"collectionId": null | number;
|
||||
"mediaItemId": null | number;
|
||||
"multiCollectionId": null | number;
|
||||
"smartCollectionId": null | number;
|
||||
"playlistId": null | number;
|
||||
"placement": components["schemas"]["DecoBreakPlacement"];
|
||||
};
|
||||
"DecoBreakContentResponseModel": {
|
||||
"id": number;
|
||||
"collectionType": components["schemas"]["CollectionType"];
|
||||
"collectionId": null | number;
|
||||
"mediaItemId": null | number;
|
||||
"multiCollectionId": null | number;
|
||||
"smartCollectionId": null | number;
|
||||
"playlistId": null | number;
|
||||
"playlistGroupId": null | number;
|
||||
"selectionName": null | string;
|
||||
"placement": components["schemas"]["DecoBreakPlacement"];
|
||||
};
|
||||
"DecoBreakPlacement": "BlockStart" | "BlockFinish" | "BetweenBlockItems" | "ChapterMarkers";
|
||||
"DecoGroupResponseModel": {
|
||||
"id": number;
|
||||
"name": string;
|
||||
"decoCount": number;
|
||||
};
|
||||
"DecoListItemResponseModel": {
|
||||
"id": number;
|
||||
"decoGroupId": number;
|
||||
"decoGroupName": string;
|
||||
"name": string;
|
||||
};
|
||||
"DecoMode": "Inherit" | "Disable" | "Override" | "Merge";
|
||||
"DecoResponseModel": {
|
||||
"id": number;
|
||||
"decoGroupId": number;
|
||||
"decoGroupName": string;
|
||||
"name": string;
|
||||
"watermarkMode": components["schemas"]["DecoMode"];
|
||||
"watermarkIds": Array<number>;
|
||||
"useWatermarkDuringFiller": boolean;
|
||||
"graphicsElementsMode": components["schemas"]["DecoMode"];
|
||||
"graphicsElementIds": Array<number>;
|
||||
"useGraphicsElementsDuringFiller": boolean;
|
||||
"breakContentMode": components["schemas"]["DecoMode"];
|
||||
"breakContent": Array<components["schemas"]["DecoBreakContentResponseModel"]>;
|
||||
"defaultFillerMode": components["schemas"]["DecoMode"];
|
||||
"defaultFillerCollectionType": components["schemas"]["CollectionType"];
|
||||
"defaultFillerCollectionId": null | number;
|
||||
"defaultFillerMediaItemId": null | number;
|
||||
"defaultFillerMultiCollectionId": null | number;
|
||||
"defaultFillerSmartCollectionId": null | number;
|
||||
"defaultFillerSelectionName": null | string;
|
||||
"defaultFillerTrimToFit": boolean;
|
||||
"deadAirFallbackMode": components["schemas"]["DecoMode"];
|
||||
"deadAirFallbackCollectionType": components["schemas"]["CollectionType"];
|
||||
"deadAirFallbackCollectionId": null | number;
|
||||
"deadAirFallbackMediaItemId": null | number;
|
||||
"deadAirFallbackMultiCollectionId": null | number;
|
||||
"deadAirFallbackSmartCollectionId": null | number;
|
||||
"deadAirFallbackSelectionName": null | string;
|
||||
};
|
||||
"DeleteMediaItemsRequest": {
|
||||
"ids": null | Array<number>;
|
||||
@@ -693,6 +764,18 @@ export interface components {
|
||||
"page": Array<components["schemas"]["TraktListResponseModel"]>;
|
||||
};
|
||||
"PlaybackOrder": "None" | "Chronological" | "Random" | "Shuffle" | "ShuffleInOrder" | "MultiEpisodeShuffle" | "SeasonEpisode" | "RandomRotation" | "Marathon";
|
||||
"PlaylistGroupResponseModel": {
|
||||
"id": number;
|
||||
"name": string;
|
||||
"playlistCount": number;
|
||||
"isSystem": boolean;
|
||||
};
|
||||
"PlaylistResponseModel": {
|
||||
"id": number;
|
||||
"playlistGroupId": number;
|
||||
"name": string;
|
||||
"isSystem": boolean;
|
||||
};
|
||||
"PlaylistViewModel": {
|
||||
"id": number;
|
||||
"playlistGroupId": number;
|
||||
@@ -802,6 +885,30 @@ export interface components {
|
||||
"minutes": number;
|
||||
"stopScheduling": components["schemas"]["BlockStopScheduling"];
|
||||
"items": null | Array<components["schemas"]["BlockItemRequest"]>;
|
||||
};
|
||||
"ReplaceDecoRequest": {
|
||||
"name": null | string;
|
||||
"watermarkMode": components["schemas"]["DecoMode"];
|
||||
"watermarkIds": null | Array<number>;
|
||||
"useWatermarkDuringFiller": boolean;
|
||||
"graphicsElementsMode": components["schemas"]["DecoMode"];
|
||||
"graphicsElementIds": null | Array<number>;
|
||||
"useGraphicsElementsDuringFiller": boolean;
|
||||
"breakContentMode": components["schemas"]["DecoMode"];
|
||||
"breakContent": null | Array<components["schemas"]["DecoBreakContentRequest"]>;
|
||||
"defaultFillerMode": components["schemas"]["DecoMode"];
|
||||
"defaultFillerCollectionType": components["schemas"]["CollectionType"];
|
||||
"defaultFillerCollectionId": null | number;
|
||||
"defaultFillerMediaItemId": null | number;
|
||||
"defaultFillerMultiCollectionId": null | number;
|
||||
"defaultFillerSmartCollectionId": null | number;
|
||||
"defaultFillerTrimToFit": boolean;
|
||||
"deadAirFallbackMode": components["schemas"]["DecoMode"];
|
||||
"deadAirFallbackCollectionType": components["schemas"]["CollectionType"];
|
||||
"deadAirFallbackCollectionId": null | number;
|
||||
"deadAirFallbackMediaItemId": null | number;
|
||||
"deadAirFallbackMultiCollectionId": null | number;
|
||||
"deadAirFallbackSmartCollectionId": null | number;
|
||||
};
|
||||
"ReplaceScheduleItemsRequest": {
|
||||
"items": null | Array<components["schemas"]["ScheduleItemRequest"]>;
|
||||
@@ -1026,6 +1133,9 @@ export interface components {
|
||||
"UpdateCollectionRequest": {
|
||||
"name": null | string;
|
||||
"useCustomPlaybackOrder": null | boolean;
|
||||
};
|
||||
"UpdateDefaultDecoRequest": {
|
||||
"decoId": null | number;
|
||||
};
|
||||
"UpdateFFmpegProfileRequest": {
|
||||
"name": null | string;
|
||||
|
||||
@@ -6,6 +6,7 @@ export * from './channelTemplates';
|
||||
export * from './client';
|
||||
export * from './collections';
|
||||
export * from './dashboard';
|
||||
export * from './decos';
|
||||
export * from './ffmpegProfiles';
|
||||
export * from './fillerPresets';
|
||||
export * from './guide';
|
||||
@@ -15,6 +16,7 @@ export * from './logs';
|
||||
export * from './maintenance';
|
||||
export * from './mediaItems';
|
||||
export * from './pickers';
|
||||
export * from './playlists';
|
||||
export * from './playouts';
|
||||
export * from './schedules';
|
||||
export * from './search';
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getPlaylistGroups, getPlaylists } from './playlists';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
describe('playlists api client', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('getPlaylistGroups fetches all playlist groups', async () => {
|
||||
const fetchMock = vi
|
||||
.spyOn(window, 'fetch')
|
||||
.mockResolvedValue(jsonResponse([{ id: 1, name: 'Idents', playlistCount: 2, isSystem: false }]));
|
||||
await expect(getPlaylistGroups()).resolves.toHaveLength(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/playlists/groups', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('getPlaylists filters by playlist group id', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
|
||||
await getPlaylists(3);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/playlists?playlistGroupId=3', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { ApiError, request } from './client';
|
||||
import type { components } from './generated/v1';
|
||||
|
||||
export type PlaylistGroup = components['schemas']['PlaylistGroupResponseModel'];
|
||||
export type Playlist = components['schemas']['PlaylistResponseModel'];
|
||||
|
||||
export function getPlaylistGroups(): Promise<PlaylistGroup[]> {
|
||||
return request<PlaylistGroup[]>('/api/playlists/groups');
|
||||
}
|
||||
|
||||
export function getPlaylists(playlistGroupId: number): Promise<Playlist[]> {
|
||||
return request<Playlist[]>(`/api/playlists?playlistGroupId=${playlistGroupId}`);
|
||||
}
|
||||
|
||||
export function messageFromPlaylistError(error: unknown, fallback = 'Unable to load playlists'): string {
|
||||
if (error instanceof ApiError) {
|
||||
return error.detail ?? error.message;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { DecosScreen } from './DecosScreen';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
const groups = [{ id: 2, name: 'Prime', decoCount: 1 }];
|
||||
const decoList = [{ id: 4, decoGroupId: 2, decoGroupName: 'Prime', name: 'Movie Night' }];
|
||||
const watermarks = [{ id: 1, name: 'Logo' }];
|
||||
const playlistGroups = [{ id: 3, name: 'Idents', playlistCount: 1, isSystem: false }];
|
||||
const playlists = [{ id: 9, playlistGroupId: 3, name: 'Idents Playlist', isSystem: false }];
|
||||
|
||||
function fullDeco(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 4,
|
||||
decoGroupId: 2,
|
||||
decoGroupName: 'Prime',
|
||||
name: 'Movie Night',
|
||||
watermarkMode: 'Override',
|
||||
watermarkIds: [1],
|
||||
useWatermarkDuringFiller: true,
|
||||
graphicsElementsMode: 'Inherit',
|
||||
graphicsElementIds: [],
|
||||
useGraphicsElementsDuringFiller: false,
|
||||
breakContentMode: 'Override',
|
||||
breakContent: [
|
||||
{
|
||||
id: 7,
|
||||
collectionType: 'Playlist',
|
||||
collectionId: null,
|
||||
mediaItemId: null,
|
||||
multiCollectionId: null,
|
||||
smartCollectionId: null,
|
||||
playlistId: 9,
|
||||
playlistGroupId: 3,
|
||||
selectionName: 'Idents Playlist',
|
||||
placement: 'BlockStart'
|
||||
}
|
||||
],
|
||||
defaultFillerMode: 'Override',
|
||||
defaultFillerCollectionType: 'Collection',
|
||||
defaultFillerCollectionId: 5,
|
||||
defaultFillerMediaItemId: null,
|
||||
defaultFillerMultiCollectionId: null,
|
||||
defaultFillerSmartCollectionId: null,
|
||||
defaultFillerSelectionName: 'Shorts',
|
||||
defaultFillerTrimToFit: true,
|
||||
deadAirFallbackMode: 'Inherit',
|
||||
deadAirFallbackCollectionType: 'Collection',
|
||||
deadAirFallbackCollectionId: null,
|
||||
deadAirFallbackMediaItemId: null,
|
||||
deadAirFallbackMultiCollectionId: null,
|
||||
deadAirFallbackSmartCollectionId: null,
|
||||
deadAirFallbackSelectionName: null,
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
interface MockOptions {
|
||||
deco?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function mockApi(options: MockOptions = {}) {
|
||||
const deco = fullDeco(options.deco);
|
||||
|
||||
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input.toString();
|
||||
const method = (init?.method ?? 'GET').toUpperCase();
|
||||
|
||||
if (url === '/api/decos/groups' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(groups));
|
||||
}
|
||||
if (url === '/api/decos' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(decoList));
|
||||
}
|
||||
if (url === '/api/decos/4' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(deco));
|
||||
}
|
||||
if (url === '/api/decos/4' && method === 'PUT') {
|
||||
return Promise.resolve(jsonResponse(deco));
|
||||
}
|
||||
if (url === '/api/watermarks' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(watermarks));
|
||||
}
|
||||
if (url === '/api/graphics-elements' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]));
|
||||
}
|
||||
if (url === '/api/playlists/groups' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(playlistGroups));
|
||||
}
|
||||
if (url.startsWith('/api/playlists?') && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(playlists));
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(null, { status: 204 }));
|
||||
});
|
||||
}
|
||||
|
||||
describe('DecosScreen', () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
window.history.pushState({}, '', '/app/decos');
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
window.history.pushState({}, '', '/app/decos');
|
||||
});
|
||||
|
||||
it('renders deco groups and their decos', async () => {
|
||||
mockApi();
|
||||
render(<DecosScreen />);
|
||||
|
||||
expect(await screen.findByText('Prime')).toBeInTheDocument();
|
||||
expect(screen.getByText('Movie Night')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('loads the editor with all six sections from a full deco', async () => {
|
||||
window.history.pushState({}, '', '/app/decos/4');
|
||||
mockApi();
|
||||
render(<DecosScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Movie Night')).toBeInTheDocument());
|
||||
|
||||
// Each of the six sections renders its (uniquely-labelled) mode row.
|
||||
expect(screen.getByText('Watermark mode')).toBeInTheDocument();
|
||||
expect(screen.getByText('Graphics elements mode')).toBeInTheDocument();
|
||||
expect(screen.getByText('Break content mode')).toBeInTheDocument();
|
||||
expect(screen.getByText('Default filler mode')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dead air fallback mode')).toBeInTheDocument();
|
||||
|
||||
// Break content (Override) renders its row with the playlist selection and placement.
|
||||
expect(screen.getByRole('cell', { name: 'Idents Playlist' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('cell', { name: 'Block Start' })).toBeInTheDocument();
|
||||
|
||||
// Default filler (Override) exposes its picker with the current selection.
|
||||
expect(screen.getByText('Shorts')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reveals section detail only when the mode is Override', async () => {
|
||||
window.history.pushState({}, '', '/app/decos/4');
|
||||
mockApi();
|
||||
const { unmount } = render(<DecosScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Movie Night')).toBeInTheDocument());
|
||||
|
||||
// Break content Override -> Add button shown; default filler Override -> Trim to fit shown.
|
||||
expect(screen.getByRole('button', { name: /Add break content/ })).toBeInTheDocument();
|
||||
expect(screen.getByText('Trim to fit')).toBeInTheDocument();
|
||||
// Dead air fallback is Inherit, so only the default-filler collection-type row exists.
|
||||
expect(screen.getAllByText('Collection type')).toHaveLength(1);
|
||||
|
||||
unmount();
|
||||
|
||||
// With break content Disable + default filler Inherit, neither detail renders.
|
||||
mockApi({ deco: { breakContentMode: 'Disable', defaultFillerMode: 'Inherit' } });
|
||||
render(<DecosScreen />);
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Movie Night')).toBeInTheDocument());
|
||||
expect(screen.queryByRole('button', { name: /Add break content/ })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Trim to fit')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves the full deco state via PUT', async () => {
|
||||
window.history.pushState({}, '', '/app/decos/4');
|
||||
const fetchMock = mockApi();
|
||||
render(<DecosScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Movie Night')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save deco/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
const call = fetchMock.mock.calls.find(([u, init]) => u === '/api/decos/4' && init?.method === 'PUT');
|
||||
expect(call).toBeTruthy();
|
||||
});
|
||||
|
||||
const putCall = fetchMock.mock.calls.find(([u, init]) => u === '/api/decos/4' && init?.method === 'PUT');
|
||||
const sent = JSON.parse(String(putCall?.[1]?.body));
|
||||
expect(sent.name).toBe('Movie Night');
|
||||
expect(sent.watermarkMode).toBe('Override');
|
||||
expect(sent.watermarkIds).toEqual([1]);
|
||||
expect(sent.graphicsElementsMode).toBe('Inherit');
|
||||
expect(sent.breakContentMode).toBe('Override');
|
||||
expect(sent.breakContent).toHaveLength(1);
|
||||
expect(sent.breakContent[0].playlistId).toBe(9);
|
||||
expect(sent.breakContent[0].placement).toBe('BlockStart');
|
||||
expect(sent.defaultFillerMode).toBe('Override');
|
||||
expect(sent.defaultFillerCollectionId).toBe(5);
|
||||
expect(sent.defaultFillerTrimToFit).toBe(true);
|
||||
expect(sent.deadAirFallbackMode).toBe('Inherit');
|
||||
});
|
||||
|
||||
it('assigns a distinct placement to each added break content row', async () => {
|
||||
window.history.pushState({}, '', '/app/decos/4');
|
||||
mockApi();
|
||||
render(<DecosScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Movie Night')).toBeInTheDocument());
|
||||
|
||||
// Existing row uses Block Start; adding one takes the next unused placement (Block Finish).
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add break content/ }));
|
||||
expect(await screen.findByRole('cell', { name: 'Block Finish' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('blocks save when two break content items share a placement', async () => {
|
||||
window.history.pushState({}, '', '/app/decos/4');
|
||||
mockApi({
|
||||
deco: {
|
||||
breakContent: [
|
||||
{
|
||||
id: 7,
|
||||
collectionType: 'Playlist',
|
||||
collectionId: null,
|
||||
mediaItemId: null,
|
||||
multiCollectionId: null,
|
||||
smartCollectionId: null,
|
||||
playlistId: 9,
|
||||
playlistGroupId: 3,
|
||||
selectionName: 'Idents Playlist',
|
||||
placement: 'BlockStart'
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
collectionType: 'Playlist',
|
||||
collectionId: null,
|
||||
mediaItemId: null,
|
||||
multiCollectionId: null,
|
||||
smartCollectionId: null,
|
||||
playlistId: 9,
|
||||
playlistGroupId: 3,
|
||||
selectionName: 'Idents Playlist',
|
||||
placement: 'BlockStart'
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
render(<DecosScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Movie Night')).toBeInTheDocument());
|
||||
|
||||
expect(await screen.findByText(/placement may be used only once/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Save deco/ })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user