Files
ersatztv/ErsatzTV/Controllers/Api/PlayoutController.cs
T
timothyandClaude Fable 5 f0a423c2de feat(api): block-playout history + sequential-schedule validation endpoints
Adds the REST surface for the #145 troubleshooting leftovers (#158 items 4-5):

- GET /api/playouts/{id}/blocks - blocks a block playout schedules
- GET /api/playouts/{id}/blocks/{blockId}/history - paged block history
- GET /api/playouts/history/{id} - decode a history row by id
- POST /api/troubleshoot/validate-schedule - validate sequential YAML

New MediatR queries GetPlayoutHistoryDetails (Either, 404 unknown row /
422 malformed JSON) and ValidateSequentialSchedule (wraps
ISequentialScheduleValidator, never throws). DecodePlayoutHistoryHandler
and the new by-id handler now share PlayoutHistoryDecoder. Regenerated
openapi/v1.json.

Refs #145 #158

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 22:10:37 +02:00

670 lines
30 KiB
C#

using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Application.Scheduling;
using ErsatzTV.Application.Troubleshooting;
using ErsatzTV.Application.Troubleshooting.Queries;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Playouts;
using ErsatzTV.Core.Api.Scheduling;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
public class PlayoutController(IMediator mediator) : ControllerBase
{
private const int MaxPageSize = 100;
[HttpGet("/api/playouts", Name = "GetPlayouts")]
[Tags("Playouts")]
[EndpointSummary("List playouts")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PagedPlayoutsResponseModel), StatusCodes.Status200OK)]
public async Task<PagedPlayoutsResponseModel> GetAll(
[FromQuery] string query = "",
[FromQuery] int pageNum = 0,
[FromQuery] int pageSize = 100,
CancellationToken cancellationToken = default)
{
PagedPlayoutsViewModel result =
await mediator.Send(new GetPagedPlayouts(query, pageNum, pageSize), cancellationToken);
return new PagedPlayoutsResponseModel(
result.TotalCount,
result.Page.Map(ToListItemResponse).ToList());
}
[HttpGet("/api/playouts/warnings/count", Name = "GetPlayoutWarningsCount")]
[Tags("Playouts")]
[EndpointSummary("Count playouts with a failed build")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
public async Task<int> GetWarningsCount(CancellationToken cancellationToken) =>
await mediator.Send(new GetPlayoutWarningsCount(), cancellationToken);
[HttpGet("/api/playouts/{id:int}", Name = "GetPlayoutById")]
[Tags("Playouts")]
[EndpointSummary("Get a playout by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PlayoutResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> result = await mediator.Send(new GetPlayoutById(id), cancellationToken);
return result.Map(ToResponse).ToGetResult();
}
[HttpGet("/api/playouts/{id:int}/items", Name = "GetPlayoutItems")]
[Tags("Playouts")]
[EndpointSummary("Get upcoming items (and unscheduled gaps) for a playout")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PagedPlayoutItemsResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetItems(
int id,
[FromQuery] bool showFiller = false,
[FromQuery] int pageNum = 0,
[FromQuery] int pageSize = 100,
CancellationToken cancellationToken = default)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
PagedPlayoutItemsViewModel result = await mediator.Send(
new GetFuturePlayoutItemsById(id, showFiller, pageNum, pageSize),
cancellationToken);
return new OkObjectResult(
new PagedPlayoutItemsResponseModel(
result.TotalCount,
result.Page.Map(ToItemResponse).ToList()));
}
[HttpPost("/api/playouts")]
[Tags("Playouts")]
[EndpointSummary("Create a playout")]
[EndpointDescription(
"Creates a playout of any kind (Classic, Block, Sequential, Scripted, or ExternalJson) for a channel. " +
"Classic requires ProgramScheduleId; Sequential/Scripted/ExternalJson require ScheduleFile; Block requires " +
"neither. A channel may only have one playout.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PlayoutResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required] [FromBody] CreatePlayoutRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, CreatePlayout> commandOrError = request.ToCommand();
return await commandOrError.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async command =>
{
Either<BaseError, CreatePlayoutResponse> result = await mediator.Send(command, cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async created =>
{
Option<PlayoutNameViewModel> playout =
await mediator.Send(new GetPlayoutById(created.PlayoutId), cancellationToken);
return playout.Match(
Some: vm => (IActionResult)new CreatedResult($"/api/playouts/{vm.PlayoutId}", ToResponse(vm)),
None: () => ApiResults.NotFoundProblem());
});
});
}
[HttpPut("/api/playouts/{id:int}")]
[Tags("Playouts")]
[EndpointSummary("Update playout scheduling details")]
[EndpointDescription(
"DailyRebuildTime is always applied; omit it (null) to clear the daily reset. ScheduleFile is only valid " +
"for Sequential, Scripted, and ExternalJson playouts; omit it (null) to leave it unchanged.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PlayoutResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required] [FromBody] UpdatePlayoutDetailsRequest request,
CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
var hasScheduleFile = !string.IsNullOrWhiteSpace(request.ScheduleFile);
foreach (PlayoutNameViewModel playout in maybePlayout)
{
if (hasScheduleFile && playout.ScheduleKind is not (PlayoutScheduleKind.Sequential
or PlayoutScheduleKind.Scripted or PlayoutScheduleKind.ExternalJson))
{
BaseError error =
BaseError.New("[ScheduleFile] is only valid for Sequential, Scripted, or ExternalJson playouts");
return error.ToErrorResult();
}
}
// the schedule-file update is the only step that can fail after the pre-checks,
// so it goes first — a rejected file must not leave DailyRebuildTime applied
if (hasScheduleFile)
{
foreach (PlayoutNameViewModel playout in maybePlayout)
{
Either<BaseError, PlayoutNameViewModel> scheduleFileResult =
await UpdateScheduleFile(playout, request.ScheduleFile, cancellationToken);
foreach (BaseError error in scheduleFileResult.LeftToSeq())
{
return error.ToErrorResult();
}
}
}
Option<TimeSpan> dailyRebuildTime = request.DailyRebuildTime is { } t ? Some(t) : Option<TimeSpan>.None;
Either<BaseError, PlayoutNameViewModel> result =
await mediator.Send(new UpdatePlayout(id, dailyRebuildTime), cancellationToken);
return result.Match(
Left: error => error.ToErrorResult(),
Right: playout => (IActionResult)new OkObjectResult(ToResponse(playout)));
}
private async Task<Either<BaseError, PlayoutNameViewModel>> UpdateScheduleFile(
PlayoutNameViewModel playout,
string scheduleFile,
CancellationToken cancellationToken) =>
playout.ScheduleKind switch
{
PlayoutScheduleKind.Sequential => await mediator.Send(
new UpdateSequentialPlayout(playout.PlayoutId, scheduleFile),
cancellationToken),
PlayoutScheduleKind.Scripted => await mediator.Send(
new UpdateScriptedPlayout(playout.PlayoutId, scheduleFile),
cancellationToken),
PlayoutScheduleKind.ExternalJson => await mediator.Send(
new UpdateExternalJsonPlayout(playout.PlayoutId, scheduleFile),
cancellationToken),
_ => 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());
}
[HttpGet("/api/playouts/{id:int}/alternate-schedules", Name = "GetPlayoutAlternateSchedules")]
[Tags("Playouts")]
[EndpointSummary("Get a classic playout's alternate schedules")]
[EndpointDescription(
"Lists a Classic playout's alternate schedules in priority order (first = highest priority). The last " +
"entry is the catch-all default, and its schedule is the playout's default schedule; if no explicit " +
"catch-all exists the query synthesizes one from the playout's default schedule. Only valid for Classic " +
"playouts; other kinds return 422.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<PlayoutAlternateScheduleResponseModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> GetAlternateSchedules(int id, CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
foreach (PlayoutNameViewModel playout in maybePlayout)
{
if (playout.ScheduleKind is not PlayoutScheduleKind.Classic)
{
return BaseError.New("[AlternateSchedules] are only valid for Classic playouts").ToErrorResult();
}
}
List<PlayoutAlternateScheduleViewModel> items =
await mediator.Send(new GetPlayoutAlternateSchedules(id), cancellationToken);
return new OkObjectResult(items.OrderBy(i => i.Index).Select(ToResponse).ToList());
}
[HttpPut("/api/playouts/{id:int}/alternate-schedules")]
[Tags("Playouts")]
[EndpointSummary("Replace a classic playout's alternate schedules")]
[EndpointDescription(
"Replaces a Classic playout's alternate schedules. Items are ordered by priority: the first item is the " +
"highest priority and the last item is the catch-all default whose schedule becomes the playout's default " +
"schedule. Index is assigned from array order (the request body has no Index field). The list must contain " +
"at least one item, and every ProgramScheduleId must exist. Only valid for Classic playouts.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<PlayoutAlternateScheduleResponseModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> ReplaceAlternateSchedules(
int id,
[Required] [FromBody] ReplacePlayoutAlternateSchedulesRequest request,
CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
foreach (PlayoutNameViewModel playout in maybePlayout)
{
if (playout.ScheduleKind is not PlayoutScheduleKind.Classic)
{
return BaseError.New("[AlternateSchedules] are only valid for Classic playouts").ToErrorResult();
}
}
List<PlayoutAlternateScheduleItemRequest> items = request.Items ?? [];
if (items.Count == 0)
{
return BaseError.New("[Items] must contain at least one alternate schedule").ToErrorResult();
}
foreach (BaseError error in ValidateDateRanges(items.Select(ToDateRangeCheck)))
{
return error.ToErrorResult();
}
List<ProgramScheduleViewModel> schedules =
await mediator.Send(new GetAllProgramSchedules(), cancellationToken);
var scheduleIds = schedules.Select(s => s.Id).ToHashSet();
var missingScheduleIds = items.Select(i => i.ProgramScheduleId).Distinct()
.Where(scheduleId => !scheduleIds.Contains(scheduleId)).ToList();
if (missingScheduleIds.Count > 0)
{
return BaseError.New($"[ProgramScheduleId] {missingScheduleIds[0]} does not exist").ToErrorResult();
}
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
List<PlayoutAlternateScheduleViewModel> refreshed =
await mediator.Send(new GetPlayoutAlternateSchedules(id), cancellationToken);
return (IActionResult)new OkObjectResult(refreshed.OrderBy(i => i.Index).Select(ToResponse).ToList());
});
}
[HttpGet("/api/playouts/{id:int}/templates", Name = "GetPlayoutTemplates")]
[Tags("Playouts")]
[EndpointSummary("Get a block playout's templates")]
[EndpointDescription(
"Lists a Block playout's templates in priority order (first = highest priority). Each template optionally " +
"carries a deco template. Only valid for Block playouts; other kinds return 422.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<PlayoutTemplateResponseModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> GetTemplates(int id, CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
foreach (PlayoutNameViewModel playout in maybePlayout)
{
if (playout.ScheduleKind is not PlayoutScheduleKind.Block)
{
return BaseError.New("[Templates] are only valid for Block playouts").ToErrorResult();
}
}
List<PlayoutTemplateViewModel> items = await mediator.Send(new GetPlayoutTemplates(id), cancellationToken);
return new OkObjectResult(items.OrderBy(i => i.Index).Select(ToResponse).ToList());
}
[HttpPut("/api/playouts/{id:int}/templates")]
[Tags("Playouts")]
[EndpointSummary("Replace a block playout's templates")]
[EndpointDescription(
"Replaces a Block playout's templates. Items are ordered by priority (first = highest priority); Index is " +
"assigned from array order (the request body has no Index field). Every TemplateId must exist, and any " +
"supplied DecoTemplateId must exist. An empty list clears all templates. Only valid for Block playouts.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<PlayoutTemplateResponseModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> ReplaceTemplates(
int id,
[Required] [FromBody] ReplacePlayoutTemplatesRequest request,
CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
foreach (PlayoutNameViewModel playout in maybePlayout)
{
if (playout.ScheduleKind is not PlayoutScheduleKind.Block)
{
return BaseError.New("[Templates] are only valid for Block playouts").ToErrorResult();
}
}
List<PlayoutTemplateItemRequest> items = request.Items ?? [];
foreach (BaseError error in ValidateDateRanges(items.Select(ToDateRangeCheck)))
{
return error.ToErrorResult();
}
List<TemplateViewModel> templates = await mediator.Send(new GetAllTemplates(), cancellationToken);
var templateIds = templates.Select(t => t.Id).ToHashSet();
var missingTemplateIds = items.Select(i => i.TemplateId).Distinct()
.Where(templateId => !templateIds.Contains(templateId)).ToList();
if (missingTemplateIds.Count > 0)
{
return BaseError.New($"[TemplateId] {missingTemplateIds[0]} does not exist").ToErrorResult();
}
var decoTemplateIds = items.Where(i => i.DecoTemplateId.HasValue)
.Select(i => i.DecoTemplateId!.Value).Distinct().ToList();
foreach (int decoTemplateId in decoTemplateIds)
{
Option<DecoTemplateViewModel> maybeDecoTemplate =
await mediator.Send(new GetDecoTemplateById(decoTemplateId), cancellationToken);
if (maybeDecoTemplate.IsNone)
{
return BaseError.New($"[DecoTemplateId] {decoTemplateId} does not exist").ToErrorResult();
}
}
Option<BaseError> result = await mediator.Send(request.ToCommand(id), cancellationToken);
foreach (BaseError error in result)
{
return error.ToErrorResult();
}
List<PlayoutTemplateViewModel> refreshed = await mediator.Send(new GetPlayoutTemplates(id), cancellationToken);
return new OkObjectResult(refreshed.OrderBy(i => i.Index).Select(ToResponse).ToList());
}
[HttpGet("/api/playouts/{id:int}/blocks", Name = "GetPlayoutBlocks")]
[Tags("Playouts")]
[EndpointSummary("Get the blocks scheduled by a block playout")]
[EndpointDescription(
"Lists the distinct blocks reachable through a Block playout's templates, ordered by group then name. " +
"A playout with no templates (including non-Block playouts) returns an empty list.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<BlockResponseModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetBlocks(int id, CancellationToken cancellationToken)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
List<BlockViewModel> blocks = await mediator.Send(new GetAllBlocksForPlayout(id), cancellationToken);
return new OkObjectResult(blocks.Map(ToBlockResponse).ToList());
}
[HttpGet("/api/playouts/{id:int}/blocks/{blockId:int}/history", Name = "GetPlayoutBlockHistory")]
[Tags("Playouts")]
[EndpointSummary("Get a block's playout history")]
[EndpointDescription(
"Returns the paged scheduling history for a single block within a block playout, oldest first. Each row's " +
"Key and Details carry raw JSON; decode a row via GET /api/playouts/history/{id}.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PagedPlayoutHistoryResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetBlockHistory(
int id,
int blockId,
[FromQuery] int pageNum = 0,
[FromQuery] int pageSize = 100,
CancellationToken cancellationToken = default)
{
Option<PlayoutNameViewModel> maybePlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
if (maybePlayout.IsNone)
{
return ApiResults.NotFoundProblem();
}
int clampedPageNum = Math.Max(0, pageNum);
int clampedPageSize = Math.Clamp(pageSize, 1, MaxPageSize);
PagedPlayoutHistoryViewModel result = await mediator.Send(
new GetBlockPlayoutHistory(id, blockId, clampedPageNum, clampedPageSize),
cancellationToken);
return new OkObjectResult(
new PagedPlayoutHistoryResponseModel(
result.TotalCount,
result.Page.Map(ToHistoryResponse).ToList()));
}
[HttpGet("/api/playouts/history/{id:int}", Name = "GetPlayoutHistoryDetails")]
[Tags("Playouts")]
[EndpointSummary("Decode a playout history row")]
[EndpointDescription(
"Decodes a single playout history row (by its id) into its playback order, collection, and media-item " +
"details. Returns 422 if the row's stored Key/Details JSON cannot be decoded.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PlayoutHistoryDetailsResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> GetHistoryDetails(int id, CancellationToken cancellationToken)
{
Either<BaseError, PlayoutHistoryDetailsViewModel> result =
await mediator.Send(new GetPlayoutHistoryDetails(id), cancellationToken);
return result.Match(
Left: error => error.ToErrorResult(),
Right: vm => (IActionResult)new OkObjectResult(ToDetailsResponse(vm)));
}
[HttpPost("/api/playouts/reset-all", Name = "ResetAllPlayouts")]
[Tags("Playouts")]
[EndpointSummary("Reset all playouts")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public async Task<IActionResult> ResetAll(CancellationToken cancellationToken)
{
await mediator.Send(new ResetAllPlayouts(), cancellationToken);
return Accepted();
}
[HttpDelete("/api/playouts/{id:int}")]
[Tags("Playouts")]
[EndpointSummary("Delete a playout")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(new DeletePlayout(id), cancellationToken);
return result.ToDeletedResult();
}
// Guards against AlternateScheduleSelector crashing on out-of-range dates: it constructs
// `new DateTime(year, StartMonth, StartDay)` and only recovers from an overflowing *day*
// (rolling to the 1st of the next month); an out-of-range *month* throws again from inside
// that recovery path and is never caught. Only checked when LimitToDateRange is set, since
// the fields are ignored otherwise.
private static (bool LimitToDateRange, int StartMonth, int StartDay, int EndMonth, int EndDay) ToDateRangeCheck(
PlayoutAlternateScheduleItemRequest item) =>
(item.LimitToDateRange, item.StartMonth, item.StartDay, item.EndMonth, item.EndDay);
private static (bool LimitToDateRange, int StartMonth, int StartDay, int EndMonth, int EndDay) ToDateRangeCheck(
PlayoutTemplateItemRequest item) =>
(item.LimitToDateRange, item.StartMonth, item.StartDay, item.EndMonth, item.EndDay);
private static Option<BaseError> ValidateDateRanges(
IEnumerable<(bool LimitToDateRange, int StartMonth, int StartDay, int EndMonth, int EndDay)> items)
{
foreach ((bool limitToDateRange, int startMonth, int startDay, int endMonth, int endDay) in items)
{
if (!limitToDateRange)
{
continue;
}
if (startMonth is < 1 or > 12)
{
return Some(BaseError.New($"[StartMonth] {startMonth} must be between 1 and 12"));
}
if (endMonth is < 1 or > 12)
{
return Some(BaseError.New($"[EndMonth] {endMonth} must be between 1 and 12"));
}
if (startDay is < 1 or > 31)
{
return Some(BaseError.New($"[StartDay] {startDay} must be between 1 and 31"));
}
if (endDay is < 1 or > 31)
{
return Some(BaseError.New($"[EndDay] {endDay} must be between 1 and 31"));
}
}
return Option<BaseError>.None;
}
private static BlockResponseModel ToBlockResponse(BlockViewModel vm) =>
new(vm.Id, vm.GroupId, vm.GroupName, vm.Name, vm.Minutes, vm.StopScheduling);
private static PlayoutHistoryResponseModel ToHistoryResponse(PlayoutHistoryViewModel vm) =>
new(vm.Id, vm.When, vm.Finish, vm.Key, vm.Details);
private static PlayoutHistoryDetailsResponseModel ToDetailsResponse(PlayoutHistoryDetailsViewModel vm) =>
new(vm.PlaybackOrder, vm.CollectionType, vm.Name, vm.MediaItemType, vm.MediaItemTitle);
private static PlayoutResponseModel ToResponse(PlayoutNameViewModel vm) =>
PlayoutResponseModel.From(
vm.PlayoutId,
vm.ScheduleKind,
vm.ChannelName,
vm.ChannelNumber,
vm.PlayoutMode,
vm.ScheduleName,
vm.ScheduleFile,
vm.DbDailyRebuildTime,
ToBuildStatus(vm.BuildStatus),
vm.DecoId,
vm.DecoName);
private static PlayoutAlternateScheduleResponseModel ToResponse(PlayoutAlternateScheduleViewModel vm) =>
new(
vm.Id,
vm.Index,
vm.ProgramScheduleId,
vm.DaysOfWeek,
vm.DaysOfMonth,
vm.MonthsOfYear,
vm.LimitToDateRange,
vm.StartMonth,
vm.StartDay,
vm.StartYear,
vm.EndMonth,
vm.EndDay,
vm.EndYear);
private static PlayoutTemplateResponseModel ToResponse(PlayoutTemplateViewModel vm) =>
new(
vm.Id,
vm.Index,
vm.Template.Id,
vm.Template.Name,
vm.Template.GroupName,
vm.DecoTemplate?.Id,
vm.DecoTemplate?.Name,
vm.DecoTemplate?.GroupName,
vm.DaysOfWeek,
vm.DaysOfMonth,
vm.MonthsOfYear,
vm.LimitToDateRange,
vm.StartMonth,
vm.StartDay,
vm.StartYear,
vm.EndMonth,
vm.EndDay,
vm.EndYear);
private static PlayoutListItemResponseModel ToListItemResponse(PlayoutNameViewModel vm) =>
new(
vm.PlayoutId,
vm.ChannelNumber,
vm.ChannelName,
vm.ScheduleKind,
vm.ScheduleName,
vm.DbDailyRebuildTime,
ToBuildStatus(vm.BuildStatus));
private static PlayoutBuildStatusResponseModel ToBuildStatus(PlayoutBuildStatus buildStatus) =>
buildStatus is null
? null
: new PlayoutBuildStatusResponseModel(
buildStatus.LastBuild,
buildStatus.Success,
buildStatus.Message);
private static PlayoutItemResponseModel ToItemResponse(PlayoutItemViewModel vm) =>
new(
vm.Title,
vm.Start,
vm.Finish,
vm.Duration,
vm.FillerKind.MatchUnsafe(fk => (FillerKind?)fk, () => null));
}