From fc2c054b445bef28114df70f2e48115c294cc3f4 Mon Sep 17 00:00:00 2001 From: Timothy Date: Fri, 10 Jul 2026 23:27:57 +0200 Subject: [PATCH 1/2] fix(api): validate + include RemoteStream in playlist add-items (fixes #217) AddItemsToPlaylistHandler only validated existence for movies/shows/ seasons/episodes, leaving artist/music-video/other-video/song/image/ remote-stream ids unchecked (silently accepted, or in RemoteStream's case silently dropped entirely - the apply dictionary never included CollectionType.RemoteStream). Mirror AddItemsToCollectionHandler's established pattern: add RemoteStream to the apply dictionary, and add an aggregate existence check (ValidateMediaItems/GetRequestedMediaItemIds) across all ten kinds against dbContext.MediaItems. Add ErsatzTV.Tests/Application/MediaCollections/PlaylistHandlerTests.cs covering: a bogus id of each of the ten kinds fails validation; a valid RemoteStream id is actually persisted to the playlist (regression test for the drop bug). Co-Authored-By: Claude Fable 5 --- .../Commands/AddItemsToPlaylistHandler.cs | 34 ++++- .../MediaCollections/PlaylistHandlerTests.cs | 139 ++++++++++++++++++ 2 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 ErsatzTV.Tests/Application/MediaCollections/PlaylistHandlerTests.cs diff --git a/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs b/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs index 98251b91a..fd8586c21 100644 --- a/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs +++ b/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs @@ -46,7 +46,8 @@ public class AddItemsToPlaylistHandler : IRequestHandler 0 ? playlist.Items.Max(i => i.Index) + 1 : 0; @@ -81,8 +82,9 @@ public class AddItemsToPlaylistHandler : IRequestHandler collection); + await ValidateEpisodes(request), + await ValidateMediaItems(dbContext, request, cancellationToken)) + .Apply((collection, _, _, _, _, _) => collection); private static async Task> PlaylistMustExist( TvContext dbContext, @@ -126,4 +128,30 @@ public class AddItemsToPlaylistHandler : IRequestHandler v == true) .MapT(_ => Unit.Default) .Map(v => v.ToValidation("Episode does not exist")); + + private static async Task> ValidateMediaItems( + TvContext dbContext, + AddItemsToPlaylist request, + CancellationToken cancellationToken) + { + List 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 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); } diff --git a/ErsatzTV.Tests/Application/MediaCollections/PlaylistHandlerTests.cs b/ErsatzTV.Tests/Application/MediaCollections/PlaylistHandlerTests.cs new file mode 100644 index 000000000..b0082fcbd --- /dev/null +++ b/ErsatzTV.Tests/Application/MediaCollections/PlaylistHandlerTests.cs @@ -0,0 +1,139 @@ +using ErsatzTV.Application.MediaCollections; +using ErsatzTV.Core; +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Errors; +using ErsatzTV.Core.Interfaces.Repositories; +using ErsatzTV.Infrastructure.Data; +using ErsatzTV.Tests.Support; +using LanguageExt; +using NSubstitute; +using NUnit.Framework; +using Shouldly; +using Unit = LanguageExt.Unit; + +namespace ErsatzTV.Tests.Application.MediaCollections; + +[TestFixture] +public class PlaylistHandlerTests : MediaCollectionHandlerTestBase +{ + [TestCase(CollectionType.Artist)] + [TestCase(CollectionType.MusicVideo)] + [TestCase(CollectionType.OtherVideo)] + [TestCase(CollectionType.Song)] + [TestCase(CollectionType.Image)] + [TestCase(CollectionType.RemoteStream)] + public async Task AddItems_Should_Return_ValidationError_When_Previously_Unvalidated_Kind_Missing( + CollectionType collectionType) + { + await SeedPlaylist(1); + var handler = MakeHandler(); + + Either result = + await handler.Handle(MakeAddItems(1, collectionType, [999]), CancellationToken.None); + + BaseError error = LeftOf(result); + error.ShouldNotBeOfType(); + error.Value.ShouldContain("Media item does not exist"); + } + + [TestCase(CollectionType.Movie)] + [TestCase(CollectionType.TelevisionShow)] + [TestCase(CollectionType.TelevisionSeason)] + [TestCase(CollectionType.Episode)] + public async Task AddItems_Should_Return_ValidationError_When_Existing_Validated_Kind_Missing( + CollectionType collectionType) + { + await SeedPlaylist(1); + var handler = MakeHandler(); + + Either result = + await handler.Handle(MakeAddItems(1, collectionType, [999]), CancellationToken.None); + + BaseError error = LeftOf(result); + error.ShouldNotBeOfType(); + } + + [Test] + public async Task AddItems_Should_Add_Valid_RemoteStream_Item_To_Playlist() + { + await SeedPlaylist(1); + await SeedRemoteStream(50); + var handler = MakeHandler(); + + Either result = + await handler.Handle(MakeAddItems(1, CollectionType.RemoteStream, [50]), CancellationToken.None); + + RightOf(result); + + await using TvContext context = Db.CreateContext(); + Playlist playlist = await context.Playlists.FindAsync(1); + List items = context.Entry(playlist!).Collection(p => p.Items).Query().ToList(); + + items.ShouldHaveSingleItem(); + items[0].CollectionType.ShouldBe(CollectionType.RemoteStream); + items[0].MediaItemId.ShouldBe(50); + } + + private AddItemsToPlaylistHandler MakeHandler() + { + IMovieRepository movieRepository = Substitute.For(); + movieRepository.AllMoviesExist(Arg.Any>()).Returns(true); + ITelevisionRepository televisionRepository = Substitute.For(); + televisionRepository.AllShowsExist(Arg.Any>()).Returns(true); + televisionRepository.AllSeasonsExist(Arg.Any>()).Returns(true); + televisionRepository.AllEpisodesExist(Arg.Any>()).Returns(true); + + return new AddItemsToPlaylistHandler(Db.Factory, movieRepository, televisionRepository); + } + + private async Task SeedPlaylist(int id, string name = "Playlist") + { + await using TvContext context = Db.CreateContext(); + context.Playlists.Add(new Playlist { Id = id, Name = name, Items = [] }); + await context.SaveChangesAsync(); + } + + private async Task SeedRemoteStream(int id) + { + await using TvContext context = Db.CreateContext(); + context.RemoteStreams.Add(new RemoteStream + { + Id = id, + RemoteStreamMetadata = [] + }); + await context.SaveChangesAsync(); + } + + private static AddItemsToPlaylist MakeAddItems(int playlistId, CollectionType collectionType, List ids) + { + List movieIds = collectionType == CollectionType.Movie ? ids : []; + List showIds = collectionType == CollectionType.TelevisionShow ? ids : []; + List seasonIds = collectionType == CollectionType.TelevisionSeason ? ids : []; + List episodeIds = collectionType == CollectionType.Episode ? ids : []; + List artistIds = collectionType == CollectionType.Artist ? ids : []; + List musicVideoIds = collectionType == CollectionType.MusicVideo ? ids : []; + List otherVideoIds = collectionType == CollectionType.OtherVideo ? ids : []; + List songIds = collectionType == CollectionType.Song ? ids : []; + List imageIds = collectionType == CollectionType.Image ? ids : []; + List remoteStreamIds = collectionType == CollectionType.RemoteStream ? ids : []; + + return new AddItemsToPlaylist( + playlistId, + movieIds, + showIds, + seasonIds, + episodeIds, + artistIds, + musicVideoIds, + otherVideoIds, + songIds, + imageIds, + remoteStreamIds); + } + + private static BaseError LeftOf(Either either) => + either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result")); + + private static TR RightOf(Either either) => + either.Match(Left: e => throw new AssertionException($"Expected a Right result, got: {e.Value}"), Right: v => v); +} From 8ddf0ae16932cdf3754719a90e3e6c223e5ebb56 Mon Sep 17 00:00:00 2001 From: Timothy Date: Fri, 10 Jul 2026 23:28:09 +0200 Subject: [PATCH 2/2] fix(api): resolve per-show scan by exact show id, not substring title (fixes #219) POST /api/libraries/{id}/scan-show resolved the target show via GetShowIdByTitle, an EF.Functions.Like "%title%" substring match with no OrderBy - non-deterministic under duplicate/overlapping titles and capable of scanning the wrong show. The Blazor UI never had this bug (it always passed the exact show id); this endpoint shipped days ago in PR #216 with no external consumers, so the contract break is safe. BREAKING CHANGE: ScanShowRequest now takes `showId: int` instead of `showTitle: string`. Replaced ITelevisionRepository.GetShowIdByTitle with GetShowTitle(libraryId, showId), which also enforces the show belongs to the given library. LibrariesController.ScanShow now returns a genuine 404 ProblemDetails (via ApiResults.NotFoundProblem, the established pre-check pattern from TemplateController.DeleteGroup) when the show id doesn't exist in that library, then queues QueueShowScanByLibraryId with the DB-resolved title. SPA: libraries.ts ScanShowParams.showId replaces showTitle; MediaDetailScreen.tsx passes show.id. Extended ApiErrorResponseMetadataTests and OpenApiErrorResponseContractTests with the new 404 contract for ScanShow. Regenerated v1.json / v1.d.ts via scripts/update-openapi.sh + npm run generate:api. Co-Authored-By: Claude Fable 5 --- .../Fakes/FakeTelevisionRepository.cs | 2 +- .../Repositories/ITelevisionRepository.cs | 2 +- .../Data/Repositories/TelevisionRepository.cs | 8 +-- .../ApiErrorResponseMetadataTests.cs | 1 + .../Controllers/LibrariesControllerTests.cs | 45 ++++++++++++++++- .../OpenApiErrorResponseContractTests.cs | 1 + .../Controllers/Api/LibrariesController.cs | 21 ++++---- ErsatzTV/wwwroot/openapi/v1.json | 50 ++++++++++++++++--- web/src/api/generated/v1.d.ts | 2 +- web/src/api/libraries.test.ts | 10 ++-- web/src/api/libraries.ts | 10 ++-- web/src/screens/MediaDetailScreen.test.tsx | 2 +- web/src/screens/MediaDetailScreen.tsx | 2 +- 13 files changed, 118 insertions(+), 38 deletions(-) diff --git a/ErsatzTV.Core.Tests/Fakes/FakeTelevisionRepository.cs b/ErsatzTV.Core.Tests/Fakes/FakeTelevisionRepository.cs index e69ac7432..eb4087d8a 100644 --- a/ErsatzTV.Core.Tests/Fakes/FakeTelevisionRepository.cs +++ b/ErsatzTV.Core.Tests/Fakes/FakeTelevisionRepository.cs @@ -14,7 +14,7 @@ public class FakeTelevisionRepository : ITelevisionRepository public Task> GetAllShows() => throw new NotSupportedException(); public Task> GetShow(int showId, CancellationToken cancellationToken) => throw new NotSupportedException(); - public Task> GetShowIdByTitle(int libraryId, string title) => throw new NotSupportedException(); + public Task> GetShowTitle(int libraryId, int showId) => throw new NotSupportedException(); public Task> GetShowItems(int showId) => throw new NotSupportedException(); public Task> GetEpisodeIdsForShow(int showId) => throw new NotSupportedException(); diff --git a/ErsatzTV.Core/Interfaces/Repositories/ITelevisionRepository.cs b/ErsatzTV.Core/Interfaces/Repositories/ITelevisionRepository.cs index 947802782..3518743c2 100644 --- a/ErsatzTV.Core/Interfaces/Repositories/ITelevisionRepository.cs +++ b/ErsatzTV.Core/Interfaces/Repositories/ITelevisionRepository.cs @@ -10,7 +10,7 @@ public interface ITelevisionRepository Task AllEpisodesExist(List episodeIds); Task> GetAllShows(); Task> GetShow(int showId, CancellationToken cancellationToken); - Task> GetShowIdByTitle(int libraryId, string title); + Task> GetShowTitle(int libraryId, int showId); Task> GetShowItems(int showId); Task> GetEpisodeIdsForShow(int showId); Task> GetAllSeasons(); diff --git a/ErsatzTV.Infrastructure/Data/Repositories/TelevisionRepository.cs b/ErsatzTV.Infrastructure/Data/Repositories/TelevisionRepository.cs index b788851bc..4909612a7 100644 --- a/ErsatzTV.Infrastructure/Data/Repositories/TelevisionRepository.cs +++ b/ErsatzTV.Infrastructure/Data/Repositories/TelevisionRepository.cs @@ -80,16 +80,16 @@ public class TelevisionRepository : ITelevisionRepository .SelectOneAsync(s => s.Id, s => s.Id == showId, cancellationToken); } - public async Task> GetShowIdByTitle(int libraryId, string title) + public async Task> GetShowTitle(int libraryId, int showId) { await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(); return await dbContext.ShowMetadata .AsNoTracking() + .Where(sm => sm.ShowId == showId) .Where(sm => sm.Show.LibraryPath.LibraryId == libraryId) - .Where(sm => EF.Functions.Like(sm.Title, $"%{title}%")) - .Map(sm => sm.ShowId) + .Map(sm => sm.Title) .FirstOrDefaultAsync() - .Map(showId => showId > 0 ? Option.Some(showId) : Option.None); + .Map(Optional); } public async Task> GetEpisodeIdsForShow(int showId) diff --git a/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs b/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs index 7ab30a490..9ed6f5474 100644 --- a/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs +++ b/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs @@ -139,6 +139,7 @@ public class ApiErrorResponseMetadataTests [TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.DeleteProfileAsync), StatusCodes.Status404NotFound)] [TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.DeleteProfileAsync), StatusCodes.Status401Unauthorized)] [TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.DeleteProfileAsync), StatusCodes.Status422UnprocessableEntity)] + [TestCase(typeof(LibrariesController), nameof(LibrariesController.ScanShow), StatusCodes.Status404NotFound)] public void Api_Error_Response_Metadata_Should_Document_ProblemDetails( Type controllerType, string actionName, diff --git a/ErsatzTV.Tests/Controllers/LibrariesControllerTests.cs b/ErsatzTV.Tests/Controllers/LibrariesControllerTests.cs index 95d67c9a0..0971c747c 100644 --- a/ErsatzTV.Tests/Controllers/LibrariesControllerTests.cs +++ b/ErsatzTV.Tests/Controllers/LibrariesControllerTests.cs @@ -3,7 +3,10 @@ using ErsatzTV.Application.Libraries; using ErsatzTV.Controllers.Api; using ErsatzTV.Core.Api.Libraries; using ErsatzTV.Core.Interfaces.Repositories; +using LanguageExt; using MediatR; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; using NSubstitute; using NUnit.Framework; @@ -16,12 +19,14 @@ public class LibrariesControllerTests { private LibrariesController _controller = null!; private IMediator _mediator = null!; + private ITelevisionRepository _televisionRepository = null!; [SetUp] public void SetUp() { _mediator = Substitute.For(); - _controller = new LibrariesController(Substitute.For(), _mediator); + _televisionRepository = Substitute.For(); + _controller = new LibrariesController(_televisionRepository, _mediator); } [Test] @@ -52,4 +57,42 @@ public class LibrariesControllerTests result.ShouldBe(expected); } + + [Test] + public async Task ScanShow_Should_Return_NotFoundProblem_When_Show_Not_In_Library() + { + _televisionRepository.GetShowTitle(3, 999).Returns(Option.None); + + IActionResult result = await _controller.ScanShow(3, new ScanShowRequest(999)); + + var notFound = result.ShouldBeOfType(); + notFound.Value.ShouldBeOfType().Status.ShouldBe(StatusCodes.Status404NotFound); + await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); + } + + [Test] + public async Task ScanShow_Should_Queue_Scan_By_Show_Id_When_Show_Belongs_To_Library() + { + _televisionRepository.GetShowTitle(3, 42).Returns(Option.Some("The Office")); + _mediator.Send(Arg.Any(), Arg.Any()).Returns(true); + + IActionResult result = await _controller.ScanShow(3, new ScanShowRequest(42, DeepScan: true)); + + result.ShouldBeOfType(); + await _mediator.Received(1).Send( + Arg.Is(r => + r.LibraryId == 3 && r.ShowId == 42 && r.ShowTitle == "The Office" && r.DeepScan), + Arg.Any()); + } + + [Test] + public async Task ScanShow_Should_Return_BadRequest_When_Mediator_Fails_To_Queue() + { + _televisionRepository.GetShowTitle(3, 42).Returns(Option.Some("The Office")); + _mediator.Send(Arg.Any(), Arg.Any()).Returns(false); + + IActionResult result = await _controller.ScanShow(3, new ScanShowRequest(42)); + + result.ShouldBeOfType(); + } } diff --git a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs index a24049ea0..aeb42758c 100644 --- a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs +++ b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs @@ -260,6 +260,7 @@ public class OpenApiErrorResponseContractTests [TestCase("/api/trakt/lists/{id}", "put", "404")] [TestCase("/api/trakt/lists/{id}", "put", "422")] [TestCase("/api/troubleshoot/playback/subtitles/{mediaItemId}", "get", "404")] + [TestCase("/api/libraries/{id}/scan-show", "post", "404")] public void Static_OpenApi_Should_Document_ProblemDetails_For_Api_Error_Responses( string path, string method, diff --git a/ErsatzTV/Controllers/Api/LibrariesController.cs b/ErsatzTV/Controllers/Api/LibrariesController.cs index 15878394b..844a73859 100644 --- a/ErsatzTV/Controllers/Api/LibrariesController.cs +++ b/ErsatzTV/Controllers/Api/LibrariesController.cs @@ -1,6 +1,7 @@ using ErsatzTV.Application.Libraries; using ErsatzTV.Core.Api.Libraries; using ErsatzTV.Core.Interfaces.Repositories; +using ErsatzTV.Extensions; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -29,27 +30,23 @@ public class LibrariesController(ITelevisionRepository televisionRepository, IMe [HttpPost("/api/libraries/{id:int}/scan-show")] [Tags("Libraries")] [EndpointSummary("Scan show")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task ScanShow(int id, [FromBody] ScanShowRequest request) { - if (string.IsNullOrWhiteSpace(request.ShowTitle)) + Option maybeTitle = await televisionRepository.GetShowTitle(id, request.ShowId); + foreach (string title in maybeTitle) { - return new BadRequestObjectResult(new { error = "ShowTitle is required" }); - } - - string trimmedTitle = request.ShowTitle.Trim(); - Option maybeShowId = await televisionRepository.GetShowIdByTitle(id, trimmedTitle); - foreach (int showId in maybeShowId) - { - bool result = await mediator.Send(new QueueShowScanByLibraryId(id, showId, trimmedTitle, request.DeepScan)); + bool result = await mediator.Send(new QueueShowScanByLibraryId(id, request.ShowId, title, request.DeepScan)); return result ? new OkResult() : new BadRequestObjectResult(new { error = "Unable to queue show scan. Library may not exist, may not support single show scanning, or may already be scanning." }); } - return new BadRequestObjectResult( - new { error = $"Unable to locate show with title {request.ShowTitle} in library {id}" }); + return ApiResults.NotFoundProblem($"Show {request.ShowId} does not exist in library {id}."); } } -public record ScanShowRequest(string ShowTitle, bool DeepScan = false); +public record ScanShowRequest(int ShowId, bool DeepScan = false); diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json index 847e90c5a..7d1af9f06 100644 --- a/ErsatzTV/wwwroot/openapi/v1.json +++ b/ErsatzTV/wwwroot/openapi/v1.json @@ -5317,6 +5317,46 @@ "responses": { "200": { "description": "OK" + }, + "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" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } } } } @@ -20790,15 +20830,13 @@ }, "ScanShowRequest": { "required": [ - "showTitle" + "showId" ], "type": "object", "properties": { - "showTitle": { - "type": [ - "null", - "string" - ] + "showId": { + "type": "integer", + "format": "int32" }, "deepScan": { "type": "boolean", diff --git a/web/src/api/generated/v1.d.ts b/web/src/api/generated/v1.d.ts index 9c9024447..7bd68ccd1 100644 --- a/web/src/api/generated/v1.d.ts +++ b/web/src/api/generated/v1.d.ts @@ -1280,7 +1280,7 @@ export interface components { "libraryRefreshInterval": number; }; "ScanShowRequest": { - "showTitle": null | string; + "showId": number; "deepScan"?: boolean; }; "ScheduleItemRequest": { diff --git a/web/src/api/libraries.test.ts b/web/src/api/libraries.test.ts index f50fa5436..349f26bb0 100644 --- a/web/src/api/libraries.test.ts +++ b/web/src/api/libraries.test.ts @@ -22,19 +22,19 @@ describe('libraries api client', () => { expect(fetchMock).toHaveBeenCalledWith('/api/libraries/4/scan', expect.objectContaining({ method: 'POST' })); }); - it('scanShow POSTs the show title and deepScan flag', async () => { + it('scanShow POSTs the show id and deepScan flag', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent()); - await scanShow(4, { deepScan: true, showTitle: 'The Office' }); + await scanShow(4, { deepScan: true, showId: 42 }); const { init, url } = lastCall(fetchMock); expect(url).toBe('/api/libraries/4/scan-show'); expect(init?.method).toBe('POST'); - expect(JSON.parse(String(init?.body))).toEqual({ deepScan: true, showTitle: 'The Office' }); + expect(JSON.parse(String(init?.body))).toEqual({ deepScan: true, showId: 42 }); }); it('scanShow defaults deepScan to false when omitted', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent()); - await scanShow(9, { showTitle: 'Firefly' }); + await scanShow(9, { showId: 17 }); const { init } = lastCall(fetchMock); - expect(JSON.parse(String(init?.body))).toEqual({ deepScan: false, showTitle: 'Firefly' }); + expect(JSON.parse(String(init?.body))).toEqual({ deepScan: false, showId: 17 }); }); }); diff --git a/web/src/api/libraries.ts b/web/src/api/libraries.ts index 0def1f765..b2b1e0d01 100644 --- a/web/src/api/libraries.ts +++ b/web/src/api/libraries.ts @@ -52,16 +52,16 @@ export function scanLibrary(libraryId: number): Promise { } export interface ScanShowParams { - showTitle: string; + showId: number; deepScan?: boolean; } -// Queues a scan of a single show (by title) within a library. Returns 200 on success, 400 when -// the title can't be resolved / the library doesn't support single-show scanning. Body keys are -// `showTitle` and `deepScan` (see LibrariesController.ScanShowRequest). +// Queues a scan of a single show (by id) within a library. Returns 200 on success, 404 when the +// show id doesn't exist in the library, 400 when the library doesn't support single-show +// scanning. Body keys are `showId` and `deepScan` (see LibrariesController.ScanShowRequest). export function scanShow(libraryId: number, params: ScanShowParams): Promise { return request(`/api/libraries/${libraryId}/scan-show`, { - body: { deepScan: params.deepScan ?? false, showTitle: params.showTitle }, + body: { deepScan: params.deepScan ?? false, showId: params.showId }, method: 'POST' }); } diff --git a/web/src/screens/MediaDetailScreen.test.tsx b/web/src/screens/MediaDetailScreen.test.tsx index a36d80dbd..c0b97538c 100644 --- a/web/src/screens/MediaDetailScreen.test.tsx +++ b/web/src/screens/MediaDetailScreen.test.tsx @@ -154,7 +154,7 @@ describe('media detail screens', () => { const scanCall = fetchSpy.mock.calls.find(([url]) => String(url) === '/api/libraries/3/scan-show'); expect(scanCall).toBeTruthy(); const body = JSON.parse(String((scanCall![1] as RequestInit).body)); - expect(body).toMatchObject({ deepScan: true, showTitle: 'The Show' }); + expect(body).toMatchObject({ deepScan: true, showId: 42 }); }); await waitFor(() => expect(screen.getByText('Scan queued')).toBeInTheDocument()); }); diff --git a/web/src/screens/MediaDetailScreen.tsx b/web/src/screens/MediaDetailScreen.tsx index 14e8c8aaa..e6490ff4b 100644 --- a/web/src/screens/MediaDetailScreen.tsx +++ b/web/src/screens/MediaDetailScreen.tsx @@ -584,7 +584,7 @@ function ShowScanControls({ show }: { show: ShowDetail }) { const runScan = (deepScan: boolean) => { setScanning(deepScan ? 'deep' : 'quick'); setMessage(null); - scanShow(show.libraryId, { deepScan, showTitle: show.title }) + scanShow(show.libraryId, { deepScan, showId: show.id }) .then(() => { if (activeRef.current) { setScanning(false);