feat(api): playlist add-items + search all-items endpoints (#208 #209)

- POST /api/playlists/{id:int}/items wraps the existing AddItemsToPlaylist
  command (mirrors CollectionController.AddItems); controller pre-checks
  playlist existence for a real 404, and the handler now rejects adds to
  system (generated) playlists, matching the guard already applied to
  rename/delete/replace-items so the Blazor path gets the same protection.
- GET /api/search/all-items wraps the existing QuerySearchIndexAllItems
  query, returning a new SearchResultAllItemsResponseModel (never expose
  the VM directly) so the SPA's shared "add all to collection/playlist"
  component can materialize ids before calling the add endpoints, same
  two-step flow Blazor's Search.razor already uses.
- Show-detail DTO check: ShowDetailResponseModel already exposes
  libraryId, title, and mediaSourceKind (serialized as a string enum via
  the global StringEnumConverter) - no changes needed.

Adds controller tests (route table + per-action) for both endpoints and
regenerates the OpenAPI document, endpoint index, and SPA client types.
This commit is contained in:
2026-07-09 23:56:50 +02:00
parent cfabd6f33f
commit 819e751cab
10 changed files with 646 additions and 6 deletions
@@ -84,14 +84,20 @@ public class AddItemsToPlaylistHandler : IRequestHandler<AddItemsToPlaylist, Eit
await ValidateEpisodes(request))
.Apply((collection, _, _, _, _) => collection);
private static Task<Validation<BaseError, Playlist>> PlaylistMustExist(
private static async Task<Validation<BaseError, Playlist>> PlaylistMustExist(
TvContext dbContext,
AddItemsToPlaylist request,
CancellationToken cancellationToken) =>
dbContext.Playlists
CancellationToken cancellationToken)
{
Option<Playlist> maybePlaylist = await dbContext.Playlists
.Include(c => c.Items)
.SelectOneAsync(c => c.Id, c => c.Id == request.PlaylistId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("Playlist does not exist."));
.SelectOneAsync(c => c.Id, c => c.Id == request.PlaylistId, cancellationToken);
return maybePlaylist.ToValidation<BaseError>("Playlist does not exist.")
.Bind(playlist => playlist.IsSystem
? BaseError.New("Cannot add items to system (generated) playlist")
: Success<BaseError, Playlist>(playlist));
}
private Task<Validation<BaseError, Unit>> ValidateMovies(AddItemsToPlaylist request) =>
_movieRepository.AllMoviesExist(request.MovieIds)
@@ -0,0 +1,13 @@
namespace ErsatzTV.Core.Api.Search;
public record SearchResultAllItemsResponseModel(
List<int> MovieIds,
List<int> ShowIds,
List<int> SeasonIds,
List<int> EpisodeIds,
List<int> ArtistIds,
List<int> MusicVideoIds,
List<int> OtherVideoIds,
List<int> SongIds,
List<int> ImageIds,
List<int> RemoteStreamIds);
@@ -15,6 +15,7 @@ using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Controllers;
@@ -44,6 +45,7 @@ public class PlaylistControllerTests
ShouldHaveActionRoute(nameof(PlaylistController.Create), "POST", "/api/playlists");
ShouldHaveActionRoute(nameof(PlaylistController.Update), "PUT", "/api/playlists/{id:int}");
ShouldHaveActionRoute(nameof(PlaylistController.Delete), "DELETE", "/api/playlists/{id:int}");
ShouldHaveActionRoute(nameof(PlaylistController.AddItems), "POST", "/api/playlists/{id:int}/items");
ShouldHaveActionRoute(nameof(PlaylistController.Preview), "POST", "/api/playlists/preview");
}
@@ -445,6 +447,75 @@ public class PlaylistControllerTests
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task AddItems_Should_Return_204_And_Map_Request()
{
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlaylistViewModel>.Some(new PlaylistViewModel(4, 1, "Kids", false)));
_mediator.Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.AddItems(
4,
new AddItemsToPlaylistRequest([1, 2], [3], [], [], [], [], [], [], [], []),
CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<AddItemsToPlaylist>(c =>
c.PlaylistId == 4 &&
c.MovieIds.SequenceEqual(new List<int> { 1, 2 }) &&
c.ShowIds.SequenceEqual(new List<int> { 3 })),
Arg.Any<CancellationToken>());
}
[Test]
public async Task AddItems_Should_Return_404_When_Playlist_Missing()
{
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlaylistViewModel>.None);
IActionResult result = await _controller.AddItems(
4,
new AddItemsToPlaylistRequest([1], [], [], [], [], [], [], [], [], []),
CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
await _mediator.DidNotReceive().Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task AddItems_Should_Return_422_On_System_Playlist()
{
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlaylistViewModel>.Some(new PlaylistViewModel(4, 1, "System", true)));
_mediator.Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(BaseError.New("Cannot add items to system (generated) playlist")));
IActionResult result = await _controller.AddItems(
4,
new AddItemsToPlaylistRequest([1], [], [], [], [], [], [], [], [], []),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task AddItems_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
.Returns(Option<PlaylistViewModel>.Some(new PlaylistViewModel(4, 1, "Kids", false)));
_mediator.Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(BaseError.New("Movie does not exist")));
IActionResult result = await _controller.AddItems(
4,
new AddItemsToPlaylistRequest([999], [], [], [], [], [], [], [], [], []),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task Preview_Should_Return_200_And_Format_Times()
{
@@ -75,6 +75,54 @@ public class SearchControllerTests
ok.Value.ShouldBe(results);
}
[Test]
public void Controller_Should_Expose_SearchAllItems_Route_With_Stable_Operation_Name()
{
MethodInfo action = typeof(SearchController).GetMethod(nameof(SearchController.SearchAllItems))
?? throw new AssertionException($"Missing action {nameof(SearchController.SearchAllItems)}");
var attribute = action.GetCustomAttributes<HttpGetAttribute>().Single();
attribute.Template.ShouldBe("/api/search/all-items");
attribute.Name.ShouldBe("SearchAllItems");
}
[Test]
public async Task SearchAllItems_Should_Return_422_For_Empty_Query()
{
IActionResult result = await _controller.SearchAllItems(" ", CancellationToken.None);
var unprocessable = result.ShouldBeOfType<UnprocessableEntityObjectResult>();
unprocessable.StatusCode.ShouldBe(422);
await _mediator.DidNotReceive().Send(Arg.Any<QuerySearchIndexAllItems>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task SearchAllItems_Should_Map_Id_Lists()
{
_mediator.Send(Arg.Any<QuerySearchIndexAllItems>(), Arg.Any<CancellationToken>())
.Returns(new SearchResultAllItemsViewModel(
[1, 2],
[3],
[],
[],
[],
[],
[],
[],
[],
[]));
IActionResult result = await _controller.SearchAllItems("star", CancellationToken.None);
var body = result.ShouldBeOfType<OkObjectResult>().Value
.ShouldBeOfType<SearchResultAllItemsResponseModel>();
body.MovieIds.ShouldBe(new List<int> { 1, 2 });
body.ShowIds.ShouldBe(new List<int> { 3 });
await _mediator.Received(1).Send(
Arg.Is<QuerySearchIndexAllItems>(q => q.Query == "star"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task SearchCollections_Should_Map_To_Picker_Options()
{
@@ -222,6 +222,31 @@ public class PlaylistController(IMediator mediator) : ControllerBase
None: () => new NoContentResult());
}
[HttpPost("/api/playlists/{id:int}/items", Name = "AddItemsToPlaylist")]
[Tags("Playlists")]
[EndpointSummary("Add items to a playlist")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> AddItems(
int id,
[Required] [FromBody] AddItemsToPlaylistRequest request,
CancellationToken cancellationToken)
{
Option<PlaylistViewModel> maybePlaylist = await mediator.Send(new GetPlaylistById(id), cancellationToken);
if (maybePlaylist.IsNone)
{
return ApiResults.NotFoundProblem();
}
// System (generated) playlists must not have items added. The AddItemsToPlaylistHandler
// also enforces this (defense-in-depth for the Blazor path, which calls the same command
// from MultiSelectBase.AddItemsToPlaylist).
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
return result.ToDeletedResult();
}
[HttpPost("/api/playlists/preview", Name = "PreviewPlaylist")]
[Tags("Playlists")]
[EndpointSummary("Preview the playout of a draft playlist")]
@@ -0,0 +1,30 @@
using ErsatzTV.Application.MediaCollections;
namespace ErsatzTV.Controllers.Api.Requests;
public record AddItemsToPlaylistRequest(
List<int> MovieIds,
List<int> ShowIds,
List<int> SeasonIds,
List<int> EpisodeIds,
List<int> ArtistIds,
List<int> MusicVideoIds,
List<int> OtherVideoIds,
List<int> SongIds,
List<int> ImageIds,
List<int> RemoteStreamIds)
{
public AddItemsToPlaylist ToCommand(int playlistId) =>
new(
playlistId,
MovieIds ?? [],
ShowIds ?? [],
SeasonIds ?? [],
EpisodeIds ?? [],
ArtistIds ?? [],
MusicVideoIds ?? [],
OtherVideoIds ?? [],
SongIds ?? [],
ImageIds ?? [],
RemoteStreamIds ?? []);
}
@@ -39,6 +39,30 @@ public class SearchController(IMediator mediator) : ControllerBase
return new OkObjectResult(result);
}
[HttpGet("/api/search/all-items", Name = "SearchAllItems")]
[Tags("Search")]
[EndpointSummary("Search library items across all media kinds and return raw id lists")]
[EndpointDescription(
"Returns every matching item's id, grouped by media kind, with no paging. Used by the SPA's " +
"\"add all to collection/playlist\" flow to materialize ids before calling the add endpoints.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(SearchResultAllItemsResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> SearchAllItems(
[FromQuery] string query = "",
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(query))
{
return BaseError.New("A non-empty query is required").ToErrorResult();
}
SearchResultAllItemsViewModel result = await mediator.Send(
new QuerySearchIndexAllItems(query),
cancellationToken);
return new OkObjectResult(Project(result));
}
[HttpGet("/api/search/collections", Name = "SearchCollections")]
[Tags("Search")]
[EndpointSummary("Search collections by name")]
@@ -134,4 +158,17 @@ public class SearchController(IMediator mediator) : ControllerBase
cancellationToken);
return results.Map(c => new SchedulingPickerOptionResponseModel(c.Id, c.Name)).ToList();
}
private static SearchResultAllItemsResponseModel Project(SearchResultAllItemsViewModel vm) =>
new(
vm.MovieIds,
vm.ShowIds,
vm.SeasonIds,
vm.EpisodeIds,
vm.ArtistIds,
vm.MusicVideoIds,
vm.OtherVideoIds,
vm.SongIds,
vm.ImageIds,
vm.RemoteStreamIds);
}
+384
View File
@@ -6852,6 +6852,94 @@
}
}
}
},
"post": {
"tags": [
"Playlists"
],
"summary": "Add items to a playlist",
"operationId": "AddItemsToPlaylist",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"format": "int32"
}
}
],
"requestBody": {
"content": {
"application/json-patch+json": {
"schema": {
"$ref": "#/components/schemas/AddItemsToPlaylistRequest"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/AddItemsToPlaylistRequest"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/AddItemsToPlaylistRequest"
}
},
"application/*+json": {
"schema": {
"$ref": "#/components/schemas/AddItemsToPlaylistRequest"
}
}
},
"required": true
},
"responses": {
"204": {
"description": "No Content"
},
"404": {
"description": "Not Found",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"422": {
"description": "Unprocessable Entity",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
}
}
}
},
"/api/playlists/preview": {
@@ -9838,6 +9926,68 @@
}
}
},
"/api/search/all-items": {
"get": {
"tags": [
"Search"
],
"summary": "Search library items across all media kinds and return raw id lists",
"description": "Returns every matching item's id, grouped by media kind, with no paging. Used by the SPA's \"add all to collection/playlist\" flow to materialize ids before calling the add endpoints.",
"operationId": "SearchAllItems",
"parameters": [
{
"name": "query",
"in": "query",
"schema": {
"type": "string",
"default": ""
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/SearchResultAllItemsResponseModel"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/SearchResultAllItemsResponseModel"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/SearchResultAllItemsResponseModel"
}
}
}
},
"422": {
"description": "Unprocessable Entity",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
}
}
}
},
"/api/search/collections": {
"get": {
"tags": [
@@ -13845,6 +13995,123 @@
}
}
},
"AddItemsToPlaylistRequest": {
"required": [
"movieIds",
"showIds",
"seasonIds",
"episodeIds",
"artistIds",
"musicVideoIds",
"otherVideoIds",
"songIds",
"imageIds",
"remoteStreamIds"
],
"type": "object",
"properties": {
"movieIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"showIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"seasonIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"episodeIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"artistIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"musicVideoIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"otherVideoIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"songIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"imageIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"remoteStreamIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
}
}
},
"AddTraktListRequest": {
"required": [
"url"
@@ -20819,6 +21086,123 @@
}
}
},
"SearchResultAllItemsResponseModel": {
"required": [
"movieIds",
"showIds",
"seasonIds",
"episodeIds",
"artistIds",
"musicVideoIds",
"otherVideoIds",
"songIds",
"imageIds",
"remoteStreamIds"
],
"type": "object",
"properties": {
"movieIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"showIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"seasonIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"episodeIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"artistIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"musicVideoIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"otherVideoIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"songIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"imageIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
},
"remoteStreamIds": {
"type": [
"null",
"array"
],
"items": {
"type": "integer",
"format": "int32"
}
}
}
},
"SearchResultGroupResponseModel": {
"required": [
"totalCount",
+3 -1
View File
@@ -2,7 +2,7 @@
*Generated by `scripts/generate-endpoint-index.py` from `ErsatzTV/wwwroot/openapi/v1.json`. Do not edit by hand -- regenerated by `scripts/update-openapi.sh`.*
129 endpoints, 202 operations.
130 endpoints, 204 operations.
## Artists
@@ -214,6 +214,7 @@
| GET | `/api/playlists/{id}` | GetPlaylistById | Get a playlist by id |
| PUT | `/api/playlists/{id}` | UpdatePlaylist | Update a playlist (rename and replace its items) |
| GET | `/api/playlists/{id}/items` | GetPlaylistItems | Get the items in a playlist |
| POST | `/api/playlists/{id}/items` | AddItemsToPlaylist | Add items to a playlist |
## Playouts
@@ -274,6 +275,7 @@
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/search` | Search | Search library items across all media kinds |
| GET | `/api/search/all-items` | SearchAllItems | Search library items across all media kinds and return raw id lists |
| GET | `/api/search/artists` | SearchArtists | Search artists by name |
| GET | `/api/search/collections` | SearchCollections | Search collections by name |
| GET | `/api/search/multi-collections` | SearchMultiCollections | Search multi collections by name |
+24
View File
@@ -20,6 +20,18 @@ export interface components {
"songIds": null | Array<number>;
"imageIds": null | Array<number>;
"remoteStreamIds": null | Array<number>;
};
"AddItemsToPlaylistRequest": {
"movieIds": null | Array<number>;
"showIds": null | Array<number>;
"seasonIds": null | Array<number>;
"episodeIds": null | Array<number>;
"artistIds": null | Array<number>;
"musicVideoIds": null | Array<number>;
"otherVideoIds": null | Array<number>;
"songIds": null | Array<number>;
"imageIds": null | Array<number>;
"remoteStreamIds": null | Array<number>;
};
"AddTraktListRequest": {
"url": null | string;
@@ -1313,6 +1325,18 @@ export interface components {
"SchedulingPickerOptionResponseModel": {
"id": number;
"name": string;
};
"SearchResultAllItemsResponseModel": {
"movieIds": null | Array<number>;
"showIds": null | Array<number>;
"seasonIds": null | Array<number>;
"episodeIds": null | Array<number>;
"artistIds": null | Array<number>;
"musicVideoIds": null | Array<number>;
"otherVideoIds": null | Array<number>;
"songIds": null | Array<number>;
"imageIds": null | Array<number>;
"remoteStreamIds": null | Array<number>;
};
"SearchResultGroupResponseModel": {
"totalCount": number;