Files
ersatztv/ErsatzTV/Controllers/Api/LocalLibrariesController.cs
T
timothy f5cf23c952 feat(api): local libraries REST endpoints (#202 slice S1)
Adds LocalLibrariesController (L1-L7: list/get/create/update/delete/move-path/
path-exists) wrapping the existing local-library MediatR commands, mapping to
the shared S0 response DTOs. Per design #202 §A.1/§C5/§C6:

- 404 for L4/L5/L6 comes from a controller pre-check (GetLocalLibraryById is
  None), not the handler -- .Apply/.ToEitherAsync both .Join() a NotFoundError
  into a plain 422, so relying on the handler would be dead code. This is
  check-then-act; a delete racing the pre-check falls through to the handler's
  422, documented in the controller.
- L4/L5 409 via IEntityLocker.IsLibraryLocked(id); L6 resolves the source
  library from the path id (new ILibraryRepository.GetLibraryIdForPath) before
  its own lock check.
- MoveLocalLibraryPathHandler gains same-MediaKind and different-library
  validation (finding 3) -- Blazor only filtered these client-side in the move
  dialog, so an API/MCP client could bypass them.
- CreateLocalLibraryHandler/UpdateLocalLibraryHandler gain a shared
  NewPathsMustExist validation (LocalLibraryHandlerBase) that Directory.Exists-
  checks only new paths (Id < 1); existing rows stay exempt so an unmounted
  share doesn't block a rename. L7 (path-exists) is a controller-local
  IFileSystem check with no command.

Tests: controller route/mediator-arg tests incl. 404-pre-check vs
fall-through-422 and 409-lock cases; handler tests for the move-path
cross-kind/same-library 422s, new-path 422 (missing/mixed), and a lossless
round-trip proving local paths are identified by normalized path string, not
id. Full solution test suite (Scanner/Core/Architecture/Tests/Infrastructure)
green, 0 regressions.

Deviations: none from the S1 slice description. Did not touch
MediaSourceRepository.cs or any Plex/Jellyfin/Emby file (S2/S3 scope). Did not
run the OpenAPI regen scripts (separate gate after S1-S3 merge per design §E).
2026-07-11 15:43:10 +02:00

217 lines
10 KiB
C#

using System.ComponentModel.DataAnnotations;
using System.IO.Abstractions;
using ErsatzTV.Application.Libraries;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.MediaSources;
using ErsatzTV.Core.Interfaces.Locking;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
// Local library CRUD (design #202 §A.1, endpoints L1-L7). Every id-keyed mutation (L4/L5/L6) gets
// its real 404 from a controller pre-check, NOT from the wrapped handler: `.Apply`/`ToEitherAsync`
// both `.Join()` a `NotFoundError` into a plain `BaseError`, which maps to 422
// (see `ErsatzTV.Core.LanguageExtensions`) — so relying on the handler for 404 here would be dead
// code (design #202 §A.1 finding 9). This is check-then-act: a delete racing the pre-check falls
// through to the handler's own 422, which is accepted and documented, not silently hidden.
[ApiController]
[EndpointGroupName("general")]
public class LocalLibrariesController(
IMediator mediator,
IEntityLocker entityLocker,
IFileSystem fileSystem,
ILibraryRepository libraryRepository) : ControllerBase
{
[HttpGet("/api/libraries/local", Name = "GetLocalLibraries")]
[Tags("Libraries")]
[EndpointSummary("Get all local libraries")]
[ProducesResponseType(typeof(List<LocalLibraryResponseModel>), StatusCodes.Status200OK)]
public async Task<List<LocalLibraryResponseModel>> GetAll(CancellationToken cancellationToken)
{
List<LocalLibraryViewModel> libraries = await mediator.Send(new GetAllLocalLibraries(), cancellationToken);
return libraries.Map(ProjectToResponseModel).ToList();
}
[HttpGet("/api/libraries/local/{id:int}", Name = "GetLocalLibrary")]
[Tags("Libraries")]
[EndpointSummary("Get a local library by id")]
[ProducesResponseType(typeof(LocalLibraryDetailResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<LocalLibraryViewModel> maybeLibrary = await mediator.Send(new GetLocalLibraryById(id), cancellationToken);
return await maybeLibrary.Match(
Some: async vm => (IActionResult)new OkObjectResult(await ProjectToDetailResponseModel(vm, cancellationToken)),
None: () => Task.FromResult(ApiResults.NotFoundProblem($"Local library {id} does not exist.")));
}
[HttpPost("/api/libraries/local")]
[Tags("Libraries")]
[EndpointSummary("Create a local library")]
[ProducesResponseType(typeof(LocalLibraryResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required] [FromBody] CreateLocalLibraryRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, LocalLibraryViewModel> result = await mediator.Send(request.ToCommand(), cancellationToken);
return result.ToCreatedResult(
vm => $"/api/libraries/local/{vm.Id}",
ProjectToResponseModel);
}
[HttpPut("/api/libraries/local/{id:int}")]
[Tags("Libraries")]
[EndpointSummary("Update a local library")]
[EndpointDescription(
"Replaces the library's name and full path list. MediaKind is immutable after create and is not " +
"part of this request. Paths are identified by normalized path string, not id — a renamed path is a " +
"delete-old + add-new (its id changes).")]
[ProducesResponseType(typeof(LocalLibraryDetailResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required] [FromBody] UpdateLocalLibraryRequest request,
CancellationToken cancellationToken)
{
Option<LocalLibraryViewModel> existing = await mediator.Send(new GetLocalLibraryById(id), cancellationToken);
if (existing.IsNone)
{
return ApiResults.NotFoundProblem($"Local library {id} does not exist.");
}
if (entityLocker.IsLibraryLocked(id))
{
return ApiResults.ConflictProblem(
"Library scan in progress",
$"Local library {id} is locked by an in-progress scan.");
}
Either<BaseError, LocalLibraryViewModel> result =
await mediator.Send(request.ToCommand(id), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
// reload via the same query GetById uses (api-conventions §7 write-path projection);
// paths.Id may have changed for renamed/added paths.
Option<LocalLibraryViewModel> refreshed =
await mediator.Send(new GetLocalLibraryById(id), cancellationToken);
return await refreshed.Match(
Some: async vm => (IActionResult)new OkObjectResult(
await ProjectToDetailResponseModel(vm, cancellationToken)),
None: () => Task.FromResult(ApiResults.NotFoundProblem($"Local library {id} does not exist.")));
});
}
[HttpDelete("/api/libraries/local/{id:int}")]
[Tags("Libraries")]
[EndpointSummary("Delete a local library")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{
Option<LocalLibraryViewModel> existing = await mediator.Send(new GetLocalLibraryById(id), cancellationToken);
if (existing.IsNone)
{
return ApiResults.NotFoundProblem($"Local library {id} does not exist.");
}
if (entityLocker.IsLibraryLocked(id))
{
return ApiResults.ConflictProblem(
"Library scan in progress",
$"Local library {id} is locked by an in-progress scan.");
}
Either<BaseError, Unit> result = await mediator.Send(new DeleteLocalLibrary(id), cancellationToken);
return result.ToDeletedResult();
}
[HttpPost("/api/libraries/local/paths/{pathId:int}/move")]
[Tags("Libraries")]
[EndpointSummary("Move a local library path to another local library")]
[EndpointDescription(
"Moves a path (and its scanned media) from its current library to a different local library of the " +
"same media kind. Blazor's move dialog enforces same-kind/different-library only client-side; this " +
"endpoint enforces both server-side so API/MCP clients cannot bypass them.")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> MovePath(
int pathId,
[Required] [FromBody] MoveLocalLibraryPathRequest request,
CancellationToken cancellationToken)
{
Option<int> maybeSourceLibraryId = await libraryRepository.GetLibraryIdForPath(pathId);
if (maybeSourceLibraryId.IsNone)
{
return ApiResults.NotFoundProblem($"Library path {pathId} does not exist.");
}
int sourceLibraryId = maybeSourceLibraryId.IfNone(0);
if (entityLocker.IsLibraryLocked(sourceLibraryId))
{
return ApiResults.ConflictProblem(
"Library scan in progress",
$"Local library {sourceLibraryId} is locked by an in-progress scan.");
}
// residual check-then-act race (design #202 §C5): a concurrent delete of this path between
// the pre-check above and this Send falls through to the handler's own 422, not a 404.
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(pathId), cancellationToken);
return result.ToDeletedResult();
}
[HttpPost("/api/libraries/local/path-exists")]
[Tags("Libraries")]
[EndpointSummary("Check whether a filesystem path exists")]
[EndpointDescription(
"Server-side existence check for the SPA's add-path UX (a browser cannot call Directory.Exists). " +
"This is a check-then-act convenience only — Create/Update still validate new paths at save time " +
"(design #202 §C2).")]
[ProducesResponseType(typeof(LocalPathCheckResponseModel), StatusCodes.Status200OK)]
public IActionResult CheckPathExists([Required] [FromBody] LocalPathCheckRequest request)
{
bool exists = !string.IsNullOrWhiteSpace(request.Path) && fileSystem.Directory.Exists(request.Path);
return new OkObjectResult(new LocalPathCheckResponseModel(exists));
}
private LocalLibraryResponseModel ProjectToResponseModel(LocalLibraryViewModel vm) =>
new(vm.Id, vm.Name, vm.MediaKind, entityLocker.IsLibraryLocked(vm.Id));
private async Task<LocalLibraryDetailResponseModel> ProjectToDetailResponseModel(
LocalLibraryViewModel vm,
CancellationToken cancellationToken)
{
List<LocalLibraryPathViewModel> paths =
await mediator.Send(new GetLocalLibraryPaths(vm.Id), cancellationToken);
int mediaItemCount = await mediator.Send(new CountMediaItemsByLibrary(vm.Id), cancellationToken);
var pathModels = new List<LocalLibraryPathResponseModel>();
foreach (LocalLibraryPathViewModel path in paths)
{
int pathCount = await mediator.Send(new CountMediaItemsByLibraryPath(path.Id), cancellationToken);
pathModels.Add(new LocalLibraryPathResponseModel(path.Id, path.Path, pathCount));
}
return new LocalLibraryDetailResponseModel(
vm.Id,
vm.Name,
vm.MediaKind,
entityLocker.IsLibraryLocked(vm.Id),
mediaItemCount,
pathModels);
}
}