Files
ersatztv/ErsatzTV/Controllers/Api/CollectionController.cs
T
timothy 214fad2dcd fix(633): document the 0-based paging contract on the OpenAPI parameters
`api.paging-zero-based` says `pageNum` is 0-based across `/api/v1` and every wrapper
of it. That was true of the MCP tool catalog and the docs, and not true of the
generated OpenAPI document: all 24 paging parameters across the 12 paged operations
were emitted with no `description` at all, so a consumer reading only `v1.json` — the
intended contract, and what generated clients surface to their users — had to infer
the base from `default: 0`. That is the same inference that cost #487 a verification
pass on the MCP side, where the description was present but wrong.

Annotates each `[FromQuery]` paging parameter with `[Description]`
(`System.ComponentModel`), the mechanism `parentId` already used in ImagesController,
and regenerates `v1.json`. `pageSize` states the endpoint's OWN cap, because the caps
genuinely differ — 100 typical, 200 auto-tune members, 1000 search/all-items — and the
record forbids documenting one global number; it also states that the offset derives
from the effective (capped) size, so an over-large `pageSize` narrows the page instead
of widening the offset.

The generated TypeScript client covers DTOs only, not query parameters, so it is
unchanged; `endpoint-index.md` carries summaries, not parameter descriptions, so it is
unchanged too.

Pinned by OpenApiPagingContractTests against the in-process generated document. The
test NAMES the expected set of 12 paged operations rather than only filtering for
parameters called `pageNum`: a filter cannot see an endpoint that should page and
doesn't, which is exactly how two MCP tools escaped the equivalent check in #616. Set
equality is asserted in both directions, and the caps are pinned per endpoint so a
description naming the wrong cap fails — a wrong justification outlives a wrong line.

Mutation-verified both ways: dropping one `[Description]` reddens the description test,
and making one endpoint stop exposing `pageNum`/`pageSize` under those names reddens
the set-equality test.

Refs #633

Decisions-Edit: yes
2026-07-26 11:10:22 +02:00

212 lines
10 KiB
C#

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.LibraryBrowse;
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 CollectionController(IMediator mediator) : ControllerBase
{
[HttpGet("/api/v1/collections")]
[Tags("Collections")]
[EndpointSummary("Get all collections")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<MediaCollectionResponseModel>), StatusCodes.Status200OK)]
public async Task<List<MediaCollectionResponseModel>> GetAll(CancellationToken cancellationToken)
{
List<MediaCollectionViewModel> collections = await mediator.Send(new GetAllCollections(), cancellationToken);
return collections.Map(ProjectToResponseModel).ToList();
}
[HttpGet("/api/v1/collections/{id:int}", Name = "GetCollectionById")]
[Tags("Collections")]
[EndpointSummary("Get a collection by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(MediaCollectionResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<MediaCollectionViewModel> result = await mediator.Send(new GetCollectionById(id), cancellationToken);
return result.Map(ProjectToResponseModel).ToGetResult();
}
[HttpGet("/api/v1/collections/{id:int}/items", Name = "GetCollectionItems")]
[Tags("Collections")]
[EndpointSummary("Get the items in a manual collection")]
[EndpointDescription("Returns a manual collection's full contents (all media kinds), paged.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PagedLibraryBrowseItemsResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetItems(
int id,
[FromQuery]
[Description("0-based page index: the first page is 0, not 1. A negative value is clamped to 0.")]
int pageNum = 0,
[FromQuery]
[Description("Rows per page (default 100); capped at 100 for this endpoint. The page offset is derived from the effective (capped) size, so a larger value narrows the page instead of widening the offset.")]
int pageSize = 100,
CancellationToken cancellationToken = default)
{
int clampedPageNum = Math.Max(0, pageNum);
int clampedPageSize = Math.Clamp(pageSize, 1, 100);
// The items GET is the reorder editor's load endpoint: emit the collection's version as the
// concurrency ETag (issue #253). The response carries children, so read the root separately.
Option<MediaCollectionViewModel> maybeCollection =
await mediator.Send(new GetCollectionById(id), cancellationToken);
foreach (MediaCollectionViewModel collection in maybeCollection)
{
ConcurrencyHeaders.SetETag(Response, collection.Version);
}
Either<BaseError, PagedLibraryBrowseItemsResponseModel> result = await mediator.Send(
new GetCollectionItems(id, clampedPageNum, clampedPageSize),
cancellationToken);
return result.ToUpdatedResult();
}
[HttpPost("/api/v1/collections")]
[Tags("Collections")]
[EndpointSummary("Create a collection")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(MediaCollectionResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required][FromBody] CreateCollectionRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, MediaCollectionViewModel> result =
await mediator.Send(request.ToCommand(), cancellationToken);
return result.ToCreatedResult(vm => $"/api/v1/collections/{vm.Id}", ProjectToResponseModel);
}
[HttpPut("/api/v1/collections/{id:int}")]
[Tags("Collections")]
[EndpointSummary("Update a collection")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(MediaCollectionResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required][FromBody] UpdateCollectionRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
Option<MediaCollectionViewModel> collection =
await mediator.Send(new GetCollectionById(id), cancellationToken);
return collection.Match(
Some: vm => (IActionResult)new OkObjectResult(ProjectToResponseModel(vm)),
None: () => ApiResults.NotFoundProblem());
});
}
[HttpPut("/api/v1/collections/{id:int}/custom-order")]
[Tags("Collections")]
[EndpointSummary("Set a collection's custom playback order")]
[EndpointDescription(
"Replaces the custom playback order of a manual collection. CustomIndex is assigned from array position " +
"(the request body has no index field); ids that are not members of the collection are ignored. Set " +
"UseCustomPlaybackOrder on the collection for this order to take effect.")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> UpdateCustomOrder(
int id,
[Required][FromBody] UpdateCollectionCustomOrderRequest request,
CancellationToken cancellationToken)
{
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return ConcurrencyHeaders.MalformedIfMatchProblem();
}
Option<MediaCollectionViewModel> maybeCollection =
await mediator.Send(new GetCollectionById(id), cancellationToken);
if (maybeCollection.IsNone)
{
return ApiResults.NotFoundProblem();
}
Either<BaseError, Unit> result =
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersions), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
// Emit the new ETag on the bodyless 204 so a same-tab second save doesn't 412 (#253).
Option<MediaCollectionViewModel> refreshed =
await mediator.Send(new GetCollectionById(id), cancellationToken);
ConcurrencyHeaders.SetETag(Response, refreshed.Map(c => c.Version).IfNone(0));
return (IActionResult)new NoContentResult();
});
}
[HttpDelete("/api/v1/collections/{id:int}")]
[Tags("Collections")]
[EndpointSummary("Delete a collection")]
[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 DeleteCollection(id), cancellationToken);
return result.ToDeletedResult();
}
[HttpPost("/api/v1/collections/{id:int}/items")]
[Tags("Collections")]
[EndpointSummary("Add items to a collection")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> AddItems(
int id,
[Required][FromBody] AddItemsToCollectionRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
return result.ToDeletedResult();
}
[HttpDelete("/api/v1/collections/{id:int}/items/{mediaItemId:int}")]
[Tags("Collections")]
[EndpointSummary("Remove an item from a collection")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> RemoveItem(int id, int mediaItemId, CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(
new RemoveItemsFromCollection(id)
{
MediaItemIds = [mediaItemId]
},
cancellationToken);
return result.ToDeletedResult();
}
private static MediaCollectionResponseModel ProjectToResponseModel(MediaCollectionViewModel vm) =>
new(vm.Id, vm.Name, vm.CollectionType, vm.UseCustomPlaybackOrder);
}