Adversarial review found the previous multi-flood design non-viable:
PlayoutModeSchedulerFlood never yields to a following Dynamic-start
schedule item, so only the first item ever played, and grouping
media items into a Collection silently dropped the requested order.
Redesign:
- Single-item lineup: one ProgramScheduleItemFlood referencing the
target directly (media item / collection / smart / multi / rerun /
playlist); no generated collection or playlist. Response PlaylistId
is null.
- Multi-item lineup (>= 2): one generated IsSystem Playlist in a
get-or-created IsSystem PlaylistGroup ("Channel Lineups"), one
PlaylistItem per entry in lineup order with PlayAll=true, referenced
by a single Flood schedule item. Rerun collections and playlists are
rejected (422) in multi lineups (PlaylistItem/CollectionKey lack the
fields to enumerate them).
Review fixes:
- Normalize + strict-validate MediaType<->CollectionType pairs once up
front (422 on mismatch / wrong id / not exactly one id).
- Reject MultiCollection with non-Shuffle order (mirrors
PlayoutModeMustBeValid), Mirror playout source, all via 422.
- OnDemand parity: queue TimeShiftOnDemandPlayout post-commit.
- De-collide generated ProgramSchedule and Playlist names against their
unique indexes instead of leaking a UNIQUE-constraint DbUpdateException.
- Generic 422 on save failure + ILogger; AnyAsync existence checks;
Either/Validation unwrap via Match; XML doc on request DTO + endpoint.
- Response model: ChannelId, PlaylistId (nullable), ProgramScheduleId,
PlayoutId (CollectionId removed). Regenerated OpenAPI v1.json + v1.d.ts.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
227 lines
11 KiB
C#
227 lines
11 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using System.Threading.Channels;
|
|
using ErsatzTV.Application;
|
|
using ErsatzTV.Application.Channels;
|
|
using ErsatzTV.Application.Playouts;
|
|
using ErsatzTV.Controllers.Api.Requests;
|
|
using ErsatzTV.Core;
|
|
using ErsatzTV.Core.Api.Channels;
|
|
using ErsatzTV.Core.Domain;
|
|
using ErsatzTV.Core.Scheduling;
|
|
using ErsatzTV.Extensions;
|
|
using MediatR;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace ErsatzTV.Controllers.Api;
|
|
|
|
[ApiController]
|
|
public class ChannelController(ChannelWriter<IBackgroundServiceRequest> workerChannel, IMediator mediator)
|
|
{
|
|
[HttpGet("/api/channels")]
|
|
[EndpointGroupName("general")]
|
|
public async Task<List<ChannelResponseModel>> GetAll() => await mediator.Send(new GetAllChannelsForApi());
|
|
|
|
[HttpGet("/api/channels/state")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Get channel runtime state")]
|
|
[EndpointGroupName("general")]
|
|
public async Task<List<ChannelStateResponseModel>> GetState(CancellationToken cancellationToken) =>
|
|
await mediator.Send(new GetChannelStatesForApi(DateTime.UtcNow), cancellationToken);
|
|
|
|
[HttpGet("/api/guide")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Get the JSON channel guide (EPG)")]
|
|
[EndpointDescription(
|
|
"Returns per-channel programme arrays for the EPG grid. When omitted, start defaults to now, " +
|
|
"and end defaults to start plus the configured XmltvDaysToBuild window.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(ChannelGuideResponseModel), StatusCodes.Status200OK)]
|
|
public async Task<ChannelGuideResponseModel> GetGuide(
|
|
[FromQuery] DateTimeOffset? start,
|
|
[FromQuery] DateTimeOffset? end,
|
|
CancellationToken cancellationToken) =>
|
|
await mediator.Send(new GetChannelGuideData(start, end), cancellationToken);
|
|
|
|
[HttpGet("/api/channels/{id:int}", Name = "GetChannelById")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Get a channel by id")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(ChannelViewModel), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
|
|
{
|
|
Option<ChannelViewModel> result = await mediator.Send(new GetChannelById(id), cancellationToken);
|
|
return result.ToGetResult();
|
|
}
|
|
|
|
[HttpPost("/api/channels")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Create a channel")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(ChannelViewModel), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Create(
|
|
[Required] [FromBody] CreateChannelRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, CreateChannelResult> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return await result.Match(
|
|
Left: error => Task.FromResult(error.ToErrorResult()),
|
|
Right: async created =>
|
|
{
|
|
Option<ChannelViewModel> channel =
|
|
await mediator.Send(new GetChannelById(created.ChannelId), cancellationToken);
|
|
return channel.Match(
|
|
Some: vm => (IActionResult)new CreatedResult($"/api/channels/{vm.Id}", vm),
|
|
None: () => ApiResults.NotFoundProblem());
|
|
});
|
|
}
|
|
|
|
[HttpPost("/api/channels/from-lineup", Name = "CreateChannelFromLineup")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Create a channel from a library lineup")]
|
|
[EndpointDescription(
|
|
"Atomically creates the channel, program schedule, a classic playout, and (for multi-item lineups) a " +
|
|
"generated system playlist. A single-item lineup produces one flood schedule item that references the " +
|
|
"target directly (movie, show, season, artist, collection, smart/multi collection, rerun collection, or " +
|
|
"playlist) and no generated playlist. A lineup with two or more items produces one generated system " +
|
|
"playlist whose entries play in the given order (each entry played in full before the next) referenced by " +
|
|
"one flood schedule item; only movies, shows, seasons, artists, collections, smart collections and multi " +
|
|
"collections are allowed there (rerun collections and playlists are single-item only). playbackOrder sets " +
|
|
"how items within each lineup entry are ordered. Template defaults are stamped at create time; advanced " +
|
|
"overrides win.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(CreateChannelFromLineupResponseModel), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> CreateFromLineup(
|
|
[Required] [FromBody] CreateChannelFromLineupRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, CreateChannelFromLineupResponseModel> result =
|
|
await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.ToCreatedResult(response => $"/api/channels/{response.ChannelId}", response => response);
|
|
}
|
|
|
|
[HttpPut("/api/channels/{id:int}")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Update a channel")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(typeof(ChannelViewModel), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> Update(
|
|
int id,
|
|
[Required] [FromBody] UpdateChannelRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, ChannelViewModel> result =
|
|
await mediator.Send(request.ToCommand(id), cancellationToken);
|
|
return result.ToUpdatedResult();
|
|
}
|
|
|
|
[HttpDelete("/api/channels/{id:int}")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Delete a channel")]
|
|
[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 DeleteChannel(id), cancellationToken);
|
|
return result.ToDeletedResult();
|
|
}
|
|
|
|
[HttpPost("/api/channels/bulk/renumber")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Renumber channels")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> BulkRenumber(
|
|
[Required] [FromBody] BulkRenumberChannelsRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Option<BaseError> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.Match<IActionResult>(
|
|
Some: error => error.ToErrorResult(),
|
|
None: () => new NoContentResult());
|
|
}
|
|
|
|
[HttpPost("/api/channels/bulk/group")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Move channels to a group")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> BulkMoveToGroup(
|
|
[Required] [FromBody] BulkMoveChannelsToGroupRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.ToDeletedResult();
|
|
}
|
|
|
|
[HttpPost("/api/channels/bulk/delete")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Delete channels")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
|
public async Task<IActionResult> BulkDelete(
|
|
[Required] [FromBody] BulkDeleteChannelsRequest request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
|
return result.ToDeletedResult();
|
|
}
|
|
|
|
[HttpPost("/api/channels/{channelNumber}/playout/reset")]
|
|
[Tags("Channels")]
|
|
[EndpointSummary("Reset channel playout")]
|
|
[EndpointDescription(
|
|
"When mode is omitted, classic playouts use Refresh (rebuild while maintaining collection " +
|
|
"progress) and all other playout kinds use Reset (rebuild from scratch), matching the Blazor UI. " +
|
|
"Pass mode to force a specific PlayoutBuildMode.")]
|
|
[EndpointGroupName("general")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> ResetPlayout(
|
|
string channelNumber,
|
|
[FromQuery] PlayoutBuildMode? mode,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Option<int> maybePlayoutId =
|
|
await mediator.Send(new GetPlayoutIdByChannelNumber(channelNumber), cancellationToken);
|
|
foreach (int playoutId in maybePlayoutId)
|
|
{
|
|
PlayoutBuildMode buildMode = mode ?? await DefaultResetMode(playoutId, cancellationToken);
|
|
await workerChannel.WriteAsync(new BuildPlayout(playoutId, buildMode), cancellationToken);
|
|
return new OkResult();
|
|
}
|
|
|
|
return ApiResults.NotFoundProblem();
|
|
}
|
|
|
|
// Match Blazor's Playouts.razor reset semantics: classic playouts refresh (preserve progress),
|
|
// every other kind resets from scratch.
|
|
private async Task<PlayoutBuildMode> DefaultResetMode(int playoutId, CancellationToken cancellationToken)
|
|
{
|
|
Option<PlayoutNameViewModel> maybePlayout =
|
|
await mediator.Send(new GetPlayoutById(playoutId), cancellationToken);
|
|
return maybePlayout.Match(
|
|
Some: vm => vm.ScheduleKind switch
|
|
{
|
|
PlayoutScheduleKind.Classic => PlayoutBuildMode.Refresh,
|
|
_ => PlayoutBuildMode.Reset
|
|
},
|
|
None: () => PlayoutBuildMode.Reset);
|
|
}
|
|
}
|