Hardening from adversarial review of the #153 playlist API: - PUT /api/playlists/{id}: guard IsSystem in the controller after the existence pre-check -> 422, so a system (generated) playlist can no longer be renamed/wiped. ReplacePlaylistItems is never sent for it. - PUT /api/playlists/groups/{id}: add controller existence pre-check (404 for missing, mirroring DeleteGroup) plus an IsSystem 422 guard; RenamePlaylistGroupHandler also gains a system guard (defense-in-depth for the Blazor path). Missing/system are now distinct outcomes despite LanguageExtensions.Apply collapsing NotFoundError to a plain BaseError. - POST /api/playlists/preview: validate each draft item at the controller boundary (the id required for its collection type must be present) -> 422 before the shared PreviewPlaylistPlayoutHandler runs, preventing a NRE/500 in the playout builder. Logic lives in ReplacePlaylistRequest so it stays parallel with ReplacePlaylistItemsHandler's PUT-path check. Tests: controller cases for system-playlist PUT, system-group PUT, missing-group 404, and invalid-preview 422 (each asserting the handler is not invoked); handler tests for RenamePlaylistGroup system/missing/success. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
286 lines
13 KiB
C#
286 lines
13 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using System.Globalization;
|
|
using ErsatzTV.Application.MediaCollections;
|
|
using ErsatzTV.Application.Scheduling;
|
|
using ErsatzTV.Controllers.Api.Requests;
|
|
using ErsatzTV.Core;
|
|
using ErsatzTV.Core.Api.MediaCollections;
|
|
using ErsatzTV.Extensions;
|
|
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(ProjectToGroupResponse).ToList();
|
|
}
|
|
|
|
[HttpPost("/api/playlists/groups", Name = "CreatePlaylistGroup")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Create a playlist group")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(PlaylistGroupResponseModel), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> CreateGroup(
|
|
[Required] [FromBody] CreatePlaylistGroupRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, PlaylistGroupViewModel> result =
|
|
await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.ToCreatedResult(
|
|
g => $"/api/playlists/groups/{g.Id}",
|
|
ProjectToGroupResponse);
|
|
}
|
|
|
|
[HttpPut("/api/playlists/groups/{id:int}", Name = "UpdatePlaylistGroup")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Rename a playlist group")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(PlaylistGroupResponseModel), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> UpdateGroup(
|
|
int id,
|
|
[Required] [FromBody] UpdatePlaylistGroupRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
// Existence pre-check (404) mirrors DeleteGroup. Required controller-side because the
|
|
// handler's NotFoundError is collapsed to a plain BaseError by LanguageExtensions.Apply
|
|
// (error.Join()), so a missing group would otherwise map to 422 instead of 404.
|
|
List<PlaylistGroupViewModel> groups = await mediator.Send(new GetAllPlaylistGroups(), cancellationToken);
|
|
Option<PlaylistGroupViewModel> maybeGroup = groups.Find(g => g.Id == id);
|
|
if (maybeGroup.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
// System (generated) groups must not be renamed. The RenamePlaylistGroupHandler also
|
|
// enforces this (defense-in-depth for the Blazor path); catching it here keeps the API's
|
|
// 422 independent of the handler's error-collapsing.
|
|
foreach (PlaylistGroupViewModel group in maybeGroup)
|
|
{
|
|
if (group.IsSystem)
|
|
{
|
|
return BaseError.New("Cannot rename system playlist group").ToErrorResult();
|
|
}
|
|
}
|
|
|
|
Either<BaseError, PlaylistGroupViewModel> result =
|
|
await mediator.Send(request.ToCommand(id), cancellationToken);
|
|
return result.Match(
|
|
Left: error => error.ToErrorResult(),
|
|
Right: vm => (IActionResult)new OkObjectResult(ProjectToGroupResponse(vm)));
|
|
}
|
|
|
|
[HttpDelete("/api/playlists/groups/{id:int}", Name = "DeletePlaylistGroup")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Delete a playlist group")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> DeleteGroup(int id, CancellationToken cancellationToken)
|
|
{
|
|
List<PlaylistGroupViewModel> groups = await mediator.Send(new GetAllPlaylistGroups(), cancellationToken);
|
|
if (groups.All(g => g.Id != id))
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
Option<BaseError> result = await mediator.Send(new DeletePlaylistGroup(id), cancellationToken);
|
|
return result.Match<IActionResult>(
|
|
Some: error => error.ToErrorResult(),
|
|
None: () => new NoContentResult());
|
|
}
|
|
|
|
[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(ProjectToPlaylistResponse).ToList();
|
|
}
|
|
|
|
[HttpGet("/api/playlists/{id:int}", Name = "GetPlaylistById")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Get a playlist by id")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(PlaylistResponseModel), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
|
|
{
|
|
Option<PlaylistViewModel> result = await mediator.Send(new GetPlaylistById(id), cancellationToken);
|
|
return result.Map(ProjectToPlaylistResponse).ToGetResult();
|
|
}
|
|
|
|
[HttpGet("/api/playlists/{id:int}/items", Name = "GetPlaylistItems")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Get the items in a playlist")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(List<PlaylistItemResponseModel>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> GetItems(int id, CancellationToken cancellationToken)
|
|
{
|
|
Option<PlaylistViewModel> maybePlaylist = await mediator.Send(new GetPlaylistById(id), cancellationToken);
|
|
if (maybePlaylist.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
List<PlaylistItemViewModel> items = await mediator.Send(new GetPlaylistItems(id), cancellationToken);
|
|
return new OkObjectResult(items.Map(ProjectToItemResponse).ToList());
|
|
}
|
|
|
|
[HttpPost("/api/playlists", Name = "CreatePlaylistInGroup")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Create a playlist")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(PlaylistResponseModel), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Create(
|
|
[Required] [FromBody] CreatePlaylistRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, PlaylistViewModel> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.ToCreatedResult(
|
|
p => $"/api/playlists/{p.Id}",
|
|
ProjectToPlaylistResponse);
|
|
}
|
|
|
|
[HttpPut("/api/playlists/{id:int}", Name = "UpdatePlaylist")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Update a playlist (rename and replace its items)")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(List<PlaylistItemResponseModel>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Update(
|
|
int id,
|
|
[Required] [FromBody] ReplacePlaylistRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Option<PlaylistViewModel> maybePlaylist = await mediator.Send(new GetPlaylistById(id), cancellationToken);
|
|
if (maybePlaylist.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
// System (generated) playlists must not be renamed or have their items replaced.
|
|
// Mirrors the DeletePlaylist system-guard (422); done controller-side so item
|
|
// replacement never reaches ReplacePlaylistItemsHandler for a generated playlist.
|
|
foreach (PlaylistViewModel playlist in maybePlaylist)
|
|
{
|
|
if (playlist.IsSystem)
|
|
{
|
|
return BaseError.New("Cannot modify system (generated) playlist").ToErrorResult();
|
|
}
|
|
}
|
|
|
|
Either<BaseError, List<PlaylistItemViewModel>> result =
|
|
await mediator.Send(request.ToCommand(id), cancellationToken);
|
|
return result.Match(
|
|
Left: error => error.ToErrorResult(),
|
|
Right: items => (IActionResult)new OkObjectResult(items.Map(ProjectToItemResponse).ToList()));
|
|
}
|
|
|
|
[HttpDelete("/api/playlists/{id:int}", Name = "DeletePlaylist")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Delete a playlist")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
|
|
{
|
|
Option<PlaylistViewModel> maybePlaylist = await mediator.Send(new GetPlaylistById(id), cancellationToken);
|
|
if (maybePlaylist.IsNone)
|
|
{
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
Option<BaseError> result = await mediator.Send(new DeletePlaylist(id), cancellationToken);
|
|
return result.Match<IActionResult>(
|
|
Some: error => error.ToErrorResult(),
|
|
None: () => new NoContentResult());
|
|
}
|
|
|
|
[HttpPost("/api/playlists/preview", Name = "PreviewPlaylist")]
|
|
[Tags("Playlists")]
|
|
[EndpointSummary("Preview the playout of a draft playlist")]
|
|
[EndpointDescription("Builds a preview playout from the posted draft playlist items (no persistence).")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(List<PlaylistPreviewItemResponseModel>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Preview(
|
|
[Required] [FromBody] ReplacePlaylistRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
// The preview path does not run the handler's CollectionTypesMustBeValid check
|
|
// (PreviewPlaylistPlayoutHandler is shared with Blazor and left unchanged), so
|
|
// validate the draft at the controller boundary to avoid a 500 in the playout
|
|
// builder on an item missing the id required for its collection type.
|
|
List<int> invalidItems = request.ItemsMissingRequiredId();
|
|
if (invalidItems.Count > 0)
|
|
{
|
|
return BaseError
|
|
.New($"Invalid playlist item(s) at index(es): {string.Join(", ", invalidItems)}")
|
|
.ToErrorResult();
|
|
}
|
|
|
|
Either<BaseError, List<PlayoutItemPreviewViewModel>> result =
|
|
await mediator.Send(new PreviewPlaylistPlayout(request.ToReplaceCommand()), cancellationToken);
|
|
return result.Match(
|
|
Left: error => error.ToErrorResult(),
|
|
Right: items => (IActionResult)new OkObjectResult(items.Map(ProjectToPreviewResponse).ToList()));
|
|
}
|
|
|
|
private static PlaylistGroupResponseModel ProjectToGroupResponse(PlaylistGroupViewModel vm) =>
|
|
new(vm.Id, vm.Name, vm.PlaylistCount, vm.IsSystem);
|
|
|
|
private static PlaylistResponseModel ProjectToPlaylistResponse(PlaylistViewModel vm) =>
|
|
new(vm.Id, vm.PlaylistGroupId, vm.Name, vm.IsSystem);
|
|
|
|
private static PlaylistItemResponseModel ProjectToItemResponse(PlaylistItemViewModel 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.PlaybackOrder,
|
|
vm.Count,
|
|
vm.PlayAll,
|
|
vm.IncludeInProgramGuide);
|
|
|
|
private static PlaylistPreviewItemResponseModel ProjectToPreviewResponse(PlayoutItemPreviewViewModel vm) =>
|
|
new(
|
|
vm.Title,
|
|
vm.Start.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture),
|
|
vm.Finish.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture),
|
|
vm.Duration);
|
|
}
|