using ErsatzTV.Application.LibraryBrowse; using ErsatzTV.Core.Api.LibraryBrowse; using ErsatzTV.Core.Api.Search; using MediatR; namespace ErsatzTV.Application.Search; // Fans out to the shared library-browse query once per media kind (mirroring the legacy Search.razor page, // which sends one `type:{kind} AND ({query})` query per kind). Reusing GetLibraryBrowseItems keeps hydration, // artwork resolution and the response shape identical to /api/v1/library/browse. Raw Lucene queries pass through // unchanged, so state filters such as `state:FileNotFound` (the Trash screen) work here too. public class GetSearchResultsHandler(IMediator mediator) : IRequestHandler { public async Task Handle( GetSearchResults request, CancellationToken cancellationToken) { async Task ForKind(LibraryBrowseMediaType kind) { PagedLibraryBrowseItemsResponseModel paged = await mediator.Send( new GetLibraryBrowseItems(request.Query, null, kind, request.PageNum, request.PageSize), cancellationToken); return new SearchResultGroupResponseModel(paged.TotalCount, paged.Page); } // Each ForKind call sends through IMediator to GetLibraryBrowseItemsHandler, which creates its // own TvContext per invocation via IDbContextFactory (never shares one across calls), // so these are safe to run concurrently. Task movies = ForKind(LibraryBrowseMediaType.Movie); Task shows = ForKind(LibraryBrowseMediaType.TelevisionShow); Task seasons = ForKind(LibraryBrowseMediaType.TelevisionSeason); Task artists = ForKind(LibraryBrowseMediaType.Artist); Task episodes = ForKind(LibraryBrowseMediaType.Episode); Task musicVideos = ForKind(LibraryBrowseMediaType.MusicVideo); Task songs = ForKind(LibraryBrowseMediaType.Song); Task otherVideos = ForKind(LibraryBrowseMediaType.OtherVideo); Task images = ForKind(LibraryBrowseMediaType.Image); Task remoteStreams = ForKind(LibraryBrowseMediaType.RemoteStream); await Task.WhenAll( movies, shows, seasons, artists, episodes, musicVideos, songs, otherVideos, images, remoteStreams); return new SearchResultsResponseModel( movies.Result, shows.Result, seasons.Result, artists.Result, episodes.Result, musicVideos.Result, songs.Result, otherVideos.Result, images.Result, remoteStreams.Result); } }