Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 5s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m6s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 9m49s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Activating #253's `Version` as an `IsConcurrencyToken` made EF guard every UPDATE *and DELETE* of a versioned root with `WHERE Version=@orig`, so any writer outside the If-Match contract that saves via plain `SaveChangesAsync` throws an unhandled `DbUpdateConcurrencyException`->500 when a replace-all editor bumps the row in its narrow load->save window (ordinary two-tab UI). A completeness sweep (grep every `Version` bumper + every root delete, not just the handlers PR3's close note named) found 17 exposed writers, all now routed through `ConcurrencyExtensions.SaveChangesForcingVersion` (Phase-1 force-write: adopt the stored token and retry; rethrow only on genuine row-deletion): - 9 versioned-root delete handlers (a delete has no ETag to rotate -> force only, no bump) - UpdateProgramScheduleHandler (bumps then saved plainly - the ProgramSchedule case PR3 only suspected; its post-commit query/enqueue also moved to CancellationToken.None per section 7b) - 7 item add/remove bumpers PR2 left on plain save: Add/DeleteProgramScheduleItem + Add{Items,Movie,Show,Season,Episode}ToPlaylist Force-write (not 412) is correct: these endpoints take no If-Match, so an unconditional delete/edit should win. No API contract change (no new response codes) -> no OpenAPI regen. Still deferred to #197 (cross-editor ETag rotation only, not a 500): the non-bumping config siblings + the scanner-shared Add*ToCollection family. Tests: RootWriterForceVersionTests races a bump *through the handler* via a pre-tracked context (non-vacuous - reverting a handler to plain save fails the test, verified) for the Option-delete / Either-delete / bump+update shapes, plus the genuine-conflict rethrow branch and an explicit negative control proving the plain-save path throws. Full ErsatzTV.Tests green (1482). Also strips a pre-existing UTF-8 BOM from the touched handlers to satisfy the .editorconfig `charset=utf-8` rule the pre-commit format hook enforces. Docs: api-conventions section 7a (fan-out completeness) + decisions.md entry. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
161 lines
6.5 KiB
C#
161 lines
6.5 KiB
C#
using ErsatzTV.Core;
|
|
using ErsatzTV.Core.Domain;
|
|
using ErsatzTV.Core.Interfaces.Repositories;
|
|
using ErsatzTV.Infrastructure.Data;
|
|
using ErsatzTV.Infrastructure.Extensions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace ErsatzTV.Application.MediaCollections;
|
|
|
|
public class AddItemsToPlaylistHandler : IRequestHandler<AddItemsToPlaylist, Either<BaseError, Unit>>
|
|
{
|
|
private readonly IDbContextFactory<TvContext> _dbContextFactory;
|
|
private readonly IMovieRepository _movieRepository;
|
|
private readonly ITelevisionRepository _televisionRepository;
|
|
|
|
public AddItemsToPlaylistHandler(
|
|
IDbContextFactory<TvContext> dbContextFactory,
|
|
IMovieRepository movieRepository,
|
|
ITelevisionRepository televisionRepository)
|
|
{
|
|
_dbContextFactory = dbContextFactory;
|
|
_movieRepository = movieRepository;
|
|
_televisionRepository = televisionRepository;
|
|
}
|
|
|
|
public async Task<Either<BaseError, Unit>> Handle(AddItemsToPlaylist request, CancellationToken cancellationToken)
|
|
{
|
|
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
|
Validation<BaseError, Playlist> validation = await Validate(dbContext, request, cancellationToken);
|
|
return await validation.Apply(c => ApplyAddItemsRequest(dbContext, c, request, cancellationToken));
|
|
}
|
|
|
|
private static async Task<Unit> ApplyAddItemsRequest(
|
|
TvContext dbContext,
|
|
Playlist playlist,
|
|
AddItemsToPlaylist request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var allItems = new Dictionary<CollectionType, List<int>>
|
|
{
|
|
{ CollectionType.Movie, request.MovieIds },
|
|
{ CollectionType.TelevisionShow, request.ShowIds },
|
|
{ CollectionType.TelevisionSeason, request.SeasonIds },
|
|
{ CollectionType.Episode, request.EpisodeIds },
|
|
{ CollectionType.Artist, request.ArtistIds },
|
|
{ CollectionType.MusicVideo, request.MusicVideoIds },
|
|
{ CollectionType.OtherVideo, request.OtherVideoIds },
|
|
{ CollectionType.Song, request.SongIds },
|
|
{ CollectionType.Image, request.ImageIds },
|
|
{ CollectionType.RemoteStream, request.RemoteStreamIds }
|
|
};
|
|
|
|
int index = playlist.Items.Count > 0 ? playlist.Items.Max(i => i.Index) + 1 : 0;
|
|
|
|
foreach ((CollectionType collectionType, List<int> ids) in allItems)
|
|
{
|
|
foreach (int id in ids)
|
|
{
|
|
var item = new PlaylistItem
|
|
{
|
|
Index = index++,
|
|
CollectionType = collectionType,
|
|
MediaItemId = id,
|
|
PlaybackOrder = PlaybackOrder.Shuffle,
|
|
IncludeInProgramGuide = true
|
|
};
|
|
|
|
playlist.Items.Add(item);
|
|
}
|
|
}
|
|
|
|
// Mutates the playlist's editor-visible item list, so bump the concurrency token (issue #253).
|
|
playlist.Version++;
|
|
|
|
await dbContext.SaveChangesForcingVersion(cancellationToken);
|
|
|
|
return Unit.Default;
|
|
}
|
|
|
|
private async Task<Validation<BaseError, Playlist>> Validate(
|
|
TvContext dbContext,
|
|
AddItemsToPlaylist request,
|
|
CancellationToken cancellationToken) =>
|
|
(await PlaylistMustExist(dbContext, request, cancellationToken),
|
|
await ValidateMovies(request),
|
|
await ValidateShows(request),
|
|
await ValidateSeasons(request),
|
|
await ValidateEpisodes(request),
|
|
await ValidateMediaItems(dbContext, request, cancellationToken))
|
|
.Apply((collection, _, _, _, _, _) => collection);
|
|
|
|
private static async Task<Validation<BaseError, Playlist>> PlaylistMustExist(
|
|
TvContext dbContext,
|
|
AddItemsToPlaylist request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Option<Playlist> maybePlaylist = await dbContext.Playlists
|
|
.Include(c => c.Items)
|
|
.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)
|
|
.Map(Optional)
|
|
.Filter(v => v == true)
|
|
.MapT(_ => Unit.Default)
|
|
.Map(v => v.ToValidation<BaseError>("Movie does not exist"));
|
|
|
|
private Task<Validation<BaseError, Unit>> ValidateShows(AddItemsToPlaylist request) =>
|
|
_televisionRepository.AllShowsExist(request.ShowIds)
|
|
.Map(Optional)
|
|
.Filter(v => v == true)
|
|
.MapT(_ => Unit.Default)
|
|
.Map(v => v.ToValidation<BaseError>("Show does not exist"));
|
|
|
|
private Task<Validation<BaseError, Unit>> ValidateSeasons(AddItemsToPlaylist request) =>
|
|
_televisionRepository.AllSeasonsExist(request.SeasonIds)
|
|
.Map(Optional)
|
|
.Filter(v => v == true)
|
|
.MapT(_ => Unit.Default)
|
|
.Map(v => v.ToValidation<BaseError>("Season does not exist"));
|
|
|
|
private Task<Validation<BaseError, Unit>> ValidateEpisodes(AddItemsToPlaylist request) =>
|
|
_televisionRepository.AllEpisodesExist(request.EpisodeIds)
|
|
.Map(Optional)
|
|
.Filter(v => v == true)
|
|
.MapT(_ => Unit.Default)
|
|
.Map(v => v.ToValidation<BaseError>("Episode does not exist"));
|
|
|
|
private static async Task<Validation<BaseError, Unit>> ValidateMediaItems(
|
|
TvContext dbContext,
|
|
AddItemsToPlaylist request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
List<int> ids = GetRequestedMediaItemIds(request).Distinct().ToList();
|
|
int existingCount = await dbContext.MediaItems
|
|
.CountAsync(mi => ids.Contains(mi.Id), cancellationToken);
|
|
|
|
return existingCount == ids.Count
|
|
? Unit.Default
|
|
: BaseError.New("Media item does not exist");
|
|
}
|
|
|
|
private static IEnumerable<int> GetRequestedMediaItemIds(AddItemsToPlaylist request) =>
|
|
request.MovieIds
|
|
.Append(request.ShowIds)
|
|
.Append(request.SeasonIds)
|
|
.Append(request.EpisodeIds)
|
|
.Append(request.ArtistIds)
|
|
.Append(request.MusicVideoIds)
|
|
.Append(request.OtherVideoIds)
|
|
.Append(request.SongIds)
|
|
.Append(request.ImageIds)
|
|
.Append(request.RemoteStreamIds);
|
|
}
|