Clears the still-live findings from #172 (verified against main; #2/#4/#7 and the auth/search/Trakt tail were already deliberate-documented or fixed since 2026-07-07). - Null/empty Name → 500 (10 create/replace handlers). Block/Template/DecoTemplate/Deco Create+Replace/Update + UpdateFFmpegProfile did `request.Name.Length > 50` on a client-nullable string → unhandled NullReferenceException → HTTP 500 (no global exception filter). Now `string.IsNullOrWhiteSpace(request.Name) || .Length > 50` → 422; also rejects empty/whitespace names, matching the group-create handlers' NotEmpty behavior. CreatePlaylist coalesces null→"" at the DTO so it was an empty-name persist, not a 500; guarded the same way. - ReplaceTemplateItems overlap validation iterated with an `item == otherItem` record value-equality skip, so two exact-duplicate items were value-equal and bypassed the intersection check (both persisted). Now index-based (i != j) so duplicates register as a self-intersection and are rejected 422. - Trimmed the unreachable 404 ProducesResponseType from POST /api/blocks/groups and POST /api/templates/groups (a create has no parent lookup that can 404); v1.json regenerated. - Regression tests: all 10 name-guard paths + the duplicate-items path (19 cases). - Docs: decisions.md entry + api-conventions.md §3b null-safe-validation bullet. fixes #172 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
306 lines
13 KiB
C#
306 lines
13 KiB
C#
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 BlockController(IMediator mediator) : ControllerBase
|
|
{
|
|
[HttpGet("/api/v1/blocks/groups", Name = "GetBlockGroups")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Get all block groups")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(List<BlockGroupResponseModel>), StatusCodes.Status200OK)]
|
|
public async Task<List<BlockGroupResponseModel>> GetGroups(CancellationToken cancellationToken)
|
|
{
|
|
List<BlockGroupViewModel> groups = await mediator.Send(new GetAllBlockGroups(), cancellationToken);
|
|
return groups.Map(ProjectToResponseModel).ToList();
|
|
}
|
|
|
|
[HttpPost("/api/v1/blocks/groups")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Create a block group")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(BlockGroupResponseModel), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> CreateGroup(
|
|
[Required][FromBody] CreateBlockGroupRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, BlockGroupViewModel> result =
|
|
await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.ToCreatedResult(
|
|
vm => $"/api/v1/blocks/groups/{vm.Id}",
|
|
vm => ProjectToResponseModel(vm));
|
|
}
|
|
|
|
[HttpDelete("/api/v1/blocks/groups/{id:int}")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Delete a block group")]
|
|
[EndpointDescription(
|
|
"Deletes the block group. The database cascade removes every block (and its items) in the group.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> DeleteGroup(int id, CancellationToken cancellationToken)
|
|
{
|
|
List<BlockGroupViewModel> groups = await mediator.Send(new GetAllBlockGroups(), cancellationToken);
|
|
if (groups.All(g => g.Id != id))
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
Option<BaseError> result = await mediator.Send(new DeleteBlockGroup(id), cancellationToken);
|
|
return result.Match<IActionResult>(
|
|
Some: error => error.ToErrorResult(),
|
|
None: () => new NoContentResult());
|
|
}
|
|
|
|
[HttpGet("/api/v1/blocks")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Get all blocks")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(List<BlockResponseModel>), StatusCodes.Status200OK)]
|
|
public async Task<List<BlockResponseModel>> GetAll(CancellationToken cancellationToken)
|
|
{
|
|
List<BlockViewModel> blocks = await mediator.Send(new GetAllBlocks(), cancellationToken);
|
|
return blocks.Map(ProjectToResponseModel).ToList();
|
|
}
|
|
|
|
[HttpGet("/api/v1/blocks/{id:int}", Name = "GetBlockById")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Get a block by id")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(BlockResponseModel), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
|
|
{
|
|
Option<BlockViewModel> result = await mediator.Send(new GetBlockById(id), cancellationToken);
|
|
return result.Map(ProjectToResponseModel).ToGetResult();
|
|
}
|
|
|
|
[HttpPost("/api/v1/blocks")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Create a block")]
|
|
[EndpointDescription("Creates an empty block in the given block group. The block defaults to 30 minutes.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(BlockResponseModel), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Create(
|
|
[Required][FromBody] CreateBlockRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, BlockViewModel> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.ToCreatedResult(
|
|
vm => $"/api/v1/blocks/{vm.Id}",
|
|
vm => ProjectToResponseModel(vm));
|
|
}
|
|
|
|
[HttpDelete("/api/v1/blocks/{id:int}")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Delete a block")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
|
|
{
|
|
Option<BlockViewModel> existing = await mediator.Send(new GetBlockById(id), cancellationToken);
|
|
if (existing.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
Option<BaseError> result = await mediator.Send(new DeleteBlock(id), cancellationToken);
|
|
return result.Match<IActionResult>(
|
|
Some: error => error.ToErrorResult(),
|
|
None: () => new NoContentResult());
|
|
}
|
|
|
|
[HttpGet("/api/v1/blocks/{id:int}/items")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Get block items")]
|
|
[EndpointDescription(
|
|
"Returns the block's items and a strong ETag of the block's version. Pass that ETag back as " +
|
|
"If-Match on the replace (PUT) to detect a concurrent edit (issue #253).")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(List<BlockItemResponseModel>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> GetItems(int id, CancellationToken cancellationToken)
|
|
{
|
|
Option<BlockViewModel> block = await mediator.Send(new GetBlockById(id), cancellationToken);
|
|
if (block.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
// The items GET returns children, not the root, so read the block's version for the ETag.
|
|
ConcurrencyHeaders.SetETag(Response, block.Map(b => b.Version).IfNone(0));
|
|
|
|
List<BlockItemViewModel> items = await mediator.Send(new GetBlockItems(id), cancellationToken);
|
|
return new OkObjectResult(items.OrderBy(i => i.Index).Map(ProjectToResponseModel).ToList());
|
|
}
|
|
|
|
[HttpPut("/api/v1/blocks/{id:int}")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Replace a block and its items")]
|
|
[EndpointDescription(
|
|
"Replaces the block's name/minutes/stop-scheduling and its full item list. Item indexes are assigned " +
|
|
"from the array order. Minutes must be greater than zero, divisible by 5, and at most 24 hours. " +
|
|
"Send the ETag from the items GET as If-Match to reject a stale overwrite with 412 (issue #253); " +
|
|
"a successful response carries the new ETag.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(BlockWithItemsResponseModel), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Replace(
|
|
int id,
|
|
[Required][FromBody] ReplaceBlockRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
|
|
if (ifMatch.Kind is IfMatchKind.Malformed)
|
|
{
|
|
return new BadRequestObjectResult(
|
|
new ProblemDetails
|
|
{
|
|
Status = StatusCodes.Status400BadRequest,
|
|
Title = "Invalid If-Match header",
|
|
Detail = "If-Match must be a strong ETag of the resource version (e.g. \"3\") or \"*\"."
|
|
});
|
|
}
|
|
|
|
Option<BlockViewModel> maybeBlock = await mediator.Send(new GetBlockById(id), cancellationToken);
|
|
if (maybeBlock.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
int groupId = maybeBlock.Map(b => b.GroupId).IfNone(0);
|
|
|
|
Either<BaseError, Unit> result =
|
|
await mediator.Send(request.ToCommand(groupId, id, ifMatch.ExpectedVersions), cancellationToken);
|
|
|
|
return await result.Match(
|
|
Left: error => Task.FromResult(error.ToErrorResult()),
|
|
Right: async _ =>
|
|
{
|
|
Option<BlockViewModel> refreshed = await mediator.Send(new GetBlockById(id), cancellationToken);
|
|
List<BlockItemViewModel> items = await mediator.Send(new GetBlockItems(id), cancellationToken);
|
|
return refreshed.Match(
|
|
Some: vm =>
|
|
{
|
|
// Return the new ETag so a same-tab second save doesn't 412 against its own write.
|
|
ConcurrencyHeaders.SetETag(Response, vm.Version);
|
|
return (IActionResult)new OkObjectResult(ProjectToWithItemsResponseModel(vm, items));
|
|
},
|
|
None: () => ApiResults.NotFoundProblem());
|
|
});
|
|
}
|
|
|
|
[HttpPost("/api/v1/blocks/{id:int}/preview")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Preview a block playout")]
|
|
[EndpointDescription(
|
|
"Builds a preview playout from the supplied block definition without persisting any changes to the " +
|
|
"block, its items, or any playout. Returns the resulting start/finish/title/duration list.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(List<BlockPreviewItemResponseModel>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> Preview(
|
|
int id,
|
|
[Required][FromBody] ReplaceBlockRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Option<BlockViewModel> maybeBlock = await mediator.Send(new GetBlockById(id), cancellationToken);
|
|
if (maybeBlock.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
int groupId = maybeBlock.Map(b => b.GroupId).IfNone(0);
|
|
|
|
List<PlayoutItemPreviewViewModel> preview = await mediator.Send(
|
|
new PreviewBlockPlayout(request.ToCommand(groupId, id)),
|
|
cancellationToken);
|
|
|
|
return new OkObjectResult(preview.Map(ProjectToResponseModel).ToList());
|
|
}
|
|
|
|
[HttpPost("/api/v1/blocks/{id:int}/copy")]
|
|
[Tags("Blocks")]
|
|
[EndpointSummary("Copy a block")]
|
|
[EndpointDescription("Copies the block and its items into another (or the same) block group under a new name.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(BlockResponseModel), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Copy(
|
|
int id,
|
|
[Required][FromBody] CopyBlockRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Option<BlockViewModel> existing = await mediator.Send(new GetBlockById(id), cancellationToken);
|
|
if (existing.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
Either<BaseError, BlockViewModel> result = await mediator.Send(request.ToCommand(id), cancellationToken);
|
|
return result.ToCreatedResult(
|
|
vm => $"/api/v1/blocks/{vm.Id}",
|
|
vm => ProjectToResponseModel(vm));
|
|
}
|
|
|
|
private static BlockGroupResponseModel ProjectToResponseModel(BlockGroupViewModel vm) =>
|
|
new(vm.Id, vm.Name);
|
|
|
|
private static BlockResponseModel ProjectToResponseModel(BlockViewModel vm) =>
|
|
new(vm.Id, vm.GroupId, vm.GroupName, vm.Name, vm.Minutes, vm.StopScheduling);
|
|
|
|
private static BlockWithItemsResponseModel ProjectToWithItemsResponseModel(
|
|
BlockViewModel vm,
|
|
List<BlockItemViewModel> items) =>
|
|
new(
|
|
vm.Id,
|
|
vm.GroupId,
|
|
vm.GroupName,
|
|
vm.Name,
|
|
vm.Minutes,
|
|
vm.StopScheduling,
|
|
items.OrderBy(i => i.Index).Map(ProjectToResponseModel).ToList());
|
|
|
|
private static BlockItemResponseModel ProjectToResponseModel(BlockItemViewModel vm) =>
|
|
new(
|
|
vm.Id,
|
|
vm.Index,
|
|
vm.CollectionType,
|
|
vm.Collection?.Id,
|
|
vm.Collection?.Name,
|
|
vm.MultiCollection?.Id,
|
|
vm.MultiCollection?.Name,
|
|
vm.SmartCollection?.Id,
|
|
vm.SmartCollection?.Name,
|
|
vm.MediaItem?.MediaItemId,
|
|
vm.MediaItem?.Name,
|
|
vm.SearchTitle,
|
|
vm.SearchQuery,
|
|
vm.PlaybackOrder,
|
|
vm.IncludeInProgramGuide,
|
|
vm.DisableWatermarks,
|
|
vm.Watermarks.Map(w => w.Id).ToList(),
|
|
vm.GraphicsElements.Map(g => g.Id).ToList());
|
|
|
|
private static BlockPreviewItemResponseModel ProjectToResponseModel(PlayoutItemPreviewViewModel vm) =>
|
|
new(vm.Title, vm.Start, vm.Finish, vm.Duration);
|
|
}
|