Compare commits
96
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf85bf3093 | ||
|
|
72fc8cc850 | ||
|
|
f869dfe87a | ||
|
|
311411fa38 | ||
|
|
a7d3fc3055 | ||
|
|
316b673c3b | ||
|
|
9f73542296 | ||
|
|
6902f559f0 | ||
|
|
0290594f0b | ||
|
|
50ae0a7f3b | ||
|
|
dbda2d8991 | ||
|
|
685894517d | ||
|
|
d5aa838b22 | ||
|
|
cd31c755bb | ||
|
|
1c883ac601 | ||
|
|
d2096c0675 | ||
|
|
822f3692dc | ||
|
|
ec7531d821 | ||
|
|
7787b17495 | ||
|
|
f0a423c2de | ||
|
|
3ec3ab5fe0 | ||
|
|
82d3b586f2 | ||
|
|
d05e442605 | ||
|
|
54b18e73cd | ||
|
|
e58da21a56 | ||
|
|
a709dccec7 | ||
|
|
c480fbe8d5 | ||
|
|
d7617b7456 | ||
|
|
fb76f34fc6 | ||
|
|
0bc74f9b1d | ||
|
|
4f472134fb | ||
|
|
ca3fe0c87b | ||
|
|
50b13afac3 | ||
|
|
4ea5273770 | ||
|
|
c745d01a2c | ||
|
|
0d9504c16b | ||
|
|
2b54a2d591 | ||
|
|
cda5c12e34 | ||
|
|
0c355e1132 | ||
|
|
d71a609b4f | ||
|
|
4c215f6f73 | ||
|
|
a52939f292 | ||
|
|
57bb320af8 | ||
|
|
86f280f9d0 | ||
|
|
d48e48f1be | ||
|
|
0299293e14 | ||
|
|
2071858523 | ||
|
|
a0521cd6dc | ||
|
|
0203b5b154 | ||
|
|
ae10eba4d7 | ||
|
|
3b7d5fd5a1 | ||
|
|
e3f2cd631a | ||
|
|
a20fef6096 | ||
|
|
1e34e00e31 | ||
|
|
a228927b4f | ||
|
|
ecd9d526d0 | ||
|
|
6b5bc8e29a | ||
|
|
f06bc064a0 | ||
|
|
15f2beb7f9 | ||
|
|
605b325370 | ||
|
|
9b7718fd7c | ||
|
|
5f202a2175 | ||
|
|
e00b7e4d11 | ||
|
|
3c37ec5f38 | ||
|
|
f1fae6397e | ||
|
|
72b6d0a76a | ||
|
|
117afa310e | ||
|
|
7c4cf55715 | ||
|
|
7083301ce6 | ||
|
|
14cafca740 | ||
|
|
cf21f889bf | ||
|
|
063dae731f | ||
|
|
9c03184707 | ||
|
|
6c68c291a0 | ||
|
|
1b9d85896c | ||
|
|
e2663758e1 | ||
|
|
5c932fdc54 | ||
|
|
4306b39ef8 | ||
|
|
e0f36a12fb | ||
|
|
66abb24402 | ||
|
|
7454411dee | ||
|
|
bef33c2950 | ||
|
|
e95eed11dd | ||
|
|
46c8c2e2dc | ||
|
|
e0a860e577 | ||
|
|
24a26cbe34 | ||
|
|
5530db7089 | ||
|
|
bb34014a07 | ||
|
|
dfa561a97e | ||
|
|
6e091c98ae | ||
|
|
22fa3ecb08 | ||
|
|
d58deddc48 | ||
|
|
5995707c84 | ||
|
|
fcdecd16c0 | ||
|
|
2b09bffab8 | ||
|
|
39455a96ed |
@@ -5,7 +5,7 @@ Custom IPTV channel server for Jellyfin. Forked from [ErsatzTV/ErsatzTV](https:/
|
||||
## Architecture
|
||||
|
||||
- **Language**: C# / .NET 10
|
||||
- **UI**: ChicoryTV React SPA (`web/`, Vite, served at `/app`) over the REST API — the default UI; root `/` and migrated legacy routes 302 there (`ErsatzTV/LegacyUiRedirects.cs`). The legacy Blazor Server UI (MudBlazor) still serves un-migrated admin screens (collections, media browse, trakt, filler, watermarks, ffmpeg profiles, blocks/decos/templates, playout editors, logs, troubleshooting; Blazor home = `/system/health`); its removal is #91 phase (b), gated on parity issues #140–#147
|
||||
- **UI**: ChicoryTV React SPA (`web/`, Vite, served at `/app`) over the REST API — the default UI; root `/` and migrated legacy routes 302 there (`ErsatzTV/LegacyUiRedirects.cs`). The legacy Blazor Server UI (MudBlazor) still serves the remaining un-migrated admin screens — playback troubleshooting, multi/rerun collections, and playlist editing depth; Blazor home = `/system/health`, reachable via the Settings → System "Classic UI" link. Media detail pages + image folder browser landed in the SPA via #141 (PR #183); its removal is #91 phase (b), gated on #145 (playback troubleshooting) and API gaps #151/#152/#153/#155 (scheduling parity #144/#162 DONE 2026-07-07: blocks/templates/decos/deco-templates/playout editors all in the SPA; #141/#158/#161/#180 also DONE)
|
||||
- **Pattern**: CQRS via MediatR — queries/commands in `ErsatzTV.Application/`
|
||||
- **Database**: EF Core (SQLite default, MySQL optional) — context in `ErsatzTV.Infrastructure/Data/TvContext.cs`
|
||||
- **Media**: FFmpeg via CliWrap, SkiaSharp for logo generation
|
||||
@@ -56,6 +56,7 @@ docker build -f docker/Dockerfile -t ersatztv:dev .
|
||||
## Conventions
|
||||
|
||||
- **Read [`docs/contributing.md`](docs/contributing.md)** before non-trivial changes — it documents the established patterns (layering, CQRS handlers, LanguageExt, Blazor/MudBlazor, EF Core + dual-provider migrations, the FFmpeg pipeline, analyzers, testing) and the **deviation policy**: match the established style; diverge only with a concrete, stated reason.
|
||||
- **Convention docs replace re-recon**: before API/SPA/E2E/parity work, read `docs/README.md` (index) → `docs/api-conventions.md`, `docs/spa-conventions.md`, `docs/e2e-local.md`, `docs/domain-model.md`, `docs/blazor-route-parity.md`, `docs/decisions.md`. Any PR that changes a convention, migrates a route, or reverses a decision MUST update the relevant doc in the same PR.
|
||||
- Follow existing MediatR CQRS pattern for new features
|
||||
- Domain logic in `ErsatzTV.Core`, infrastructure in `ErsatzTV.Infrastructure`
|
||||
- Keep UI thin: the SPA talks to `/api/*` only; legacy Blazor pages delegate to MediatR handlers. New screens go in the SPA (`web/`), never in Blazor
|
||||
|
||||
@@ -52,13 +52,17 @@ internal static class Mapper
|
||||
ffmpegProfile.Id,
|
||||
ffmpegProfile.Name,
|
||||
ffmpegProfile.ThreadCount,
|
||||
ffmpegProfile.NormalizeAudio,
|
||||
ffmpegProfile.NormalizeVideo,
|
||||
ffmpegProfile.HardwareAcceleration,
|
||||
ffmpegProfile.VaapiDisplay,
|
||||
ffmpegProfile.VaapiDriver,
|
||||
ffmpegProfile.VaapiDevice,
|
||||
ffmpegProfile.QsvExtraHardwareFrames,
|
||||
ffmpegProfile.ResolutionId,
|
||||
ffmpegProfile.Resolution.Name,
|
||||
ffmpegProfile.ScalingBehavior,
|
||||
ffmpegProfile.PadMode,
|
||||
ffmpegProfile.VideoFormat,
|
||||
ffmpegProfile.VideoProfile,
|
||||
ffmpegProfile.VideoPreset,
|
||||
@@ -71,8 +75,10 @@ internal static class Mapper
|
||||
ffmpegProfile.AudioBitrate,
|
||||
ffmpegProfile.AudioBufferSize,
|
||||
ffmpegProfile.NormalizeLoudnessMode,
|
||||
ffmpegProfile.TargetLoudness,
|
||||
ffmpegProfile.AudioChannels,
|
||||
ffmpegProfile.AudioSampleRate,
|
||||
ffmpegProfile.NormalizeFramerate,
|
||||
ffmpegProfile.DeinterlaceVideo);
|
||||
ffmpegProfile.NormalizeColors,
|
||||
ffmpegProfile.DeinterlaceVideo == true);
|
||||
}
|
||||
|
||||
@@ -20,4 +20,6 @@ public record CreateFillerPreset(
|
||||
int? PlaylistId,
|
||||
string Expression,
|
||||
bool UseChaptersAsMediaItems
|
||||
) : IRequest<Either<BaseError, Unit>>;
|
||||
) : IRequest<Either<BaseError, CreateFillerPresetResult>>;
|
||||
|
||||
public record CreateFillerPresetResult(int FillerPresetId) : EntityIdResult(FillerPresetId);
|
||||
|
||||
@@ -6,23 +6,25 @@ using Microsoft.EntityFrameworkCore;
|
||||
namespace ErsatzTV.Application.Filler;
|
||||
|
||||
public class CreateFillerPresetHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
: IRequestHandler<CreateFillerPreset, Either<BaseError, Unit>>
|
||||
: IRequestHandler<CreateFillerPreset, Either<BaseError, CreateFillerPresetResult>>
|
||||
{
|
||||
public async Task<Either<BaseError, Unit>> Handle(CreateFillerPreset request, CancellationToken cancellationToken)
|
||||
public async Task<Either<BaseError, CreateFillerPresetResult>> Handle(
|
||||
CreateFillerPreset request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
Validation<BaseError, FillerPreset> validation = await Validate(dbContext, request);
|
||||
return await validation.Apply(fp => Persist(dbContext, fp, cancellationToken));
|
||||
}
|
||||
|
||||
private static async Task<Unit> Persist(
|
||||
private static async Task<CreateFillerPresetResult> Persist(
|
||||
TvContext dbContext,
|
||||
FillerPreset fillerPreset,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await dbContext.FillerPresets.AddAsync(fillerPreset, cancellationToken);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return Unit.Default;
|
||||
return new CreateFillerPresetResult(fillerPreset.Id);
|
||||
}
|
||||
|
||||
private static Task<Validation<BaseError, FillerPreset>> Validate(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain.Filler;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -18,8 +19,14 @@ public class DeleteFillerPresetHandler : IRequestHandler<DeleteFillerPreset, Eit
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
Validation<BaseError, FillerPreset> validation = await FillerPresetMustExist(dbContext, request, cancellationToken);
|
||||
return await validation.Apply(ps => DoDeletion(dbContext, ps));
|
||||
Option<FillerPreset> maybeFillerPreset = await FillerPresetMustExist(dbContext, request, cancellationToken);
|
||||
|
||||
// must-exist maps to a NotFoundError Either directly (not via Validation, which
|
||||
// aggregates errors and loses the subtype the API layer maps to 404)
|
||||
return await maybeFillerPreset.Match(
|
||||
Some: fillerPreset => DoDeletion(dbContext, fillerPreset).Map(Right<BaseError, Unit>),
|
||||
None: () => Task.FromResult<Either<BaseError, Unit>>(
|
||||
new NotFoundError($"FillerPreset {request.FillerPresetId} does not exist.")));
|
||||
}
|
||||
|
||||
private static Task<Unit> DoDeletion(TvContext dbContext, FillerPreset fillerPreset)
|
||||
@@ -28,11 +35,10 @@ public class DeleteFillerPresetHandler : IRequestHandler<DeleteFillerPreset, Eit
|
||||
return dbContext.SaveChangesAsync().ToUnit();
|
||||
}
|
||||
|
||||
private static Task<Validation<BaseError, FillerPreset>> FillerPresetMustExist(
|
||||
private static Task<Option<FillerPreset>> FillerPresetMustExist(
|
||||
TvContext dbContext,
|
||||
DeleteFillerPreset request,
|
||||
CancellationToken cancellationToken) =>
|
||||
dbContext.FillerPresets
|
||||
.SelectOneAsync(fp => fp.Id, ps => ps.Id == request.FillerPresetId, cancellationToken)
|
||||
.Map(o => o.ToValidation<BaseError>($"FillerPreset {request.FillerPresetId} does not exist."));
|
||||
.SelectOneAsync(fp => fp.Id, ps => ps.Id == request.FillerPresetId, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain.Filler;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -12,8 +13,19 @@ public class UpdateFillerPresetHandler(IDbContextFactory<TvContext> dbContextFac
|
||||
public async Task<Either<BaseError, Unit>> Handle(UpdateFillerPreset request, CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
Validation<BaseError, FillerPreset> validation = await Validate(dbContext, request, cancellationToken);
|
||||
return await validation.Apply(ps => ApplyUpdateRequest(dbContext, ps, request, cancellationToken));
|
||||
Option<FillerPreset> maybeFillerPreset = await FillerPresetMustExist(dbContext, request, cancellationToken);
|
||||
|
||||
// must-exist maps to a NotFoundError Either directly (not via Validation, which
|
||||
// aggregates errors and loses the subtype the API layer maps to 404)
|
||||
return await maybeFillerPreset.Match(
|
||||
Some: async fillerPreset =>
|
||||
{
|
||||
Validation<BaseError, string> validation = await ValidateName(dbContext, request);
|
||||
return await validation.Apply((string _) =>
|
||||
ApplyUpdateRequest(dbContext, fillerPreset, request, cancellationToken));
|
||||
},
|
||||
None: () => Task.FromResult<Either<BaseError, Unit>>(
|
||||
new NotFoundError($"FillerPreset {request.Id} does not exist.")));
|
||||
}
|
||||
|
||||
private static async Task<Unit> ApplyUpdateRequest(
|
||||
@@ -44,20 +56,12 @@ public class UpdateFillerPresetHandler(IDbContextFactory<TvContext> dbContextFac
|
||||
return Unit.Default;
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, FillerPreset>> Validate(
|
||||
TvContext dbContext,
|
||||
UpdateFillerPreset request,
|
||||
CancellationToken cancellationToken) =>
|
||||
(await FillerPresetMustExist(dbContext, request, cancellationToken), await ValidateName(dbContext, request))
|
||||
.Apply((collectionToUpdate, _) => collectionToUpdate);
|
||||
|
||||
private static Task<Validation<BaseError, FillerPreset>> FillerPresetMustExist(
|
||||
private static Task<Option<FillerPreset>> FillerPresetMustExist(
|
||||
TvContext dbContext,
|
||||
UpdateFillerPreset request,
|
||||
CancellationToken cancellationToken) =>
|
||||
dbContext.FillerPresets
|
||||
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.Id, cancellationToken)
|
||||
.Map(o => o.ToValidation<BaseError>("Filler preset does not exist"));
|
||||
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.Id, cancellationToken);
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -8,6 +8,25 @@ internal static class Mapper
|
||||
internal static FillerPresetResponseModel ProjectToResponseModel(FillerPreset fillerPreset) =>
|
||||
new(fillerPreset.Id, fillerPreset.Name);
|
||||
|
||||
internal static FillerPresetFullResponseModel ProjectToFullResponseModel(FillerPreset fillerPreset) =>
|
||||
new(
|
||||
fillerPreset.Id,
|
||||
fillerPreset.Name,
|
||||
fillerPreset.FillerKind,
|
||||
fillerPreset.FillerMode,
|
||||
fillerPreset.Duration,
|
||||
fillerPreset.Count,
|
||||
fillerPreset.PadToNearestMinute,
|
||||
fillerPreset.AllowWatermarks,
|
||||
fillerPreset.CollectionType,
|
||||
fillerPreset.CollectionId,
|
||||
fillerPreset.MediaItemId,
|
||||
fillerPreset.MultiCollectionId,
|
||||
fillerPreset.SmartCollectionId,
|
||||
fillerPreset.PlaylistId,
|
||||
fillerPreset.Expression,
|
||||
fillerPreset.UseChaptersAsMediaItems);
|
||||
|
||||
internal static FillerPresetViewModel ProjectToViewModel(FillerPreset fillerPreset) =>
|
||||
new(
|
||||
fillerPreset.Id,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
using ErsatzTV.Core.Api.Filler;
|
||||
|
||||
namespace ErsatzTV.Application.Filler;
|
||||
|
||||
public record GetFillerPresetByIdForApi(int Id) : IRequest<Option<FillerPresetFullResponseModel>>;
|
||||
@@ -0,0 +1,22 @@
|
||||
using ErsatzTV.Core.Api.Filler;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static ErsatzTV.Application.Filler.Mapper;
|
||||
|
||||
namespace ErsatzTV.Application.Filler;
|
||||
|
||||
public class GetFillerPresetByIdForApiHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
: IRequestHandler<GetFillerPresetByIdForApi, Option<FillerPresetFullResponseModel>>
|
||||
{
|
||||
public async Task<Option<FillerPresetFullResponseModel>> Handle(
|
||||
GetFillerPresetByIdForApi request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await dbContext.FillerPresets
|
||||
.AsNoTracking()
|
||||
.SelectOneAsync(fp => fp.Id, fp => fp.Id == request.Id, cancellationToken)
|
||||
.MapT(ProjectToFullResponseModel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace ErsatzTV.Application.Images;
|
||||
|
||||
public record ImageFolderExists(int LibraryFolderId) : IRequest<bool>;
|
||||
@@ -0,0 +1,21 @@
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ErsatzTV.Application.Images;
|
||||
|
||||
public class ImageFolderExistsHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
: IRequestHandler<ImageFolderExists, bool>
|
||||
{
|
||||
public async Task<bool> Handle(ImageFolderExists request, CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
return await dbContext.LibraryFolders
|
||||
.AsNoTracking()
|
||||
.AnyAsync(
|
||||
lf => lf.Id == request.LibraryFolderId
|
||||
&& lf.LibraryPath.Library.MediaKind == LibraryMediaKind.Images,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
using ErsatzTV.Core.Api.LibraryBrowse;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Emby;
|
||||
using ErsatzTV.Core.Jellyfin;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using Flurl;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ErsatzTV.Application.LibraryBrowse;
|
||||
|
||||
// Shared MediaItem -> LibraryBrowseItemResponseModel projection used by both the library-browse
|
||||
// search handler and the collection-items handler (#155). Keeping the per-kind hydration and the
|
||||
// rooted-artwork logic in one place avoids duplicating the Blazor-vs-SPA artwork rooting rules
|
||||
// (see the Artwork helper below and docs/api-conventions.md §4).
|
||||
internal static class LibraryBrowseItemMapper
|
||||
{
|
||||
// Hydrates an arbitrary set of media item ids (any kinds mixed) into response models. MediaItem
|
||||
// ids are globally unique across kinds, so passing the full id list to every per-kind query is
|
||||
// safe: each query only matches its own kind. Callers order/page the result themselves.
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> HydrateMediaItemsByIds(
|
||||
TvContext dbContext,
|
||||
IReadOnlyList<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var idList = ids.Distinct().ToList();
|
||||
|
||||
var results = new List<LibraryBrowseItemResponseModel>();
|
||||
results.AddRange(await GetMovies(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetShows(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetSeasons(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetArtists(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetEpisodes(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetMusicVideos(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetSongs(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetOtherVideos(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetImages(dbContext, idList, cancellationToken));
|
||||
results.AddRange(await GetRemoteStreams(dbContext, idList, cancellationToken));
|
||||
return results;
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetMovies(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.MovieMetadata
|
||||
.AsNoTracking()
|
||||
.Where(mm => ids.Contains(mm.MovieId))
|
||||
.Include(mm => mm.Artwork)
|
||||
.Include(mm => mm.Movie)
|
||||
.ThenInclude(m => m.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(mm => mm.Movie)
|
||||
.ThenInclude(m => m.MediaVersions)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(mm => mm.MovieId)
|
||||
.Select(g => g.OrderBy(mm => mm.Id).First())
|
||||
.Map(mm => new LibraryBrowseItemResponseModel(
|
||||
mm.MovieId,
|
||||
LibraryBrowseMediaType.Movie,
|
||||
mm.Title ?? string.Empty,
|
||||
mm.Movie.LibraryPath.LibraryId,
|
||||
mm.Movie.LibraryPath.Library.Name,
|
||||
Artwork(mm, ArtworkKind.Poster),
|
||||
BestDuration(mm.Movie.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.Movie,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
mm.MovieId,
|
||||
null)).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetShows(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
Dictionary<int, int> counts = await dbContext.Episodes
|
||||
.AsNoTracking()
|
||||
.Where(e => ids.Contains(e.Season.ShowId))
|
||||
.GroupBy(e => e.Season.ShowId)
|
||||
.Select(g => new { ShowId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(g => g.ShowId, g => g.Count, cancellationToken);
|
||||
|
||||
return await dbContext.ShowMetadata
|
||||
.AsNoTracking()
|
||||
.Where(sm => ids.Contains(sm.ShowId))
|
||||
.Include(sm => sm.Artwork)
|
||||
.Include(sm => sm.Show)
|
||||
.ThenInclude(s => s.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(sm => sm.ShowId)
|
||||
.Select(g => g.OrderBy(sm => sm.Id).First())
|
||||
.Map(sm => new LibraryBrowseItemResponseModel(
|
||||
sm.ShowId,
|
||||
LibraryBrowseMediaType.TelevisionShow,
|
||||
sm.Title ?? string.Empty,
|
||||
sm.Show.LibraryPath.LibraryId,
|
||||
sm.Show.LibraryPath.Library.Name,
|
||||
Artwork(sm, ArtworkKind.Poster),
|
||||
null,
|
||||
counts.TryGetValue(sm.ShowId, out int count) ? count : 0,
|
||||
null,
|
||||
CollectionType.TelevisionShow,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sm.ShowId,
|
||||
null)).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetSeasons(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
Dictionary<int, int> counts = await dbContext.Episodes
|
||||
.AsNoTracking()
|
||||
.Where(e => ids.Contains(e.SeasonId))
|
||||
.GroupBy(e => e.SeasonId)
|
||||
.Select(g => new { SeasonId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(g => g.SeasonId, g => g.Count, cancellationToken);
|
||||
|
||||
return await dbContext.SeasonMetadata
|
||||
.AsNoTracking()
|
||||
.Where(sm => ids.Contains(sm.SeasonId))
|
||||
.Include(sm => sm.Artwork)
|
||||
.Include(sm => sm.Season)
|
||||
.ThenInclude(s => s.Show)
|
||||
.ThenInclude(s => s.ShowMetadata)
|
||||
.ThenInclude(shm => shm.Artwork)
|
||||
.Include(sm => sm.Season)
|
||||
.ThenInclude(s => s.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(sm => sm.SeasonId)
|
||||
.Select(g => g.OrderBy(sm => sm.Id).First())
|
||||
.Map(sm => new LibraryBrowseItemResponseModel(
|
||||
sm.SeasonId,
|
||||
LibraryBrowseMediaType.TelevisionSeason,
|
||||
SeasonTitle(sm),
|
||||
sm.Season.LibraryPath.LibraryId,
|
||||
sm.Season.LibraryPath.Library.Name,
|
||||
SeasonArtwork(sm),
|
||||
null,
|
||||
counts.TryGetValue(sm.SeasonId, out int count) ? count : 0,
|
||||
null,
|
||||
CollectionType.TelevisionSeason,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sm.SeasonId,
|
||||
null)).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetArtists(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
Dictionary<int, int> counts = await dbContext.MusicVideos
|
||||
.AsNoTracking()
|
||||
.Where(mv => ids.Contains(mv.ArtistId))
|
||||
.GroupBy(mv => mv.ArtistId)
|
||||
.Select(g => new { ArtistId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(g => g.ArtistId, g => g.Count, cancellationToken);
|
||||
|
||||
return await dbContext.ArtistMetadata
|
||||
.AsNoTracking()
|
||||
.Where(am => ids.Contains(am.ArtistId))
|
||||
.Include(am => am.Artwork)
|
||||
.Include(am => am.Artist)
|
||||
.ThenInclude(a => a.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(am => am.ArtistId)
|
||||
.Select(g => g.OrderBy(am => am.Id).First())
|
||||
.Map(am => new LibraryBrowseItemResponseModel(
|
||||
am.ArtistId,
|
||||
LibraryBrowseMediaType.Artist,
|
||||
am.Title ?? string.Empty,
|
||||
am.Artist.LibraryPath.LibraryId,
|
||||
am.Artist.LibraryPath.Library.Name,
|
||||
Artwork(am, ArtworkKind.Thumbnail),
|
||||
null,
|
||||
counts.TryGetValue(am.ArtistId, out int count) ? count : 0,
|
||||
null,
|
||||
CollectionType.Artist,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
am.ArtistId,
|
||||
null)).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetEpisodes(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.EpisodeMetadata
|
||||
.AsNoTracking()
|
||||
.Where(em => ids.Contains(em.EpisodeId))
|
||||
.Include(em => em.Artwork)
|
||||
.Include(em => em.Episode)
|
||||
.ThenInclude(e => e.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(em => em.Episode)
|
||||
.ThenInclude(e => e.MediaVersions)
|
||||
.Include(em => em.Episode)
|
||||
.ThenInclude(e => e.Season)
|
||||
.ThenInclude(s => s.Show)
|
||||
.ThenInclude(sh => sh.ShowMetadata)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(em => em.EpisodeId)
|
||||
.Select(g => g.OrderBy(em => em.Id).First())
|
||||
.Map(em => new LibraryBrowseItemResponseModel(
|
||||
em.EpisodeId,
|
||||
LibraryBrowseMediaType.Episode,
|
||||
em.Title ?? string.Empty,
|
||||
em.Episode.LibraryPath.LibraryId,
|
||||
em.Episode.LibraryPath.Library.Name,
|
||||
ArtworkWithFallback(em, ArtworkKind.Thumbnail, ArtworkKind.Poster),
|
||||
BestDuration(em.Episode.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.Episode,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
em.EpisodeId,
|
||||
null,
|
||||
EpisodeSubtitle(em))).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetMusicVideos(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.MusicVideoMetadata
|
||||
.AsNoTracking()
|
||||
.Where(mvm => ids.Contains(mvm.MusicVideoId))
|
||||
.Include(mvm => mvm.Artwork)
|
||||
.Include(mvm => mvm.MusicVideo)
|
||||
.ThenInclude(mv => mv.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(mvm => mvm.MusicVideo)
|
||||
.ThenInclude(mv => mv.MediaVersions)
|
||||
.Include(mvm => mvm.MusicVideo)
|
||||
.ThenInclude(mv => mv.Artist)
|
||||
.ThenInclude(a => a.ArtistMetadata)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(mvm => mvm.MusicVideoId)
|
||||
.Select(g => g.OrderBy(mvm => mvm.Id).First())
|
||||
.Map(mvm => new LibraryBrowseItemResponseModel(
|
||||
mvm.MusicVideoId,
|
||||
LibraryBrowseMediaType.MusicVideo,
|
||||
mvm.Title ?? string.Empty,
|
||||
mvm.MusicVideo.LibraryPath.LibraryId,
|
||||
mvm.MusicVideo.LibraryPath.Library.Name,
|
||||
ArtworkWithFallback(mvm, ArtworkKind.Thumbnail, ArtworkKind.Poster),
|
||||
BestDuration(mvm.MusicVideo.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.MusicVideo,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
mvm.MusicVideoId,
|
||||
null,
|
||||
MusicVideoSubtitle(mvm))).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetSongs(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.SongMetadata
|
||||
.AsNoTracking()
|
||||
.Where(sm => ids.Contains(sm.SongId))
|
||||
.Include(sm => sm.Artwork)
|
||||
.Include(sm => sm.Song)
|
||||
.ThenInclude(s => s.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(sm => sm.Song)
|
||||
.ThenInclude(s => s.MediaVersions)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(sm => sm.SongId)
|
||||
.Select(g => g.OrderBy(sm => sm.Id).First())
|
||||
.Map(sm => new LibraryBrowseItemResponseModel(
|
||||
sm.SongId,
|
||||
LibraryBrowseMediaType.Song,
|
||||
sm.Title ?? string.Empty,
|
||||
sm.Song.LibraryPath.LibraryId,
|
||||
sm.Song.LibraryPath.Library.Name,
|
||||
ArtworkWithFallback(sm, ArtworkKind.Thumbnail, ArtworkKind.Poster),
|
||||
BestDuration(sm.Song.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.Song,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sm.SongId,
|
||||
null,
|
||||
SongSubtitle(sm))).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetOtherVideos(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.OtherVideoMetadata
|
||||
.AsNoTracking()
|
||||
.Where(ovm => ids.Contains(ovm.OtherVideoId))
|
||||
.Include(ovm => ovm.Artwork)
|
||||
.Include(ovm => ovm.OtherVideo)
|
||||
.ThenInclude(ov => ov.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(ovm => ovm.OtherVideo)
|
||||
.ThenInclude(ov => ov.MediaVersions)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(ovm => ovm.OtherVideoId)
|
||||
.Select(g => g.OrderBy(ovm => ovm.Id).First())
|
||||
.Map(ovm => new LibraryBrowseItemResponseModel(
|
||||
ovm.OtherVideoId,
|
||||
LibraryBrowseMediaType.OtherVideo,
|
||||
ovm.Title ?? string.Empty,
|
||||
ovm.OtherVideo.LibraryPath.LibraryId,
|
||||
ovm.OtherVideo.LibraryPath.Library.Name,
|
||||
ArtworkWithFallback(ovm, ArtworkKind.Thumbnail, ArtworkKind.Poster),
|
||||
BestDuration(ovm.OtherVideo.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.OtherVideo,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
ovm.OtherVideoId,
|
||||
null,
|
||||
string.IsNullOrWhiteSpace(ovm.OriginalTitle) ? null : ovm.OriginalTitle)).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetImages(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.ImageMetadata
|
||||
.AsNoTracking()
|
||||
.Where(im => ids.Contains(im.ImageId))
|
||||
.Include(im => im.Artwork)
|
||||
.Include(im => im.Image)
|
||||
.ThenInclude(i => i.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(im => im.Image)
|
||||
.ThenInclude(i => i.MediaVersions)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(im => im.ImageId)
|
||||
.Select(g => g.OrderBy(im => im.Id).First())
|
||||
.Map(im => new LibraryBrowseItemResponseModel(
|
||||
im.ImageId,
|
||||
LibraryBrowseMediaType.Image,
|
||||
im.Title ?? string.Empty,
|
||||
im.Image.LibraryPath.LibraryId,
|
||||
im.Image.LibraryPath.Library.Name,
|
||||
ArtworkWithFallback(im, ArtworkKind.Poster, ArtworkKind.Thumbnail),
|
||||
BestDuration(im.Image.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.Image,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
im.ImageId,
|
||||
null,
|
||||
string.IsNullOrWhiteSpace(im.OriginalTitle) ? null : im.OriginalTitle)).ToList());
|
||||
}
|
||||
|
||||
public static async Task<List<LibraryBrowseItemResponseModel>> GetRemoteStreams(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.RemoteStreamMetadata
|
||||
.AsNoTracking()
|
||||
.Where(rsm => ids.Contains(rsm.RemoteStreamId))
|
||||
.Include(rsm => rsm.Artwork)
|
||||
.Include(rsm => rsm.RemoteStream)
|
||||
.ThenInclude(rs => rs.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(rsm => rsm.RemoteStream)
|
||||
.ThenInclude(rs => rs.MediaVersions)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(rsm => rsm.RemoteStreamId)
|
||||
.Select(g => g.OrderBy(rsm => rsm.Id).First())
|
||||
.Map(rsm => new LibraryBrowseItemResponseModel(
|
||||
rsm.RemoteStreamId,
|
||||
LibraryBrowseMediaType.RemoteStream,
|
||||
rsm.Title ?? string.Empty,
|
||||
rsm.RemoteStream.LibraryPath.LibraryId,
|
||||
rsm.RemoteStream.LibraryPath.Library.Name,
|
||||
ArtworkWithFallback(rsm, ArtworkKind.Thumbnail, ArtworkKind.Poster),
|
||||
BestDuration(rsm.RemoteStream.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.RemoteStream,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
rsm.RemoteStreamId,
|
||||
null,
|
||||
string.IsNullOrWhiteSpace(rsm.OriginalTitle) ? null : rsm.OriginalTitle)).ToList());
|
||||
}
|
||||
|
||||
public static TimeSpan? BestDuration(IEnumerable<MediaVersion> versions)
|
||||
{
|
||||
TimeSpan duration = versions
|
||||
.Select(v => v.Duration)
|
||||
.Where(d => d > TimeSpan.Zero)
|
||||
.DefaultIfEmpty()
|
||||
.Max();
|
||||
return duration > TimeSpan.Zero ? duration : null;
|
||||
}
|
||||
|
||||
// Returns a rooted, directly-usable artwork URL for the SPA's <img src>. Blazor pages rely on
|
||||
// GetPosterUrl to prefix "artwork/posters/" and resolve relative to <base href="/">, but the SPA
|
||||
// renders the value raw from under /app/, so the API must root the URL itself (issue #180).
|
||||
public static string Artwork(Metadata metadata, ArtworkKind artworkKind)
|
||||
{
|
||||
string artwork = Optional(metadata.Artwork.FirstOrDefault(a => a.ArtworkKind == artworkKind))
|
||||
.Match(a => a.Path, string.Empty);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(artwork))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
// Absolute URLs are already usable as-is (matches Blazor's GetPosterUrl guard).
|
||||
if (artwork.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
|
||||
artwork.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return artwork;
|
||||
}
|
||||
|
||||
string folder = artworkKind is ArtworkKind.Thumbnail ? "thumbnails" : "posters";
|
||||
|
||||
if (artwork.StartsWith("jellyfin://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Url url = JellyfinUrl.RelativeProxyForArtwork(artwork);
|
||||
if (artworkKind is ArtworkKind.Poster or ArtworkKind.Thumbnail)
|
||||
{
|
||||
url.SetQueryParam("fillHeight", 440);
|
||||
}
|
||||
|
||||
return $"/artwork/{folder}/{url}";
|
||||
}
|
||||
|
||||
if (artwork.StartsWith("emby://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Url url = EmbyUrl.RelativeProxyForArtwork(artwork);
|
||||
if (artworkKind is ArtworkKind.Poster or ArtworkKind.Thumbnail)
|
||||
{
|
||||
url.SetQueryParam("maxHeight", 440);
|
||||
}
|
||||
|
||||
return $"/artwork/{folder}/{url}";
|
||||
}
|
||||
|
||||
return $"/artwork/{folder}/{artwork}";
|
||||
}
|
||||
|
||||
private static string ArtworkWithFallback(Metadata metadata, ArtworkKind primary, ArtworkKind fallback)
|
||||
{
|
||||
string artwork = Artwork(metadata, primary);
|
||||
return string.IsNullOrWhiteSpace(artwork) ? Artwork(metadata, fallback) : artwork;
|
||||
}
|
||||
|
||||
private static string SeasonTitle(SeasonMetadata metadata)
|
||||
{
|
||||
string showTitle = metadata.Season.Show.ShowMetadata.HeadOrNone()
|
||||
.Map(sm => sm.Title ?? string.Empty)
|
||||
.IfNone(string.Empty);
|
||||
string seasonTitle = metadata.Season.SeasonNumber == 0
|
||||
? "Specials"
|
||||
: $"Season {metadata.Season.SeasonNumber}";
|
||||
return string.IsNullOrWhiteSpace(showTitle) ? seasonTitle : $"{showTitle} - {seasonTitle}";
|
||||
}
|
||||
|
||||
// Seasons often have no poster of their own; fall back to the parent show's poster (issue #180).
|
||||
private static string SeasonArtwork(SeasonMetadata metadata)
|
||||
{
|
||||
string artwork = Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(artwork))
|
||||
{
|
||||
return artwork;
|
||||
}
|
||||
|
||||
return metadata.Season.Show.ShowMetadata.HeadOrNone()
|
||||
.Match(sm => Artwork(sm, ArtworkKind.Poster), string.Empty);
|
||||
}
|
||||
|
||||
private static string EpisodeSubtitle(EpisodeMetadata metadata)
|
||||
{
|
||||
string showTitle = metadata.Episode.Season.Show.ShowMetadata.HeadOrNone()
|
||||
.Map(sm => sm.Title ?? string.Empty)
|
||||
.IfNone(string.Empty);
|
||||
int seasonNumber = metadata.Episode.Season.SeasonNumber;
|
||||
string suffix = $"S{seasonNumber}E{metadata.EpisodeNumber}";
|
||||
return string.IsNullOrWhiteSpace(showTitle) ? suffix : $"{showTitle} - {suffix}";
|
||||
}
|
||||
|
||||
private static string MusicVideoSubtitle(MusicVideoMetadata metadata)
|
||||
{
|
||||
string artist = metadata.MusicVideo.Artist.ArtistMetadata.HeadOrNone()
|
||||
.Map(am => am.Title ?? string.Empty)
|
||||
.IfNone(string.Empty);
|
||||
string album = string.IsNullOrWhiteSpace(metadata.Album) ? string.Empty : metadata.Album;
|
||||
if (!string.IsNullOrWhiteSpace(artist) && !string.IsNullOrWhiteSpace(album))
|
||||
{
|
||||
return $"{artist} - {album}";
|
||||
}
|
||||
|
||||
return string.IsNullOrWhiteSpace(artist) ? album : artist;
|
||||
}
|
||||
|
||||
private static string SongSubtitle(SongMetadata metadata)
|
||||
{
|
||||
string artists = string.Join(", ", metadata.Artists ?? []);
|
||||
string album = string.IsNullOrWhiteSpace(metadata.Album) ? string.Empty : metadata.Album;
|
||||
if (!string.IsNullOrWhiteSpace(artists) && !string.IsNullOrWhiteSpace(album))
|
||||
{
|
||||
return $"{artists} - {album}";
|
||||
}
|
||||
|
||||
return string.IsNullOrWhiteSpace(artists) ? album : artists;
|
||||
}
|
||||
}
|
||||
@@ -7,4 +7,5 @@ public record GetLibraryBrowseItems(
|
||||
int? LibraryId,
|
||||
LibraryBrowseMediaType? MediaType,
|
||||
int PageNum,
|
||||
int PageSize) : IRequest<PagedLibraryBrowseItemsResponseModel>;
|
||||
int PageSize,
|
||||
int? ParentId = null) : IRequest<PagedLibraryBrowseItemsResponseModel>;
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
using ErsatzTV.Core.Api.LibraryBrowse;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Emby;
|
||||
using ErsatzTV.Core.Interfaces.Search;
|
||||
using ErsatzTV.Core.Jellyfin;
|
||||
using ErsatzTV.Core.Search;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Search;
|
||||
using Flurl;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ErsatzTV.Application.LibraryBrowse;
|
||||
@@ -22,6 +19,34 @@ public class GetLibraryBrowseItemsHandler(
|
||||
GetLibraryBrowseItems request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Drill-in for detail pages: read a parent's children directly (bypassing Lucene) so the SPA can
|
||||
// expand a show into its seasons (#180), a season into its episodes, or an artist into its music
|
||||
// videos (#141/#161). Each reads in the natural display order for that kind.
|
||||
if (request.ParentId.HasValue)
|
||||
{
|
||||
switch (request.MediaType)
|
||||
{
|
||||
case LibraryBrowseMediaType.TelevisionSeason:
|
||||
{
|
||||
await using TvContext seasonContext =
|
||||
await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await BrowseSeasonsForShow(seasonContext, request, cancellationToken);
|
||||
}
|
||||
case LibraryBrowseMediaType.Episode:
|
||||
{
|
||||
await using TvContext episodeContext =
|
||||
await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await BrowseEpisodesForSeason(episodeContext, request, cancellationToken);
|
||||
}
|
||||
case LibraryBrowseMediaType.MusicVideo:
|
||||
{
|
||||
await using TvContext musicVideoContext =
|
||||
await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await BrowseMusicVideosForArtist(musicVideoContext, request, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int offset = request.PageNum * request.PageSize;
|
||||
SearchResult mediaResult = await SearchMedia(request, offset, request.PageSize, cancellationToken);
|
||||
|
||||
@@ -91,12 +116,24 @@ public class GetLibraryBrowseItemsHandler(
|
||||
LibraryBrowseMediaType.TelevisionShow => [LuceneSearchIndex.ShowType],
|
||||
LibraryBrowseMediaType.TelevisionSeason => [LuceneSearchIndex.SeasonType],
|
||||
LibraryBrowseMediaType.Artist => [LuceneSearchIndex.ArtistType],
|
||||
LibraryBrowseMediaType.Episode => [LuceneSearchIndex.EpisodeType],
|
||||
LibraryBrowseMediaType.MusicVideo => [LuceneSearchIndex.MusicVideoType],
|
||||
LibraryBrowseMediaType.Song => [LuceneSearchIndex.SongType],
|
||||
LibraryBrowseMediaType.OtherVideo => [LuceneSearchIndex.OtherVideoType],
|
||||
LibraryBrowseMediaType.Image => [LuceneSearchIndex.ImageType],
|
||||
LibraryBrowseMediaType.RemoteStream => [LuceneSearchIndex.RemoteStreamType],
|
||||
null =>
|
||||
[
|
||||
LuceneSearchIndex.MovieType,
|
||||
LuceneSearchIndex.ShowType,
|
||||
LuceneSearchIndex.SeasonType,
|
||||
LuceneSearchIndex.ArtistType
|
||||
LuceneSearchIndex.ArtistType,
|
||||
LuceneSearchIndex.EpisodeType,
|
||||
LuceneSearchIndex.MusicVideoType,
|
||||
LuceneSearchIndex.SongType,
|
||||
LuceneSearchIndex.OtherVideoType,
|
||||
LuceneSearchIndex.ImageType,
|
||||
LuceneSearchIndex.RemoteStreamType
|
||||
],
|
||||
_ => []
|
||||
};
|
||||
@@ -115,219 +152,184 @@ public class GetLibraryBrowseItemsHandler(
|
||||
List<int> showIds = searchItems.Where(i => i.Type == LuceneSearchIndex.ShowType).Select(i => i.Id).ToList();
|
||||
List<int> seasonIds = searchItems.Where(i => i.Type == LuceneSearchIndex.SeasonType).Select(i => i.Id).ToList();
|
||||
List<int> artistIds = searchItems.Where(i => i.Type == LuceneSearchIndex.ArtistType).Select(i => i.Id).ToList();
|
||||
List<int> episodeIds = searchItems.Where(i => i.Type == LuceneSearchIndex.EpisodeType).Select(i => i.Id).ToList();
|
||||
List<int> musicVideoIds =
|
||||
searchItems.Where(i => i.Type == LuceneSearchIndex.MusicVideoType).Select(i => i.Id).ToList();
|
||||
List<int> songIds = searchItems.Where(i => i.Type == LuceneSearchIndex.SongType).Select(i => i.Id).ToList();
|
||||
List<int> otherVideoIds =
|
||||
searchItems.Where(i => i.Type == LuceneSearchIndex.OtherVideoType).Select(i => i.Id).ToList();
|
||||
List<int> imageIds = searchItems.Where(i => i.Type == LuceneSearchIndex.ImageType).Select(i => i.Id).ToList();
|
||||
List<int> remoteStreamIds =
|
||||
searchItems.Where(i => i.Type == LuceneSearchIndex.RemoteStreamType).Select(i => i.Id).ToList();
|
||||
|
||||
Dictionary<(string Type, int Id), LibraryBrowseItemResponseModel> hydrated = [];
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in await GetMovies(dbContext, movieIds, cancellationToken))
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetMovies(dbContext, movieIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.MovieType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in await GetShows(dbContext, showIds, cancellationToken))
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetShows(dbContext, showIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.ShowType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in await GetSeasons(dbContext, seasonIds, cancellationToken))
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetSeasons(dbContext, seasonIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.SeasonType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in await GetArtists(dbContext, artistIds, cancellationToken))
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetArtists(dbContext, artistIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.ArtistType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetEpisodes(dbContext, episodeIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.EpisodeType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetMusicVideos(dbContext, musicVideoIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.MusicVideoType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetSongs(dbContext, songIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.SongType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetOtherVideos(dbContext, otherVideoIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.OtherVideoType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetImages(dbContext, imageIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.ImageType, item.Id)] = item;
|
||||
}
|
||||
|
||||
foreach (LibraryBrowseItemResponseModel item in
|
||||
await LibraryBrowseItemMapper.GetRemoteStreams(dbContext, remoteStreamIds, cancellationToken))
|
||||
{
|
||||
hydrated[(LuceneSearchIndex.RemoteStreamType, item.Id)] = item;
|
||||
}
|
||||
|
||||
return searchItems
|
||||
.Where(i => hydrated.ContainsKey((i.Type, i.Id)))
|
||||
.Select(i => hydrated[(i.Type, i.Id)])
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static async Task<List<LibraryBrowseItemResponseModel>> GetMovies(
|
||||
private static async Task<PagedLibraryBrowseItemsResponseModel> BrowseSeasonsForShow(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
GetLibraryBrowseItems request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await dbContext.MovieMetadata
|
||||
List<int> allSeasonIds = await dbContext.Seasons
|
||||
.AsNoTracking()
|
||||
.Where(mm => ids.Contains(mm.MovieId))
|
||||
.Include(mm => mm.Artwork)
|
||||
.Include(mm => mm.Movie)
|
||||
.ThenInclude(m => m.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.Include(mm => mm.Movie)
|
||||
.ThenInclude(m => m.MediaVersions)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(mm => mm.MovieId)
|
||||
.Select(g => g.OrderBy(mm => mm.Id).First())
|
||||
.Map(mm => new LibraryBrowseItemResponseModel(
|
||||
mm.MovieId,
|
||||
LibraryBrowseMediaType.Movie,
|
||||
mm.Title ?? string.Empty,
|
||||
mm.Movie.LibraryPath.LibraryId,
|
||||
mm.Movie.LibraryPath.Library.Name,
|
||||
Artwork(mm, ArtworkKind.Poster),
|
||||
BestDuration(mm.Movie.MediaVersions),
|
||||
1,
|
||||
null,
|
||||
CollectionType.Movie,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
mm.MovieId,
|
||||
null)).ToList());
|
||||
.Where(s => s.ShowId == request.ParentId.Value)
|
||||
.OrderBy(s => s.SeasonNumber)
|
||||
.Select(s => s.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
int total = allSeasonIds.Count;
|
||||
List<int> pageIds = allSeasonIds
|
||||
.Skip(request.PageNum * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.ToList();
|
||||
|
||||
List<LibraryBrowseItemResponseModel> seasons =
|
||||
await LibraryBrowseItemMapper.GetSeasons(dbContext, pageIds, cancellationToken);
|
||||
|
||||
// GetSeasons groups by season id, so restore the requested season-number order.
|
||||
Dictionary<int, LibraryBrowseItemResponseModel> byId = seasons.ToDictionary(s => s.Id);
|
||||
List<LibraryBrowseItemResponseModel> ordered = pageIds
|
||||
.Where(byId.ContainsKey)
|
||||
.Select(id => byId[id])
|
||||
.ToList();
|
||||
|
||||
return new PagedLibraryBrowseItemsResponseModel(total, ordered);
|
||||
}
|
||||
|
||||
private static async Task<List<LibraryBrowseItemResponseModel>> GetShows(
|
||||
// Drill-in: episodes of a specific season, in episode-number order (#141/#161).
|
||||
private static async Task<PagedLibraryBrowseItemsResponseModel> BrowseEpisodesForSeason(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
GetLibraryBrowseItems request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
Dictionary<int, int> counts = await dbContext.Episodes
|
||||
List<int> allEpisodeIds = await dbContext.EpisodeMetadata
|
||||
.AsNoTracking()
|
||||
.Where(e => ids.Contains(e.Season.ShowId))
|
||||
.GroupBy(e => e.Season.ShowId)
|
||||
.Select(g => new { ShowId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(g => g.ShowId, g => g.Count, cancellationToken);
|
||||
.Where(em => em.Episode.SeasonId == request.ParentId.Value)
|
||||
.OrderBy(em => em.EpisodeNumber)
|
||||
.ThenBy(em => em.EpisodeId)
|
||||
.Select(em => em.EpisodeId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return await dbContext.ShowMetadata
|
||||
.AsNoTracking()
|
||||
.Where(sm => ids.Contains(sm.ShowId))
|
||||
.Include(sm => sm.Artwork)
|
||||
.Include(sm => sm.Show)
|
||||
.ThenInclude(s => s.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(sm => sm.ShowId)
|
||||
.Select(g => g.OrderBy(sm => sm.Id).First())
|
||||
.Map(sm => new LibraryBrowseItemResponseModel(
|
||||
sm.ShowId,
|
||||
LibraryBrowseMediaType.TelevisionShow,
|
||||
sm.Title ?? string.Empty,
|
||||
sm.Show.LibraryPath.LibraryId,
|
||||
sm.Show.LibraryPath.Library.Name,
|
||||
Artwork(sm, ArtworkKind.Poster),
|
||||
null,
|
||||
counts.TryGetValue(sm.ShowId, out int count) ? count : 0,
|
||||
null,
|
||||
CollectionType.TelevisionShow,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sm.ShowId,
|
||||
null)).ToList());
|
||||
// Distinct preserves order (LINQ-to-Objects) for episodes with multiple metadata rows.
|
||||
allEpisodeIds = allEpisodeIds.Distinct().ToList();
|
||||
|
||||
int total = allEpisodeIds.Count;
|
||||
List<int> pageIds = allEpisodeIds
|
||||
.Skip(request.PageNum * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.ToList();
|
||||
|
||||
List<LibraryBrowseItemResponseModel> episodes =
|
||||
await LibraryBrowseItemMapper.GetEpisodes(dbContext, pageIds, cancellationToken);
|
||||
|
||||
Dictionary<int, LibraryBrowseItemResponseModel> byId = episodes.ToDictionary(e => e.Id);
|
||||
List<LibraryBrowseItemResponseModel> ordered = pageIds
|
||||
.Where(byId.ContainsKey)
|
||||
.Select(id => byId[id])
|
||||
.ToList();
|
||||
|
||||
return new PagedLibraryBrowseItemsResponseModel(total, ordered);
|
||||
}
|
||||
|
||||
private static async Task<List<LibraryBrowseItemResponseModel>> GetSeasons(
|
||||
// Drill-in: music videos of a specific artist, in album/track/title order (#141/#161).
|
||||
private static async Task<PagedLibraryBrowseItemsResponseModel> BrowseMusicVideosForArtist(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
GetLibraryBrowseItems request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
Dictionary<int, int> counts = await dbContext.Episodes
|
||||
List<int> allMusicVideoIds = await dbContext.MusicVideoMetadata
|
||||
.AsNoTracking()
|
||||
.Where(e => ids.Contains(e.SeasonId))
|
||||
.GroupBy(e => e.SeasonId)
|
||||
.Select(g => new { SeasonId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(g => g.SeasonId, g => g.Count, cancellationToken);
|
||||
.Where(mvm => mvm.MusicVideo.ArtistId == request.ParentId.Value)
|
||||
.OrderBy(mvm => mvm.Album)
|
||||
.ThenBy(mvm => mvm.Track)
|
||||
.ThenBy(mvm => mvm.Title)
|
||||
.ThenBy(mvm => mvm.MusicVideoId)
|
||||
.Select(mvm => mvm.MusicVideoId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return await dbContext.SeasonMetadata
|
||||
.AsNoTracking()
|
||||
.Where(sm => ids.Contains(sm.SeasonId))
|
||||
.Include(sm => sm.Artwork)
|
||||
.Include(sm => sm.Season)
|
||||
.ThenInclude(s => s.Show)
|
||||
.ThenInclude(s => s.ShowMetadata)
|
||||
.Include(sm => sm.Season)
|
||||
.ThenInclude(s => s.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(sm => sm.SeasonId)
|
||||
.Select(g => g.OrderBy(sm => sm.Id).First())
|
||||
.Map(sm => new LibraryBrowseItemResponseModel(
|
||||
sm.SeasonId,
|
||||
LibraryBrowseMediaType.TelevisionSeason,
|
||||
SeasonTitle(sm),
|
||||
sm.Season.LibraryPath.LibraryId,
|
||||
sm.Season.LibraryPath.Library.Name,
|
||||
Artwork(sm, ArtworkKind.Poster),
|
||||
null,
|
||||
counts.TryGetValue(sm.SeasonId, out int count) ? count : 0,
|
||||
null,
|
||||
CollectionType.TelevisionSeason,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sm.SeasonId,
|
||||
null)).ToList());
|
||||
}
|
||||
allMusicVideoIds = allMusicVideoIds.Distinct().ToList();
|
||||
|
||||
private static async Task<List<LibraryBrowseItemResponseModel>> GetArtists(
|
||||
TvContext dbContext,
|
||||
List<int> ids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
int total = allMusicVideoIds.Count;
|
||||
List<int> pageIds = allMusicVideoIds
|
||||
.Skip(request.PageNum * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.ToList();
|
||||
|
||||
Dictionary<int, int> counts = await dbContext.MusicVideos
|
||||
.AsNoTracking()
|
||||
.Where(mv => ids.Contains(mv.ArtistId))
|
||||
.GroupBy(mv => mv.ArtistId)
|
||||
.Select(g => new { ArtistId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(g => g.ArtistId, g => g.Count, cancellationToken);
|
||||
List<LibraryBrowseItemResponseModel> musicVideos =
|
||||
await LibraryBrowseItemMapper.GetMusicVideos(dbContext, pageIds, cancellationToken);
|
||||
|
||||
return await dbContext.ArtistMetadata
|
||||
.AsNoTracking()
|
||||
.Where(am => ids.Contains(am.ArtistId))
|
||||
.Include(am => am.Artwork)
|
||||
.Include(am => am.Artist)
|
||||
.ThenInclude(a => a.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ToListAsync(cancellationToken)
|
||||
.Map(list => list
|
||||
.GroupBy(am => am.ArtistId)
|
||||
.Select(g => g.OrderBy(am => am.Id).First())
|
||||
.Map(am => new LibraryBrowseItemResponseModel(
|
||||
am.ArtistId,
|
||||
LibraryBrowseMediaType.Artist,
|
||||
am.Title ?? string.Empty,
|
||||
am.Artist.LibraryPath.LibraryId,
|
||||
am.Artist.LibraryPath.Library.Name,
|
||||
Artwork(am, ArtworkKind.Thumbnail),
|
||||
null,
|
||||
counts.TryGetValue(am.ArtistId, out int count) ? count : 0,
|
||||
null,
|
||||
CollectionType.Artist,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
am.ArtistId,
|
||||
null)).ToList());
|
||||
Dictionary<int, LibraryBrowseItemResponseModel> byId = musicVideos.ToDictionary(mv => mv.Id);
|
||||
List<LibraryBrowseItemResponseModel> ordered = pageIds
|
||||
.Where(byId.ContainsKey)
|
||||
.Select(id => byId[id])
|
||||
.ToList();
|
||||
|
||||
return new PagedLibraryBrowseItemsResponseModel(total, ordered);
|
||||
}
|
||||
|
||||
private static async Task<int> CountCollections(
|
||||
@@ -659,16 +661,6 @@ public class GetLibraryBrowseItemsHandler(
|
||||
private static bool ShouldInclude(LibraryBrowseMediaType? requestType, LibraryBrowseMediaType itemType) =>
|
||||
requestType is null || requestType == itemType;
|
||||
|
||||
private static TimeSpan? BestDuration(IEnumerable<MediaVersion> versions)
|
||||
{
|
||||
TimeSpan duration = versions
|
||||
.Select(v => v.Duration)
|
||||
.Where(d => d > TimeSpan.Zero)
|
||||
.DefaultIfEmpty()
|
||||
.Max();
|
||||
return duration > TimeSpan.Zero ? duration : null;
|
||||
}
|
||||
|
||||
private static async Task<Dictionary<int, TimeSpan?>> GetManualCollectionDurations(
|
||||
TvContext dbContext,
|
||||
List<int> collectionIds,
|
||||
@@ -684,7 +676,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Include(m => m.MediaVersions)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
TimeSpan? duration = BestDuration(movie.MediaVersions);
|
||||
TimeSpan? duration = LibraryBrowseItemMapper.BestDuration(movie.MediaVersions);
|
||||
if (duration.HasValue)
|
||||
{
|
||||
mediaItemDurations[movie.Id] = duration.Value;
|
||||
@@ -697,7 +689,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Include(e => e.MediaVersions)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
TimeSpan? duration = BestDuration(episode.MediaVersions);
|
||||
TimeSpan? duration = LibraryBrowseItemMapper.BestDuration(episode.MediaVersions);
|
||||
if (duration.HasValue)
|
||||
{
|
||||
mediaItemDurations[episode.Id] = duration.Value;
|
||||
@@ -710,7 +702,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Include(mv => mv.MediaVersions)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
TimeSpan? duration = BestDuration(musicVideo.MediaVersions);
|
||||
TimeSpan? duration = LibraryBrowseItemMapper.BestDuration(musicVideo.MediaVersions);
|
||||
if (duration.HasValue)
|
||||
{
|
||||
mediaItemDurations[musicVideo.Id] = duration.Value;
|
||||
@@ -723,7 +715,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Include(ov => ov.MediaVersions)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
TimeSpan? duration = BestDuration(otherVideo.MediaVersions);
|
||||
TimeSpan? duration = LibraryBrowseItemMapper.BestDuration(otherVideo.MediaVersions);
|
||||
if (duration.HasValue)
|
||||
{
|
||||
mediaItemDurations[otherVideo.Id] = duration.Value;
|
||||
@@ -736,7 +728,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Include(s => s.MediaVersions)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
TimeSpan? duration = BestDuration(song.MediaVersions);
|
||||
TimeSpan? duration = LibraryBrowseItemMapper.BestDuration(song.MediaVersions);
|
||||
if (duration.HasValue)
|
||||
{
|
||||
mediaItemDurations[song.Id] = duration.Value;
|
||||
@@ -749,7 +741,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Include(i => i.MediaVersions)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
TimeSpan? duration = BestDuration(image.MediaVersions);
|
||||
TimeSpan? duration = LibraryBrowseItemMapper.BestDuration(image.MediaVersions);
|
||||
if (duration.HasValue)
|
||||
{
|
||||
mediaItemDurations[image.Id] = duration.Value;
|
||||
@@ -762,7 +754,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Include(rs => rs.MediaVersions)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
TimeSpan? duration = BestDuration(remoteStream.MediaVersions);
|
||||
TimeSpan? duration = LibraryBrowseItemMapper.BestDuration(remoteStream.MediaVersions);
|
||||
if (duration.HasValue)
|
||||
{
|
||||
mediaItemDurations[remoteStream.Id] = duration.Value;
|
||||
@@ -793,7 +785,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.OrderBy(mm => mm.Id)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
string poster = Artwork(metadata, ArtworkKind.Poster);
|
||||
string poster = LibraryBrowseItemMapper.Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(poster) && !mediaItemArtwork.ContainsKey(metadata.MovieId))
|
||||
{
|
||||
mediaItemArtwork[metadata.MovieId] = poster;
|
||||
@@ -807,7 +799,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.OrderBy(sm => sm.Id)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
string poster = Artwork(metadata, ArtworkKind.Poster);
|
||||
string poster = LibraryBrowseItemMapper.Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(poster) && !mediaItemArtwork.ContainsKey(metadata.ShowId))
|
||||
{
|
||||
mediaItemArtwork[metadata.ShowId] = poster;
|
||||
@@ -821,7 +813,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.OrderBy(sm => sm.Id)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
string poster = Artwork(metadata, ArtworkKind.Poster);
|
||||
string poster = LibraryBrowseItemMapper.Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(poster) && !mediaItemArtwork.ContainsKey(metadata.SeasonId))
|
||||
{
|
||||
mediaItemArtwork[metadata.SeasonId] = poster;
|
||||
@@ -835,7 +827,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.OrderBy(ovm => ovm.Id)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
string poster = Artwork(metadata, ArtworkKind.Poster);
|
||||
string poster = LibraryBrowseItemMapper.Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(poster) && !mediaItemArtwork.ContainsKey(metadata.OtherVideoId))
|
||||
{
|
||||
mediaItemArtwork[metadata.OtherVideoId] = poster;
|
||||
@@ -849,7 +841,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.OrderBy(sm => sm.Id)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
string poster = Artwork(metadata, ArtworkKind.Poster);
|
||||
string poster = LibraryBrowseItemMapper.Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(poster) && !mediaItemArtwork.ContainsKey(metadata.SongId))
|
||||
{
|
||||
mediaItemArtwork[metadata.SongId] = poster;
|
||||
@@ -863,7 +855,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.OrderBy(im => im.Id)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
string poster = Artwork(metadata, ArtworkKind.Poster);
|
||||
string poster = LibraryBrowseItemMapper.Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(poster) && !mediaItemArtwork.ContainsKey(metadata.ImageId))
|
||||
{
|
||||
mediaItemArtwork[metadata.ImageId] = poster;
|
||||
@@ -877,7 +869,7 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.OrderBy(rsm => rsm.Id)
|
||||
.ToListAsync(cancellationToken))
|
||||
{
|
||||
string poster = Artwork(metadata, ArtworkKind.Poster);
|
||||
string poster = LibraryBrowseItemMapper.Artwork(metadata, ArtworkKind.Poster);
|
||||
if (!string.IsNullOrWhiteSpace(poster) && !mediaItemArtwork.ContainsKey(metadata.RemoteStreamId))
|
||||
{
|
||||
mediaItemArtwork[metadata.RemoteStreamId] = poster;
|
||||
@@ -902,47 +894,6 @@ public class GetLibraryBrowseItemsHandler(
|
||||
.Select(ci => new CollectionMediaItem(ci.CollectionId, ci.MediaItemId, ci.CustomIndex))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
private static string SeasonTitle(SeasonMetadata metadata)
|
||||
{
|
||||
string showTitle = metadata.Season.Show.ShowMetadata.HeadOrNone()
|
||||
.Map(sm => sm.Title ?? string.Empty)
|
||||
.IfNone(string.Empty);
|
||||
string seasonTitle = metadata.Season.SeasonNumber == 0
|
||||
? "Specials"
|
||||
: $"Season {metadata.Season.SeasonNumber}";
|
||||
return string.IsNullOrWhiteSpace(showTitle) ? seasonTitle : $"{showTitle} - {seasonTitle}";
|
||||
}
|
||||
|
||||
private static string Artwork(Metadata metadata, ArtworkKind artworkKind)
|
||||
{
|
||||
string artwork = Optional(metadata.Artwork.FirstOrDefault(a => a.ArtworkKind == artworkKind))
|
||||
.Match(a => a.Path, string.Empty);
|
||||
|
||||
if (artwork.StartsWith("jellyfin://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Url url = JellyfinUrl.RelativeProxyForArtwork(artwork);
|
||||
if (artworkKind is ArtworkKind.Poster or ArtworkKind.Thumbnail)
|
||||
{
|
||||
url.SetQueryParam("fillHeight", 440);
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
if (artwork.StartsWith("emby://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Url url = EmbyUrl.RelativeProxyForArtwork(artwork);
|
||||
if (artworkKind is ArtworkKind.Poster or ArtworkKind.Thumbnail)
|
||||
{
|
||||
url.SetQueryParam("maxHeight", 440);
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
return artwork;
|
||||
}
|
||||
|
||||
private static string EscapeLike(string searchQuery) =>
|
||||
searchQuery
|
||||
.Replace("\\", "\\\\", StringComparison.Ordinal)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.LibraryBrowse;
|
||||
|
||||
namespace ErsatzTV.Application.MediaCollections;
|
||||
|
||||
public record GetCollectionItems(int Id, int PageNum, int PageSize)
|
||||
: IRequest<Either<BaseError, PagedLibraryBrowseItemsResponseModel>>;
|
||||
@@ -0,0 +1,56 @@
|
||||
using ErsatzTV.Application.LibraryBrowse;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.LibraryBrowse;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ErsatzTV.Application.MediaCollections;
|
||||
|
||||
public class GetCollectionItemsHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
: IRequestHandler<GetCollectionItems, Either<BaseError, PagedLibraryBrowseItemsResponseModel>>
|
||||
{
|
||||
public async Task<Either<BaseError, PagedLibraryBrowseItemsResponseModel>> Handle(
|
||||
GetCollectionItems request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
bool exists = await dbContext.Collections
|
||||
.AsNoTracking()
|
||||
.AnyAsync(c => c.Id == request.Id, cancellationToken);
|
||||
if (!exists)
|
||||
{
|
||||
return new NotFoundError($"Collection {request.Id} does not exist.");
|
||||
}
|
||||
|
||||
// The collection graph is bounded, so load every member id and hydrate them in one shared
|
||||
// pass (LibraryBrowseItemMapper), then order + page in-memory. Mixed media kinds are supported
|
||||
// because MediaItem ids are globally unique across kinds.
|
||||
List<int> mediaItemIds = await dbContext.CollectionItems
|
||||
.AsNoTracking()
|
||||
.Where(ci => ci.CollectionId == request.Id)
|
||||
.Select(ci => ci.MediaItemId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
List<LibraryBrowseItemResponseModel> all =
|
||||
await LibraryBrowseItemMapper.HydrateMediaItemsByIds(dbContext, mediaItemIds, cancellationToken);
|
||||
|
||||
// Stable title ordering mirrors the library-browse handler (which orders its rows by name),
|
||||
// giving the SPA a deterministic, browsable list independent of collection insertion order.
|
||||
List<LibraryBrowseItemResponseModel> ordered = all
|
||||
.OrderBy(i => i.Title, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(i => i.Id)
|
||||
.ToList();
|
||||
|
||||
int pageNum = Math.Max(0, request.PageNum);
|
||||
int pageSize = Math.Clamp(request.PageSize, 1, 100);
|
||||
|
||||
List<LibraryBrowseItemResponseModel> page = ordered
|
||||
.Skip(pageNum * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToList();
|
||||
|
||||
return new PagedLibraryBrowseItemsResponseModel(ordered.Count, page);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,9 @@ public class
|
||||
playout.ProgramSchedule?.Name ?? string.Empty,
|
||||
playout.ScheduleFile,
|
||||
playout.DailyRebuildTime,
|
||||
playout.BuildStatus);
|
||||
playout.BuildStatus,
|
||||
playout.DecoId,
|
||||
playout.Deco?.Name);
|
||||
}
|
||||
|
||||
private static Task<Validation<BaseError, Playout>> Validate(
|
||||
|
||||
@@ -46,7 +46,9 @@ public class UpdatePlayoutHandler : IRequestHandler<UpdatePlayout, Either<BaseEr
|
||||
playout.ProgramSchedule?.Name ?? string.Empty,
|
||||
playout.ScheduleFile,
|
||||
playout.DailyRebuildTime,
|
||||
playout.BuildStatus);
|
||||
playout.BuildStatus,
|
||||
playout.DecoId,
|
||||
playout.Deco?.Name);
|
||||
}
|
||||
|
||||
private static Task<Validation<BaseError, Playout>> Validate(
|
||||
|
||||
@@ -49,7 +49,9 @@ public class
|
||||
playout.ProgramSchedule?.Name ?? string.Empty,
|
||||
playout.ScheduleFile,
|
||||
playout.DailyRebuildTime,
|
||||
playout.BuildStatus);
|
||||
playout.BuildStatus,
|
||||
playout.DecoId,
|
||||
playout.Deco?.Name);
|
||||
}
|
||||
|
||||
private async Task<Validation<BaseError, Playout>> Validate(
|
||||
|
||||
@@ -54,7 +54,9 @@ public class
|
||||
playout.ProgramSchedule?.Name ?? string.Empty,
|
||||
playout.ScheduleFile,
|
||||
playout.DailyRebuildTime,
|
||||
playout.BuildStatus);
|
||||
playout.BuildStatus,
|
||||
playout.DecoId,
|
||||
playout.Deco?.Name);
|
||||
}
|
||||
|
||||
private static Task<Validation<BaseError, Playout>> Validate(
|
||||
|
||||
@@ -15,7 +15,11 @@ internal static class Mapper
|
||||
playout.ProgramScheduleId == null ? string.Empty : playout.ProgramSchedule.Name,
|
||||
playout.ScheduleFile,
|
||||
playout.DailyRebuildTime,
|
||||
playout.BuildStatus);
|
||||
playout.BuildStatus,
|
||||
playout.DecoId,
|
||||
// the paged-playouts query does not eager-load Deco (the list response does not surface
|
||||
// the default deco); GetPlayoutById includes it for the detail response
|
||||
playout.Deco?.Name);
|
||||
|
||||
internal static PlayoutItemViewModel ProjectToViewModel(PlayoutItem playoutItem) =>
|
||||
new(
|
||||
|
||||
@@ -11,7 +11,9 @@ public record PlayoutNameViewModel(
|
||||
string ScheduleName,
|
||||
string ScheduleFile,
|
||||
TimeSpan? DbDailyRebuildTime,
|
||||
PlayoutBuildStatus BuildStatus)
|
||||
PlayoutBuildStatus BuildStatus,
|
||||
int? DecoId,
|
||||
string DecoName)
|
||||
{
|
||||
public Option<TimeSpan> DailyRebuildTime => Optional(DbDailyRebuildTime);
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ public class GetPlayoutByIdHandler(IDbContextFactory<TvContext> dbContextFactory
|
||||
.Include(p => p.ProgramSchedule)
|
||||
.Include(p => p.Channel)
|
||||
.Include(p => p.BuildStatus)
|
||||
.Include(p => p.Deco)
|
||||
.SelectOneAsync(p => p.Id, p => p.Id == request.PlayoutId, cancellationToken)
|
||||
.MapT(p => new PlayoutNameViewModel(
|
||||
p.Id,
|
||||
@@ -27,6 +28,8 @@ public class GetPlayoutByIdHandler(IDbContextFactory<TvContext> dbContextFactory
|
||||
p.ProgramScheduleId == null ? string.Empty : p.ProgramSchedule.Name,
|
||||
p.ScheduleFile,
|
||||
p.DailyRebuildTime,
|
||||
p.BuildStatus));
|
||||
p.BuildStatus,
|
||||
p.DecoId,
|
||||
p.DecoId == null ? null : p.Deco.Name));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,13 +25,29 @@ public class CreateBlockHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
return Mapper.ProjectToViewModel(block);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Block>> Validate(TvContext dbContext, CreateBlock request) =>
|
||||
await ValidateBlockName(dbContext, request).MapT(name => new Block
|
||||
private static async Task<Validation<BaseError, Block>> Validate(TvContext dbContext, CreateBlock request)
|
||||
{
|
||||
Validation<BaseError, Unit> blockGroupValidation = await ValidateBlockGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateBlockName(dbContext, request);
|
||||
|
||||
return (blockGroupValidation, nameValidation).Apply((_, name) => new Block
|
||||
{
|
||||
BlockGroupId = request.BlockGroupId,
|
||||
Name = name,
|
||||
Minutes = 30
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateBlockGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateBlock request)
|
||||
{
|
||||
bool blockGroupExists = await dbContext.BlockGroups.AnyAsync(bg => bg.Id == request.BlockGroupId);
|
||||
|
||||
return blockGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Block group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateBlockName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -25,8 +25,12 @@ public class CreateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
return Mapper.ProjectToViewModel(deco);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Deco>> Validate(TvContext dbContext, CreateDeco request) =>
|
||||
await ValidateDecoName(dbContext, request).MapT(name => new Deco
|
||||
private static async Task<Validation<BaseError, Deco>> Validate(TvContext dbContext, CreateDeco request)
|
||||
{
|
||||
Validation<BaseError, Unit> decoGroupValidation = await ValidateDecoGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateDecoName(dbContext, request);
|
||||
|
||||
return (decoGroupValidation, nameValidation).Apply((_, name) => new Deco
|
||||
{
|
||||
DecoGroupId = request.DecoGroupId,
|
||||
Name = name,
|
||||
@@ -34,6 +38,18 @@ public class CreateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
DecoWatermarks = [],
|
||||
DecoGraphicsElements = []
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateDecoGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateDeco request)
|
||||
{
|
||||
bool decoGroupExists = await dbContext.DecoGroups.AnyAsync(dg => dg.Id == request.DecoGroupId);
|
||||
|
||||
return decoGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Deco group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateDecoName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -27,12 +27,30 @@ public class CreateDecoTemplateHandler(IDbContextFactory<TvContext> dbContextFac
|
||||
|
||||
private static async Task<Validation<BaseError, DecoTemplate>> Validate(
|
||||
TvContext dbContext,
|
||||
CreateDecoTemplate request) =>
|
||||
await ValidateDecoTemplateName(dbContext, request).MapT(name => new DecoTemplate
|
||||
CreateDecoTemplate request)
|
||||
{
|
||||
Validation<BaseError, Unit> decoTemplateGroupValidation =
|
||||
await ValidateDecoTemplateGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateDecoTemplateName(dbContext, request);
|
||||
|
||||
return (decoTemplateGroupValidation, nameValidation).Apply((_, name) => new DecoTemplate
|
||||
{
|
||||
DecoTemplateGroupId = request.DecoTemplateGroupId,
|
||||
Name = name
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateDecoTemplateGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateDecoTemplate request)
|
||||
{
|
||||
bool decoTemplateGroupExists =
|
||||
await dbContext.DecoTemplateGroups.AnyAsync(dtg => dtg.Id == request.DecoTemplateGroupId);
|
||||
|
||||
return decoTemplateGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Deco template group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateDecoTemplateName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -25,12 +25,28 @@ public class CreateTemplateHandler(IDbContextFactory<TvContext> dbContextFactory
|
||||
return Mapper.ProjectToViewModel(template);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Template>> Validate(TvContext dbContext, CreateTemplate request) =>
|
||||
await ValidateTemplateName(dbContext, request).MapT(name => new Template
|
||||
private static async Task<Validation<BaseError, Template>> Validate(TvContext dbContext, CreateTemplate request)
|
||||
{
|
||||
Validation<BaseError, Unit> templateGroupValidation = await ValidateTemplateGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateTemplateName(dbContext, request);
|
||||
|
||||
return (templateGroupValidation, nameValidation).Apply((_, name) => new Template
|
||||
{
|
||||
TemplateGroupId = request.TemplateGroupId,
|
||||
Name = name
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateTemplateGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateTemplate request)
|
||||
{
|
||||
bool templateGroupExists = await dbContext.TemplateGroups.AnyAsync(tg => tg.Id == request.TemplateGroupId);
|
||||
|
||||
return templateGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Template group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateTemplateName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -29,11 +29,7 @@ public class ReplaceDecoTemplateItemsHandler(IDbContextFactory<TvContext> dbCont
|
||||
|
||||
dbContext.RemoveRange(decoTemplate.Items);
|
||||
|
||||
// drop items that are invalid
|
||||
decoTemplate.Items = request.Items
|
||||
.Map(i => BuildItem(decoTemplate, i))
|
||||
.Filter(i => i.StartTime < i.EndTime || i.EndTime == TimeSpan.Zero)
|
||||
.ToList();
|
||||
decoTemplate.Items = request.Items.Map(i => BuildItem(decoTemplate, i)).ToList();
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
@@ -66,7 +62,78 @@ public class ReplaceDecoTemplateItemsHandler(IDbContextFactory<TvContext> dbCont
|
||||
ReplaceDecoTemplateItems request,
|
||||
CancellationToken cancellationToken) =>
|
||||
DecoTemplateMustExist(dbContext, request.DecoTemplateId, cancellationToken)
|
||||
.BindT(decoTemplate => DecoTemplateNameMustBeValid(dbContext, decoTemplate, request));
|
||||
.BindT(decoTemplate => DecoTemplateNameMustBeValid(dbContext, decoTemplate, request))
|
||||
.BindT(decoTemplate => DecoTemplateItemsMustBeValid(dbContext, decoTemplate, request));
|
||||
|
||||
// Hardening (deliberate deviation from the original handler): rather than silently filtering out
|
||||
// invalid items (unknown DecoId, StartTime >= EndTime, or overlapping ranges) - the same silent-drop
|
||||
// and silent-overlap bug class fixed for ReplaceTemplateItemsHandler in #144 S2 - reject the whole
|
||||
// request with a 422 so the caller knows exactly what is wrong. EndTime == TimeSpan.Zero means
|
||||
// "end of day" (24:00) and is treated as such for both the ordering and overlap checks.
|
||||
private static async Task<Validation<BaseError, DecoTemplate>> DecoTemplateItemsMustBeValid(
|
||||
TvContext dbContext,
|
||||
DecoTemplate decoTemplate,
|
||||
ReplaceDecoTemplateItems request)
|
||||
{
|
||||
var allDecoIds = request.Items.Map(i => i.DecoId).Distinct().ToList();
|
||||
|
||||
Dictionary<int, Deco> allDecos = await dbContext.Decos
|
||||
.AsNoTracking()
|
||||
.Filter(d => allDecoIds.Contains(d.Id))
|
||||
.ToListAsync()
|
||||
.Map(list => list.ToDictionary(d => d.Id, d => d));
|
||||
|
||||
var missingDecoIds = allDecoIds.Filter(id => !allDecos.ContainsKey(id)).ToList();
|
||||
if (missingDecoIds.Count > 0)
|
||||
{
|
||||
return BaseError.New($"[DecoId] {missingDecoIds.Head()} does not exist.");
|
||||
}
|
||||
|
||||
var itemsWithEffectiveEnd = request.Items
|
||||
.Map(i => new DecoTemplateItemRange(
|
||||
i.DecoId,
|
||||
i.StartTime,
|
||||
i.EndTime,
|
||||
i.EndTime == TimeSpan.Zero ? TimeSpan.FromHours(24) : i.EndTime))
|
||||
.ToList();
|
||||
|
||||
foreach (DecoTemplateItemRange item in itemsWithEffectiveEnd)
|
||||
{
|
||||
if (item.StartTime < TimeSpan.Zero || item.StartTime >= TimeSpan.FromHours(24) ||
|
||||
item.EndTime < TimeSpan.Zero || item.EndTime > TimeSpan.FromHours(24))
|
||||
{
|
||||
return BaseError.New(
|
||||
$"Deco from {item.StartTime} to {item.EndTime} must be within a single day (00:00 to 24:00)");
|
||||
}
|
||||
|
||||
if (item.StartTime >= item.EffectiveEndTime)
|
||||
{
|
||||
return BaseError.New(
|
||||
$"Deco from {item.StartTime} to {item.EndTime} must start before it ends");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (DecoTemplateItemRange item in itemsWithEffectiveEnd)
|
||||
{
|
||||
foreach (DecoTemplateItemRange otherItem in itemsWithEffectiveEnd)
|
||||
{
|
||||
if (item == otherItem)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.StartTime < otherItem.EffectiveEndTime && otherItem.StartTime < item.EffectiveEndTime)
|
||||
{
|
||||
return BaseError.New(
|
||||
$"Deco from {item.StartTime} to {item.EndTime} intersects deco from {otherItem.StartTime} to {otherItem.EndTime}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return decoTemplate;
|
||||
}
|
||||
|
||||
private sealed record DecoTemplateItemRange(int DecoId, TimeSpan StartTime, TimeSpan EndTime, TimeSpan EffectiveEndTime);
|
||||
|
||||
private static Task<Validation<BaseError, DecoTemplate>> DecoTemplateMustExist(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -76,16 +76,29 @@ public class ReplaceTemplateItemsHandler(IDbContextFactory<TvContext> dbContextF
|
||||
.ToListAsync()
|
||||
.Map(list => list.ToDictionary(b => b.Id, b => b));
|
||||
|
||||
var missingBlockIds = allBlockIds.Filter(id => !allBlocks.ContainsKey(id)).ToList();
|
||||
if (missingBlockIds.Count > 0)
|
||||
{
|
||||
return BaseError.New($"[BlockId] {missingBlockIds.Head()} does not exist.");
|
||||
}
|
||||
|
||||
var allTemplateItems = request.Items.Map(i =>
|
||||
{
|
||||
Block block = allBlocks[i.BlockId];
|
||||
return new BlockTemplateItem(
|
||||
i.BlockId,
|
||||
i.StartTime,
|
||||
i.StartTime + TimeSpan.FromMinutes(block.Minutes));
|
||||
var endTime = i.StartTime + TimeSpan.FromMinutes(block.Minutes);
|
||||
return new BlockTemplateItem(i.BlockId, i.StartTime, endTime);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
foreach (BlockTemplateItem item in allTemplateItems)
|
||||
{
|
||||
if (item.EndTime > TimeSpan.FromHours(24))
|
||||
{
|
||||
return BaseError.New(
|
||||
$"Block from {item.StartTime} to {item.EndTime} crosses midnight, which is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (BlockTemplateItem item in allTemplateItems)
|
||||
{
|
||||
foreach (BlockTemplateItem otherItem in allTemplateItems)
|
||||
|
||||
@@ -97,6 +97,7 @@ public class UpdateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
{
|
||||
ex.CollectionType = toUpdate.CollectionType;
|
||||
ex.CollectionId = toUpdate.CollectionId;
|
||||
ex.MediaItemId = toUpdate.MediaItemId;
|
||||
ex.MultiCollectionId = toUpdate.MultiCollectionId;
|
||||
ex.SmartCollectionId = toUpdate.SmartCollectionId;
|
||||
ex.PlaylistId = toUpdate.PlaylistId;
|
||||
@@ -111,6 +112,7 @@ public class UpdateDecoHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
DecoId = existing.Id,
|
||||
CollectionType = add.CollectionType,
|
||||
CollectionId = add.CollectionId,
|
||||
MediaItemId = add.MediaItemId,
|
||||
MultiCollectionId = add.MultiCollectionId,
|
||||
SmartCollectionId = add.SmartCollectionId,
|
||||
PlaylistId = add.PlaylistId,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
using ErsatzTV.Core.Api.Search;
|
||||
|
||||
namespace ErsatzTV.Application.Search;
|
||||
|
||||
public record GetSearchResults(string Query, int PageSize) : IRequest<SearchResultsResponseModel>;
|
||||
@@ -0,0 +1,65 @@
|
||||
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/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<GetSearchResults, SearchResultsResponseModel>
|
||||
{
|
||||
public async Task<SearchResultsResponseModel> Handle(
|
||||
GetSearchResults request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
async Task<SearchResultGroupResponseModel> ForKind(LibraryBrowseMediaType kind)
|
||||
{
|
||||
PagedLibraryBrowseItemsResponseModel paged = await mediator.Send(
|
||||
new GetLibraryBrowseItems(request.Query, null, kind, 0, 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<TvContext> (never shares one across calls),
|
||||
// so these are safe to run concurrently.
|
||||
Task<SearchResultGroupResponseModel> movies = ForKind(LibraryBrowseMediaType.Movie);
|
||||
Task<SearchResultGroupResponseModel> shows = ForKind(LibraryBrowseMediaType.TelevisionShow);
|
||||
Task<SearchResultGroupResponseModel> seasons = ForKind(LibraryBrowseMediaType.TelevisionSeason);
|
||||
Task<SearchResultGroupResponseModel> artists = ForKind(LibraryBrowseMediaType.Artist);
|
||||
Task<SearchResultGroupResponseModel> episodes = ForKind(LibraryBrowseMediaType.Episode);
|
||||
Task<SearchResultGroupResponseModel> musicVideos = ForKind(LibraryBrowseMediaType.MusicVideo);
|
||||
Task<SearchResultGroupResponseModel> songs = ForKind(LibraryBrowseMediaType.Song);
|
||||
Task<SearchResultGroupResponseModel> otherVideos = ForKind(LibraryBrowseMediaType.OtherVideo);
|
||||
Task<SearchResultGroupResponseModel> images = ForKind(LibraryBrowseMediaType.Image);
|
||||
Task<SearchResultGroupResponseModel> 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);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ErsatzTV.Application.Troubleshooting.Queries;
|
||||
|
||||
@@ -15,83 +12,10 @@ public class DecodePlayoutHistoryHandler(IDbContextFactory<TvContext> dbContextF
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var decodedKey = JsonConvert.DeserializeObject<BlockItemHistoryKey>(request.PlayoutHistory.Key);
|
||||
|
||||
PlaybackOrder playbackOrder = decodedKey.PlaybackOrder ?? PlaybackOrder.None;
|
||||
CollectionType collectionType = decodedKey.CollectionType ?? CollectionType.Collection;
|
||||
|
||||
string name = string.Empty;
|
||||
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.Collection:
|
||||
name = await dbContext.Collections
|
||||
.AsNoTracking()
|
||||
.Where(c => c.Id == (decodedKey.CollectionId ?? 0))
|
||||
.Map(c => c.Name)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
break;
|
||||
case CollectionType.SmartCollection:
|
||||
name = await dbContext.SmartCollections
|
||||
.AsNoTracking()
|
||||
.Where(c => c.Id == (decodedKey.SmartCollectionId ?? 0))
|
||||
.Map(c => c.Name)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
break;
|
||||
}
|
||||
|
||||
string mediaItemType = string.Empty;
|
||||
string mediaItemTitle = string.Empty;
|
||||
|
||||
Details details = JsonConvert.DeserializeObject<Details>(request.PlayoutHistory.Details);
|
||||
if (details?.MediaItemId != null)
|
||||
{
|
||||
Option<MediaItem> maybeMediaItem = await dbContext.MediaItems
|
||||
.AsNoTracking()
|
||||
.Include(i => i.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ThenInclude(l => l.MediaSource)
|
||||
.Include(i => (i as Movie).MovieMetadata)
|
||||
.Include(i => (i as Episode).EpisodeMetadata)
|
||||
.Include(i => (i as Episode).Season)
|
||||
.ThenInclude(s => s.Show)
|
||||
.ThenInclude(s => s.ShowMetadata)
|
||||
.Include(i => (i as OtherVideo).OtherVideoMetadata)
|
||||
.Include(i => (i as Image).ImageMetadata)
|
||||
.Include(i => (i as RemoteStream).RemoteStreamMetadata)
|
||||
.Include(i => (i as Song).SongMetadata)
|
||||
.Include(i => (i as MusicVideo).MusicVideoMetadata)
|
||||
.Include(i => (i as MusicVideo).Artist)
|
||||
.ThenInclude(a => a.ArtistMetadata)
|
||||
.SelectOneAsync(i => i.Id, i => i.Id == details.MediaItemId, cancellationToken);
|
||||
|
||||
foreach (var mediaItem in maybeMediaItem)
|
||||
{
|
||||
mediaItemType = mediaItem switch
|
||||
{
|
||||
Episode => "Episode",
|
||||
Movie => "Movie",
|
||||
MusicVideo => "Music Video",
|
||||
OtherVideo => "Other Video",
|
||||
Song => "Song",
|
||||
Image => "Image",
|
||||
RemoteStream => "Remote Stream",
|
||||
_ => $"Unknown ({mediaItem.GetType().Name})"
|
||||
};
|
||||
|
||||
mediaItemTitle = Playouts.Mapper.GetDisplayTitle(mediaItem, Option<string>.None);
|
||||
}
|
||||
}
|
||||
|
||||
return new PlayoutHistoryDetailsViewModel(playbackOrder, collectionType, name, mediaItemType, mediaItemTitle);
|
||||
return await PlayoutHistoryDecoder.Decode(
|
||||
dbContext,
|
||||
request.PlayoutHistory.Key,
|
||||
request.PlayoutHistory.Details,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private sealed record BlockItemHistoryKey(
|
||||
int? BlockId,
|
||||
PlaybackOrder? PlaybackOrder,
|
||||
CollectionType? CollectionType,
|
||||
int? CollectionId,
|
||||
int? SmartCollectionId);
|
||||
|
||||
private sealed record Details(int? MediaItemId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
using ErsatzTV.Core;
|
||||
|
||||
namespace ErsatzTV.Application.Troubleshooting.Queries;
|
||||
|
||||
public record GetPlayoutHistoryDetails(int Id) : IRequest<Either<BaseError, PlayoutHistoryDetailsViewModel>>;
|
||||
@@ -0,0 +1,42 @@
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ErsatzTV.Application.Troubleshooting.Queries;
|
||||
|
||||
public class GetPlayoutHistoryDetailsHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
: IRequestHandler<GetPlayoutHistoryDetails, Either<BaseError, PlayoutHistoryDetailsViewModel>>
|
||||
{
|
||||
public async Task<Either<BaseError, PlayoutHistoryDetailsViewModel>> Handle(
|
||||
GetPlayoutHistoryDetails request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
Option<PlayoutHistory> maybeHistory = await dbContext.PlayoutHistory
|
||||
.AsNoTracking()
|
||||
.SelectOneAsync(ph => ph.Id, ph => ph.Id == request.Id, cancellationToken);
|
||||
|
||||
foreach (PlayoutHistory history in maybeHistory)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await PlayoutHistoryDecoder.Decode(
|
||||
dbContext,
|
||||
history.Key,
|
||||
history.Details,
|
||||
cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// old/corrupt rows may carry malformed Key/Details JSON; surface a 422 rather than a 500
|
||||
return BaseError.New($"Unable to decode playout history: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
return new NotFoundError($"Playout history {request.Id} does not exist");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ErsatzTV.Application.Troubleshooting.Queries;
|
||||
|
||||
// Shared decode logic for a single PlayoutHistory row's Key/Details JSON. Both
|
||||
// DecodePlayoutHistoryHandler (Blazor) and GetPlayoutHistoryDetailsHandler (API) use this
|
||||
// so the collection/media-item lookup lives in exactly one place.
|
||||
internal static class PlayoutHistoryDecoder
|
||||
{
|
||||
public static async Task<PlayoutHistoryDetailsViewModel> Decode(
|
||||
TvContext dbContext,
|
||||
string key,
|
||||
string details,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var decodedKey = JsonConvert.DeserializeObject<BlockItemHistoryKey>(key);
|
||||
|
||||
PlaybackOrder playbackOrder = decodedKey.PlaybackOrder ?? PlaybackOrder.None;
|
||||
CollectionType collectionType = decodedKey.CollectionType ?? CollectionType.Collection;
|
||||
|
||||
string name = string.Empty;
|
||||
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.Collection:
|
||||
name = await dbContext.Collections
|
||||
.AsNoTracking()
|
||||
.Where(c => c.Id == (decodedKey.CollectionId ?? 0))
|
||||
.Map(c => c.Name)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
break;
|
||||
case CollectionType.SmartCollection:
|
||||
name = await dbContext.SmartCollections
|
||||
.AsNoTracking()
|
||||
.Where(c => c.Id == (decodedKey.SmartCollectionId ?? 0))
|
||||
.Map(c => c.Name)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
break;
|
||||
}
|
||||
|
||||
string mediaItemType = string.Empty;
|
||||
string mediaItemTitle = string.Empty;
|
||||
|
||||
Details decodedDetails = JsonConvert.DeserializeObject<Details>(details);
|
||||
if (decodedDetails?.MediaItemId != null)
|
||||
{
|
||||
Option<MediaItem> maybeMediaItem = await dbContext.MediaItems
|
||||
.AsNoTracking()
|
||||
.Include(i => i.LibraryPath)
|
||||
.ThenInclude(lp => lp.Library)
|
||||
.ThenInclude(l => l.MediaSource)
|
||||
.Include(i => (i as Movie).MovieMetadata)
|
||||
.Include(i => (i as Episode).EpisodeMetadata)
|
||||
.Include(i => (i as Episode).Season)
|
||||
.ThenInclude(s => s.Show)
|
||||
.ThenInclude(s => s.ShowMetadata)
|
||||
.Include(i => (i as OtherVideo).OtherVideoMetadata)
|
||||
.Include(i => (i as Image).ImageMetadata)
|
||||
.Include(i => (i as RemoteStream).RemoteStreamMetadata)
|
||||
.Include(i => (i as Song).SongMetadata)
|
||||
.Include(i => (i as MusicVideo).MusicVideoMetadata)
|
||||
.Include(i => (i as MusicVideo).Artist)
|
||||
.ThenInclude(a => a.ArtistMetadata)
|
||||
.SelectOneAsync(i => i.Id, i => i.Id == decodedDetails.MediaItemId, cancellationToken);
|
||||
|
||||
foreach (var mediaItem in maybeMediaItem)
|
||||
{
|
||||
mediaItemType = mediaItem switch
|
||||
{
|
||||
Episode => "Episode",
|
||||
Movie => "Movie",
|
||||
MusicVideo => "Music Video",
|
||||
OtherVideo => "Other Video",
|
||||
Song => "Song",
|
||||
Image => "Image",
|
||||
RemoteStream => "Remote Stream",
|
||||
_ => $"Unknown ({mediaItem.GetType().Name})"
|
||||
};
|
||||
|
||||
mediaItemTitle = Playouts.Mapper.GetDisplayTitle(mediaItem, Option<string>.None);
|
||||
}
|
||||
}
|
||||
|
||||
return new PlayoutHistoryDetailsViewModel(playbackOrder, collectionType, name, mediaItemType, mediaItemTitle);
|
||||
}
|
||||
|
||||
private sealed record BlockItemHistoryKey(
|
||||
int? BlockId,
|
||||
PlaybackOrder? PlaybackOrder,
|
||||
CollectionType? CollectionType,
|
||||
int? CollectionId,
|
||||
int? SmartCollectionId);
|
||||
|
||||
private sealed record Details(int? MediaItemId);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace ErsatzTV.Application.Troubleshooting.Queries;
|
||||
|
||||
public record ValidateSequentialSchedule(string Yaml, bool IsImport) : IRequest<ValidateSequentialScheduleViewModel>;
|
||||
@@ -0,0 +1,25 @@
|
||||
using ErsatzTV.Core.Interfaces.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Application.Troubleshooting.Queries;
|
||||
|
||||
public class ValidateSequentialScheduleHandler(ISequentialScheduleValidator validator)
|
||||
: IRequestHandler<ValidateSequentialSchedule, ValidateSequentialScheduleViewModel>
|
||||
{
|
||||
public async Task<ValidateSequentialScheduleViewModel> Handle(
|
||||
ValidateSequentialSchedule request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// ToJson runs first and can throw on malformed YAML (GetValidationMessages catches its
|
||||
// own exceptions internally); mirrors the Blazor YamlValidator ordering.
|
||||
string json = validator.ToJson(request.Yaml);
|
||||
IList<string> messages = await validator.GetValidationMessages(request.Yaml, request.IsImport);
|
||||
return new ValidateSequentialScheduleViewModel(messages.Count == 0, messages.ToList(), json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ValidateSequentialScheduleViewModel(false, [ex.Message], string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace ErsatzTV.Application.Troubleshooting;
|
||||
|
||||
public record ValidateSequentialScheduleViewModel(bool IsValid, List<string> Messages, string Json);
|
||||
@@ -1,5 +1,6 @@
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Core.Interfaces.Search;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
@@ -23,11 +24,14 @@ public class DeleteWatermarkHandler : IRequestHandler<DeleteWatermark, Either<Ba
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
Validation<BaseError, ChannelWatermark> validation = await WatermarkMustExist(
|
||||
dbContext,
|
||||
request,
|
||||
cancellationToken);
|
||||
return await validation.Apply(p => DoDeletion(dbContext, p));
|
||||
Option<ChannelWatermark> maybeWatermark = await WatermarkMustExist(dbContext, request, cancellationToken);
|
||||
|
||||
// must-exist maps to a NotFoundError Either directly (not via Validation, which
|
||||
// aggregates errors and loses the subtype the API layer maps to 404)
|
||||
return await maybeWatermark.Match(
|
||||
Some: watermark => DoDeletion(dbContext, watermark).Map(Right<BaseError, Unit>),
|
||||
None: () => Task.FromResult<Either<BaseError, Unit>>(
|
||||
new NotFoundError($"Watermark {request.WatermarkId} does not exist")));
|
||||
}
|
||||
|
||||
private async Task<Unit> DoDeletion(TvContext dbContext, ChannelWatermark watermark)
|
||||
@@ -40,11 +44,10 @@ public class DeleteWatermarkHandler : IRequestHandler<DeleteWatermark, Either<Ba
|
||||
return Unit.Default;
|
||||
}
|
||||
|
||||
private static Task<Validation<BaseError, ChannelWatermark>> WatermarkMustExist(
|
||||
private static Task<Option<ChannelWatermark>> WatermarkMustExist(
|
||||
TvContext dbContext,
|
||||
DeleteWatermark request,
|
||||
CancellationToken cancellationToken) =>
|
||||
dbContext.ChannelWatermarks
|
||||
.SelectOneAsync(p => p.Id, p => p.Id == request.WatermarkId, cancellationToken)
|
||||
.Map(o => o.ToValidation<BaseError>($"Watermark {request.WatermarkId} does not exist"));
|
||||
.SelectOneAsync(p => p.Id, p => p.Id == request.WatermarkId, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Core.Interfaces.Search;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
@@ -23,8 +24,18 @@ public class UpdateWatermarkHandler : IRequestHandler<UpdateWatermark, Either<Ba
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
Validation<BaseError, ChannelWatermark> validation = await Validate(dbContext, request, cancellationToken);
|
||||
return await validation.Apply(p => ApplyUpdateRequest(dbContext, p, request));
|
||||
Option<ChannelWatermark> maybeWatermark = await WatermarkMustExist(dbContext, request, cancellationToken);
|
||||
|
||||
// must-exist maps to a NotFoundError Either directly (not via Validation, which
|
||||
// aggregates errors and loses the subtype the API layer maps to 404)
|
||||
return await maybeWatermark.Match(
|
||||
Some: async watermark =>
|
||||
{
|
||||
Validation<BaseError, string> validation = await ValidateName(dbContext, request);
|
||||
return await validation.Apply((string _) => ApplyUpdateRequest(dbContext, watermark, request));
|
||||
},
|
||||
None: () => Task.FromResult<Either<BaseError, UpdateWatermarkResult>>(
|
||||
new NotFoundError("Watermark does not exist.")));
|
||||
}
|
||||
|
||||
private async Task<UpdateWatermarkResult> ApplyUpdateRequest(
|
||||
@@ -61,20 +72,12 @@ public class UpdateWatermarkHandler : IRequestHandler<UpdateWatermark, Either<Ba
|
||||
return new UpdateWatermarkResult(p.Id);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, ChannelWatermark>> Validate(
|
||||
TvContext dbContext,
|
||||
UpdateWatermark request,
|
||||
CancellationToken cancellationToken) =>
|
||||
(await WatermarkMustExist(dbContext, request, cancellationToken), await ValidateName(dbContext, request))
|
||||
.Apply((watermark, _) => watermark);
|
||||
|
||||
private static Task<Validation<BaseError, ChannelWatermark>> WatermarkMustExist(
|
||||
private static Task<Option<ChannelWatermark>> WatermarkMustExist(
|
||||
TvContext dbContext,
|
||||
UpdateWatermark updateWatermark,
|
||||
CancellationToken cancellationToken) =>
|
||||
dbContext.ChannelWatermarks
|
||||
.SelectOneAsync(p => p.Id, p => p.Id == updateWatermark.Id, cancellationToken)
|
||||
.Map(o => o.ToValidation<BaseError>("Watermark does not exist."));
|
||||
.SelectOneAsync(p => p.Id, p => p.Id == updateWatermark.Id, cancellationToken);
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -9,6 +9,26 @@ internal static class Mapper
|
||||
internal static WatermarkResponseModel ProjectToResponseModel(ChannelWatermark watermark) =>
|
||||
new(watermark.Id, watermark.Name);
|
||||
|
||||
internal static WatermarkFullResponseModel ProjectToFullResponseModel(ChannelWatermark watermark) =>
|
||||
new(
|
||||
watermark.Id,
|
||||
watermark.Name,
|
||||
watermark.Mode,
|
||||
watermark.ImageSource,
|
||||
watermark.Image,
|
||||
watermark.OriginalContentType,
|
||||
watermark.Location,
|
||||
watermark.Size,
|
||||
watermark.WidthPercent,
|
||||
watermark.HorizontalMarginPercent,
|
||||
watermark.VerticalMarginPercent,
|
||||
watermark.FrequencyMinutes,
|
||||
watermark.DurationSeconds,
|
||||
watermark.Opacity,
|
||||
watermark.OpacityExpression,
|
||||
watermark.ZIndex,
|
||||
watermark.PlaceWithinSourceContent);
|
||||
|
||||
public static WatermarkViewModel ProjectToViewModel(ChannelWatermark watermark) =>
|
||||
new(
|
||||
watermark.Id,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
using ErsatzTV.Core.Api.Watermarks;
|
||||
|
||||
namespace ErsatzTV.Application.Watermarks;
|
||||
|
||||
public record GetWatermarkByIdForApi(int Id) : IRequest<Option<WatermarkFullResponseModel>>;
|
||||
@@ -0,0 +1,22 @@
|
||||
using ErsatzTV.Core.Api.Watermarks;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Infrastructure.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static ErsatzTV.Application.Watermarks.Mapper;
|
||||
|
||||
namespace ErsatzTV.Application.Watermarks;
|
||||
|
||||
public class GetWatermarkByIdForApiHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
: IRequestHandler<GetWatermarkByIdForApi, Option<WatermarkFullResponseModel>>
|
||||
{
|
||||
public async Task<Option<WatermarkFullResponseModel>> Handle(
|
||||
GetWatermarkByIdForApi request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await dbContext.ChannelWatermarks
|
||||
.AsNoTracking()
|
||||
.SelectOneAsync(w => w.Id, w => w.Id == request.Id, cancellationToken)
|
||||
.MapT(ProjectToFullResponseModel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Emby;
|
||||
using ErsatzTV.Core.Jellyfin;
|
||||
using Flurl;
|
||||
|
||||
namespace ErsatzTV.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Roots an artwork value (as produced by the Application view-model mappers) into a directly-usable
|
||||
/// <c><img src></c> URL for the React SPA. The Blazor pages prefix "artwork/{folder}/" themselves and
|
||||
/// resolve relative to <c><base href="/"></c>, but the SPA renders the value raw from under <c>/app/</c>,
|
||||
/// so the API must root the URL itself (issue #180/#181). Mirrors the projection helper in
|
||||
/// GetLibraryBrowseItemsHandler so detail endpoints stay consistent with the browse grid.
|
||||
/// </summary>
|
||||
public static class ApiArtwork
|
||||
{
|
||||
public static string Root(string? artwork, ArtworkKind artworkKind)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(artwork))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
// Absolute URLs are already usable as-is (matches Blazor's GetPosterUrl guard).
|
||||
if (artwork.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
|
||||
artwork.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return artwork;
|
||||
}
|
||||
|
||||
string folder = artworkKind switch
|
||||
{
|
||||
ArtworkKind.Thumbnail => "thumbnails",
|
||||
ArtworkKind.FanArt => "fanart",
|
||||
_ => "posters"
|
||||
};
|
||||
|
||||
// Some mappers (e.g. Artists) leave the raw jellyfin://emby:// scheme in the value; convert it here so
|
||||
// the SPA gets a working proxy URL even when the source mapper didn't pre-convert. Movie/TV mappers
|
||||
// already produce a relative "jellyfin/{id}?..." path, which falls through to the plain prefix below.
|
||||
if (artwork.StartsWith("jellyfin://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Url url = JellyfinUrl.RelativeProxyForArtwork(artwork);
|
||||
if (artworkKind is ArtworkKind.Poster or ArtworkKind.Thumbnail)
|
||||
{
|
||||
url.SetQueryParam("fillHeight", 440);
|
||||
}
|
||||
|
||||
return $"/artwork/{folder}/{url}";
|
||||
}
|
||||
|
||||
if (artwork.StartsWith("emby://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Url url = EmbyUrl.RelativeProxyForArtwork(artwork);
|
||||
if (artworkKind is ArtworkKind.Poster or ArtworkKind.Thumbnail)
|
||||
{
|
||||
url.SetQueryParam("maxHeight", 440);
|
||||
}
|
||||
|
||||
return $"/artwork/{folder}/{url}";
|
||||
}
|
||||
|
||||
return $"/artwork/{folder}/{artwork}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Artists;
|
||||
|
||||
public record ArtistDetailResponseModel(
|
||||
int Id,
|
||||
string Name,
|
||||
string? Disambiguation,
|
||||
string? Biography,
|
||||
string Thumbnail,
|
||||
string FanArt,
|
||||
List<string> Genres,
|
||||
List<string> Styles,
|
||||
List<string> Moods,
|
||||
List<string> Languages);
|
||||
@@ -1,4 +1,5 @@
|
||||
using ErsatzTV.Core.Domain;
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.FFmpeg;
|
||||
|
||||
namespace ErsatzTV.Core.Api.FFmpegProfiles;
|
||||
@@ -7,13 +8,17 @@ public record FFmpegFullProfileResponseModel(
|
||||
int Id,
|
||||
string Name,
|
||||
int ThreadCount,
|
||||
bool NormalizeAudio,
|
||||
bool NormalizeVideo,
|
||||
HardwareAccelerationKind HardwareAcceleration,
|
||||
string VaapiDisplay,
|
||||
VaapiDriver VaapiDriver,
|
||||
string VaapiDevice,
|
||||
int? QsvExtraHardwareFrames,
|
||||
int ResolutionId,
|
||||
string Resolution,
|
||||
ScalingBehavior ScalingBehavior,
|
||||
FilterMode PadMode,
|
||||
FFmpegProfileVideoFormat VideoFormat,
|
||||
string VideoProfile,
|
||||
string VideoPreset,
|
||||
@@ -26,7 +31,9 @@ public record FFmpegFullProfileResponseModel(
|
||||
int AudioBitrate,
|
||||
int AudioBufferSize,
|
||||
NormalizeLoudnessMode NormalizeLoudnessMode,
|
||||
double? TargetLoudness,
|
||||
int AudioChannels,
|
||||
int AudioSampleRate,
|
||||
bool NormalizeFramerate,
|
||||
bool? DeinterlaceVideo);
|
||||
bool NormalizeColors,
|
||||
bool DeinterlaceVideo);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Filler;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Filler;
|
||||
|
||||
public record FillerPresetFullResponseModel(
|
||||
int Id,
|
||||
string Name,
|
||||
FillerKind FillerKind,
|
||||
FillerMode FillerMode,
|
||||
TimeSpan? Duration,
|
||||
int? Count,
|
||||
int? PadToNearestMinute,
|
||||
bool AllowWatermarks,
|
||||
CollectionType CollectionType,
|
||||
int? CollectionId,
|
||||
int? MediaItemId,
|
||||
int? MultiCollectionId,
|
||||
int? SmartCollectionId,
|
||||
int? PlaylistId,
|
||||
string? Expression,
|
||||
bool UseChaptersAsMediaItems);
|
||||
@@ -0,0 +1,10 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Images;
|
||||
|
||||
public record ImageFolderResponseModel(
|
||||
int LibraryFolderId,
|
||||
string Name,
|
||||
string FullPath,
|
||||
int SubfolderCount,
|
||||
int ImageCount,
|
||||
double? DurationSeconds);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Images;
|
||||
|
||||
public record UpdateImageFolderDurationResponseModel(double? DurationSeconds);
|
||||
@@ -19,4 +19,5 @@ public record LibraryBrowseItemResponseModel(
|
||||
int? SmartCollectionId,
|
||||
int? RerunCollectionId,
|
||||
int? MediaItemId,
|
||||
int? PlaylistId);
|
||||
int? PlaylistId,
|
||||
string? Subtitle = null);
|
||||
|
||||
@@ -11,5 +11,11 @@ public enum LibraryBrowseMediaType
|
||||
SmartCollection = 6,
|
||||
MultiCollection = 7,
|
||||
RerunCollection = 8,
|
||||
Playlist = 9
|
||||
Playlist = 9,
|
||||
Episode = 10,
|
||||
MusicVideo = 11,
|
||||
Song = 12,
|
||||
OtherVideo = 13,
|
||||
Image = 14,
|
||||
RemoteStream = 15
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Logs;
|
||||
|
||||
public record LogEntryResponseModel(
|
||||
DateTimeOffset Timestamp,
|
||||
string Level,
|
||||
string Message);
|
||||
@@ -0,0 +1,6 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Logs;
|
||||
|
||||
public record PagedLogEntriesResponseModel(
|
||||
int TotalCount,
|
||||
List<LogEntryResponseModel> Page);
|
||||
@@ -0,0 +1,8 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Media;
|
||||
|
||||
public record ActorResponseModel(
|
||||
int Id,
|
||||
string Name,
|
||||
string? Role,
|
||||
string Thumb);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.MediaCollections;
|
||||
|
||||
public record PlaylistGroupResponseModel(int Id, string Name, int PlaylistCount, bool IsSystem);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.MediaCollections;
|
||||
|
||||
public record PlaylistResponseModel(int Id, int PlaylistGroupId, string Name, bool IsSystem);
|
||||
@@ -0,0 +1,49 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
|
||||
namespace ErsatzTV.Core.Api.MediaItems;
|
||||
|
||||
public record MediaItemInfoResponseModel(
|
||||
int Id,
|
||||
string Title,
|
||||
string Kind,
|
||||
string LibraryKind,
|
||||
string? ServerName,
|
||||
string LibraryName,
|
||||
MediaItemState State,
|
||||
TimeSpan Duration,
|
||||
string? SampleAspectRatio,
|
||||
string? DisplayAspectRatio,
|
||||
string? RFrameRate,
|
||||
VideoScanKind VideoScanKind,
|
||||
double? InterlacedRatio,
|
||||
int Width,
|
||||
int Height,
|
||||
List<MediaItemInfoStreamResponseModel> Streams,
|
||||
List<MediaItemInfoChapterResponseModel> Chapters);
|
||||
|
||||
public record MediaItemInfoStreamResponseModel(
|
||||
int? Index,
|
||||
MediaStreamKind Kind,
|
||||
string? Title,
|
||||
string? Codec,
|
||||
string? Profile,
|
||||
string? Language,
|
||||
int? Channels,
|
||||
bool? Default,
|
||||
bool? Forced,
|
||||
bool? AttachedPic,
|
||||
string? PixelFormat,
|
||||
string? ColorRange,
|
||||
string? ColorSpace,
|
||||
string? ColorTransfer,
|
||||
string? ColorPrimaries,
|
||||
int? BitsPerRawSample,
|
||||
string? MimeType,
|
||||
string? FileName,
|
||||
bool? IsExtracted);
|
||||
|
||||
public record MediaItemInfoChapterResponseModel(
|
||||
string? Title,
|
||||
TimeSpan StartTime,
|
||||
TimeSpan EndTime);
|
||||
@@ -0,0 +1,24 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Api.Media;
|
||||
using ErsatzTV.Core.Domain;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Movies;
|
||||
|
||||
public record MovieDetailResponseModel(
|
||||
int Id,
|
||||
string Title,
|
||||
string? Year,
|
||||
string? Plot,
|
||||
List<string> Genres,
|
||||
List<string> Tags,
|
||||
List<string> Studios,
|
||||
List<string> ContentRatings,
|
||||
List<string> Languages,
|
||||
List<ActorResponseModel> Actors,
|
||||
List<string> Directors,
|
||||
List<string> Writers,
|
||||
string? Path,
|
||||
string? LocalPath,
|
||||
MediaItemState State,
|
||||
string Poster,
|
||||
string FanArt);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Playouts;
|
||||
|
||||
public record PagedPlayoutHistoryResponseModel(int TotalCount, List<PlayoutHistoryResponseModel> Page);
|
||||
@@ -0,0 +1,17 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Playouts;
|
||||
|
||||
public record PlayoutAlternateScheduleResponseModel(
|
||||
int Id,
|
||||
int Index,
|
||||
int ProgramScheduleId,
|
||||
ICollection<DayOfWeek> DaysOfWeek,
|
||||
ICollection<int> DaysOfMonth,
|
||||
ICollection<int> MonthsOfYear,
|
||||
bool LimitToDateRange,
|
||||
int StartMonth,
|
||||
int StartDay,
|
||||
int? StartYear,
|
||||
int EndMonth,
|
||||
int EndDay,
|
||||
int? EndYear);
|
||||
@@ -0,0 +1,11 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Playouts;
|
||||
|
||||
public record PlayoutHistoryDetailsResponseModel(
|
||||
PlaybackOrder PlaybackOrder,
|
||||
CollectionType CollectionType,
|
||||
string Name,
|
||||
string MediaItemType,
|
||||
string MediaItemTitle);
|
||||
@@ -0,0 +1,9 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Playouts;
|
||||
|
||||
public record PlayoutHistoryResponseModel(
|
||||
int Id,
|
||||
DateTimeOffset When,
|
||||
DateTimeOffset Finish,
|
||||
string Key,
|
||||
string Details);
|
||||
@@ -12,7 +12,9 @@ public record PlayoutResponseModel(
|
||||
string ScheduleName,
|
||||
string? ScheduleFile,
|
||||
TimeSpan? DailyRebuildTime,
|
||||
PlayoutBuildStatusResponseModel? BuildStatus)
|
||||
PlayoutBuildStatusResponseModel? BuildStatus,
|
||||
int? DecoId,
|
||||
string? DecoName)
|
||||
{
|
||||
public static PlayoutResponseModel From(
|
||||
int id,
|
||||
@@ -23,7 +25,9 @@ public record PlayoutResponseModel(
|
||||
string scheduleName,
|
||||
string? scheduleFile,
|
||||
TimeSpan? dailyRebuildTime,
|
||||
PlayoutBuildStatusResponseModel? buildStatus) =>
|
||||
PlayoutBuildStatusResponseModel? buildStatus,
|
||||
int? decoId,
|
||||
string? decoName) =>
|
||||
new(
|
||||
id,
|
||||
scheduleKind,
|
||||
@@ -33,5 +37,7 @@ public record PlayoutResponseModel(
|
||||
scheduleName,
|
||||
scheduleFile,
|
||||
dailyRebuildTime,
|
||||
buildStatus);
|
||||
buildStatus,
|
||||
decoId,
|
||||
decoName);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockGroupResponseModel(int Id, string Name);
|
||||
@@ -0,0 +1,24 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockItemResponseModel(
|
||||
int Id,
|
||||
int Index,
|
||||
CollectionType CollectionType,
|
||||
int? CollectionId,
|
||||
string? CollectionName,
|
||||
int? MultiCollectionId,
|
||||
string? MultiCollectionName,
|
||||
int? SmartCollectionId,
|
||||
string? SmartCollectionName,
|
||||
int? MediaItemId,
|
||||
string? MediaItemName,
|
||||
string SearchTitle,
|
||||
string SearchQuery,
|
||||
PlaybackOrder PlaybackOrder,
|
||||
bool IncludeInProgramGuide,
|
||||
bool DisableWatermarks,
|
||||
List<int> WatermarkIds,
|
||||
List<int> GraphicsElementIds);
|
||||
@@ -0,0 +1,8 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockPreviewItemResponseModel(
|
||||
string Title,
|
||||
TimeSpan Start,
|
||||
TimeSpan Finish,
|
||||
string Duration);
|
||||
@@ -0,0 +1,12 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockResponseModel(
|
||||
int Id,
|
||||
int GroupId,
|
||||
string GroupName,
|
||||
string Name,
|
||||
int Minutes,
|
||||
BlockStopScheduling StopScheduling);
|
||||
@@ -0,0 +1,13 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockWithItemsResponseModel(
|
||||
int Id,
|
||||
int GroupId,
|
||||
string GroupName,
|
||||
string Name,
|
||||
int Minutes,
|
||||
BlockStopScheduling StopScheduling,
|
||||
List<BlockItemResponseModel> Items);
|
||||
@@ -0,0 +1,17 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoBreakContentResponseModel(
|
||||
int Id,
|
||||
CollectionType CollectionType,
|
||||
int? CollectionId,
|
||||
int? MediaItemId,
|
||||
int? MultiCollectionId,
|
||||
int? SmartCollectionId,
|
||||
int? PlaylistId,
|
||||
int? PlaylistGroupId,
|
||||
string? SelectionName,
|
||||
DecoBreakPlacement Placement);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoGroupResponseModel(int Id, string Name, int DecoCount);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoListItemResponseModel(int Id, int DecoGroupId, string DecoGroupName, string Name);
|
||||
@@ -0,0 +1,34 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoResponseModel(
|
||||
int Id,
|
||||
int DecoGroupId,
|
||||
string DecoGroupName,
|
||||
string Name,
|
||||
DecoMode WatermarkMode,
|
||||
List<int> WatermarkIds,
|
||||
bool UseWatermarkDuringFiller,
|
||||
DecoMode GraphicsElementsMode,
|
||||
List<int> GraphicsElementIds,
|
||||
bool UseGraphicsElementsDuringFiller,
|
||||
DecoMode BreakContentMode,
|
||||
List<DecoBreakContentResponseModel> BreakContent,
|
||||
DecoMode DefaultFillerMode,
|
||||
CollectionType DefaultFillerCollectionType,
|
||||
int? DefaultFillerCollectionId,
|
||||
int? DefaultFillerMediaItemId,
|
||||
int? DefaultFillerMultiCollectionId,
|
||||
int? DefaultFillerSmartCollectionId,
|
||||
string? DefaultFillerSelectionName,
|
||||
bool DefaultFillerTrimToFit,
|
||||
DecoMode DeadAirFallbackMode,
|
||||
CollectionType DeadAirFallbackCollectionType,
|
||||
int? DeadAirFallbackCollectionId,
|
||||
int? DeadAirFallbackMediaItemId,
|
||||
int? DeadAirFallbackMultiCollectionId,
|
||||
int? DeadAirFallbackSmartCollectionId,
|
||||
string? DeadAirFallbackSelectionName);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoTemplateGroupResponseModel(int Id, string Name, int DecoTemplateCount);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoTemplateItemResponseModel(int DecoId, string DecoName, TimeSpan StartTime, TimeSpan EndTime);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoTemplateResponseModel(int Id, int DecoTemplateGroupId, string GroupName, string Name);
|
||||
@@ -0,0 +1,9 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record DecoTemplateWithItemsResponseModel(
|
||||
int Id,
|
||||
int DecoTemplateGroupId,
|
||||
string GroupName,
|
||||
string Name,
|
||||
List<DecoTemplateItemResponseModel> Items);
|
||||
@@ -0,0 +1,22 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record PlayoutTemplateResponseModel(
|
||||
int Id,
|
||||
int Index,
|
||||
int TemplateId,
|
||||
string TemplateName,
|
||||
string TemplateGroupName,
|
||||
int? DecoTemplateId,
|
||||
string? DecoTemplateName,
|
||||
string? DecoTemplateGroupName,
|
||||
ICollection<DayOfWeek> DaysOfWeek,
|
||||
ICollection<int> DaysOfMonth,
|
||||
ICollection<int> MonthsOfYear,
|
||||
bool LimitToDateRange,
|
||||
int StartMonth,
|
||||
int StartDay,
|
||||
int? StartYear,
|
||||
int EndMonth,
|
||||
int EndDay,
|
||||
int? EndYear);
|
||||
@@ -0,0 +1,8 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// A lightweight {id, name} option used by the block/schedule editor pickers
|
||||
/// (collection, television show, television season, smart collection search).
|
||||
/// </summary>
|
||||
public record SchedulingPickerOptionResponseModel(int Id, string Name);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateGroupResponseModel(int Id, string Name, int TemplateCount);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateItemResponseModel(int BlockId, string BlockName, int BlockMinutes, TimeSpan StartTime);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateResponseModel(int Id, int TemplateGroupId, string GroupName, string Name);
|
||||
@@ -0,0 +1,9 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateWithItemsResponseModel(
|
||||
int Id,
|
||||
int TemplateGroupId,
|
||||
string GroupName,
|
||||
string Name,
|
||||
List<TemplateItemResponseModel> Items);
|
||||
@@ -0,0 +1,8 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Api.LibraryBrowse;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Search;
|
||||
|
||||
public record SearchResultGroupResponseModel(
|
||||
int TotalCount,
|
||||
List<LibraryBrowseItemResponseModel> Items);
|
||||
@@ -0,0 +1,14 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Search;
|
||||
|
||||
public record SearchResultsResponseModel(
|
||||
SearchResultGroupResponseModel Movies,
|
||||
SearchResultGroupResponseModel Shows,
|
||||
SearchResultGroupResponseModel Seasons,
|
||||
SearchResultGroupResponseModel Artists,
|
||||
SearchResultGroupResponseModel Episodes,
|
||||
SearchResultGroupResponseModel MusicVideos,
|
||||
SearchResultGroupResponseModel Songs,
|
||||
SearchResultGroupResponseModel OtherVideos,
|
||||
SearchResultGroupResponseModel Images,
|
||||
SearchResultGroupResponseModel RemoteStreams);
|
||||
@@ -0,0 +1,11 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Television;
|
||||
|
||||
public record SeasonDetailResponseModel(
|
||||
int Id,
|
||||
int ShowId,
|
||||
string Title,
|
||||
string? Year,
|
||||
string Name,
|
||||
string Poster,
|
||||
string FanArt);
|
||||
@@ -0,0 +1,22 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Api.Media;
|
||||
using ErsatzTV.Core.Domain;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Television;
|
||||
|
||||
public record ShowDetailResponseModel(
|
||||
int Id,
|
||||
int LibraryId,
|
||||
MediaSourceKind MediaSourceKind,
|
||||
string Title,
|
||||
string? Year,
|
||||
string? Plot,
|
||||
string Poster,
|
||||
string FanArt,
|
||||
List<string> Genres,
|
||||
List<string> Tags,
|
||||
List<string> Studios,
|
||||
List<string> Networks,
|
||||
List<string> ContentRatings,
|
||||
List<string> Languages,
|
||||
List<ActorResponseModel> Actors);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Trakt;
|
||||
|
||||
public record PagedTraktListsResponseModel(int TotalCount, List<TraktListResponseModel> Page);
|
||||
@@ -0,0 +1,12 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Trakt;
|
||||
|
||||
public record TraktListResponseModel(
|
||||
int Id,
|
||||
int TraktId,
|
||||
string Slug,
|
||||
string Name,
|
||||
int ItemCount,
|
||||
int MatchCount,
|
||||
bool AutoRefresh,
|
||||
bool GeneratePlaylist);
|
||||
@@ -0,0 +1,8 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Trakt;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP-observable substitute for the Blazor <c>IEntityLocker.OnTraktChanged</c> event — the SPA polls this
|
||||
/// while an add/match/delete operation is in flight (no push channel exists for the REST API).
|
||||
/// </summary>
|
||||
public record TraktStatusResponseModel(bool Busy);
|
||||
@@ -0,0 +1,14 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Troubleshooting;
|
||||
|
||||
// GeneralJson mirrors the JSON blob rendered on the "General" tab of the legacy Blazor
|
||||
// Troubleshooting page (version, environment, cpus, video controllers, health, ffmpeg settings,
|
||||
// AviSynth flags, channels, ffmpeg profiles) - kept pre-serialized so the SPA can render/copy it
|
||||
// verbatim without re-deriving the same shape. The remaining fields mirror the per-platform
|
||||
// capability dump tabs (only the ones relevant to the current OS/GPU are non-empty).
|
||||
public record TroubleshootingInfoResponseModel(
|
||||
string GeneralJson,
|
||||
string? NvidiaCapabilities,
|
||||
string? QsvCapabilities,
|
||||
string? VaapiCapabilities,
|
||||
string? VideoToolboxCapabilities);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Troubleshooting;
|
||||
|
||||
public record ValidateSequentialScheduleResponseModel(bool IsValid, List<string> Messages, string Json);
|
||||
@@ -0,0 +1,24 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.FFmpeg.State;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Watermarks;
|
||||
|
||||
public record WatermarkFullResponseModel(
|
||||
int Id,
|
||||
string Name,
|
||||
ChannelWatermarkMode Mode,
|
||||
ChannelWatermarkImageSource ImageSource,
|
||||
string? Image,
|
||||
string? ImageContentType,
|
||||
WatermarkLocation Location,
|
||||
WatermarkSize Size,
|
||||
double Width,
|
||||
double HorizontalMargin,
|
||||
double VerticalMargin,
|
||||
int FrequencyMinutes,
|
||||
int DurationSeconds,
|
||||
int Opacity,
|
||||
string? OpacityExpression,
|
||||
int ZIndex,
|
||||
bool PlaceWithinSourceContent);
|
||||
@@ -86,7 +86,7 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
result.Page[0].MediaItemId.ShouldBe(20);
|
||||
result.Page[1].MediaType.ShouldBe(LibraryBrowseMediaType.Movie);
|
||||
result.Page[1].Title.ShouldBe("Collision Movie");
|
||||
result.Page[1].Artwork.ShouldBe("movie-poster.jpg");
|
||||
result.Page[1].Artwork.ShouldBe("/artwork/posters/movie-poster.jpg");
|
||||
result.Page[1].Duration.ShouldBe(TimeSpan.FromMinutes(95));
|
||||
result.Page[1].MediaItemId.ShouldBe(10);
|
||||
}
|
||||
@@ -203,7 +203,7 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
result.TotalCount.ShouldBe(1);
|
||||
result.Page.Count.ShouldBe(1);
|
||||
result.Page[0].Title.ShouldBe("Manual Metadata");
|
||||
result.Page[0].Artwork.ShouldBe("first-poster.jpg");
|
||||
result.Page[0].Artwork.ShouldBe("/artwork/posters/first-poster.jpg");
|
||||
result.Page[0].Duration.ShouldBe(TimeSpan.FromMinutes(75));
|
||||
result.Page[0].ItemCount.ShouldBe(2);
|
||||
}
|
||||
@@ -236,9 +236,111 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
result.Page[0].ItemCount.ShouldBe(2);
|
||||
result.Page[0].CollectionType.ShouldBe(CollectionType.TelevisionSeason);
|
||||
result.Page[0].MediaItemId.ShouldBe(301);
|
||||
// Season 301 has its own poster.
|
||||
result.Page[0].Artwork.ShouldBe("/artwork/posters/season-2.jpg");
|
||||
result.Page[1].Title.ShouldBe("Season Show - Specials");
|
||||
result.Page[1].ItemCount.ShouldBe(1);
|
||||
result.Page[1].MediaItemId.ShouldBe(302);
|
||||
// Specials has no poster of its own, so it falls back to the show's poster.
|
||||
result.Page[1].Artwork.ShouldBe("/artwork/posters/show.jpg");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Handle_Should_Browse_Seasons_For_A_Specific_Show_By_ParentId()
|
||||
{
|
||||
await SeedSeasonGraph();
|
||||
// ParentId drill-in bypasses the search index entirely.
|
||||
var handler = new GetLibraryBrowseItemsHandler(_searchIndex, _db.Factory);
|
||||
|
||||
PagedLibraryBrowseItemsResponseModel result = await handler.Handle(
|
||||
new GetLibraryBrowseItems("", null, LibraryBrowseMediaType.TelevisionSeason, 0, 10, 300),
|
||||
CancellationToken.None);
|
||||
|
||||
result.TotalCount.ShouldBe(2);
|
||||
// Ordered by season number: Specials (0) then Season 2.
|
||||
result.Page[0].Title.ShouldBe("Season Show - Specials");
|
||||
result.Page[0].MediaItemId.ShouldBe(302);
|
||||
result.Page[1].Title.ShouldBe("Season Show - Season 2");
|
||||
result.Page[1].MediaItemId.ShouldBe(301);
|
||||
|
||||
await _searchIndex.DidNotReceive().Search(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<List<string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Handle_Should_Browse_Episodes_For_A_Specific_Season_By_ParentId()
|
||||
{
|
||||
await SeedEpisodeDrillInGraph();
|
||||
var handler = new GetLibraryBrowseItemsHandler(_searchIndex, _db.Factory);
|
||||
|
||||
PagedLibraryBrowseItemsResponseModel result = await handler.Handle(
|
||||
new GetLibraryBrowseItems("", null, LibraryBrowseMediaType.Episode, 0, 10, 701),
|
||||
CancellationToken.None);
|
||||
|
||||
result.TotalCount.ShouldBe(3);
|
||||
// Ordered by episode number regardless of insertion order.
|
||||
result.Page[0].MediaItemId.ShouldBe(712);
|
||||
result.Page[1].MediaItemId.ShouldBe(711);
|
||||
result.Page[2].MediaItemId.ShouldBe(713);
|
||||
|
||||
await _searchIndex.DidNotReceive().Search(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<List<string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Handle_Should_Browse_Music_Videos_For_A_Specific_Artist_By_ParentId()
|
||||
{
|
||||
await SeedMusicVideoDrillInGraph();
|
||||
var handler = new GetLibraryBrowseItemsHandler(_searchIndex, _db.Factory);
|
||||
|
||||
PagedLibraryBrowseItemsResponseModel result = await handler.Handle(
|
||||
new GetLibraryBrowseItems("", null, LibraryBrowseMediaType.MusicVideo, 0, 10, 801),
|
||||
CancellationToken.None);
|
||||
|
||||
result.TotalCount.ShouldBe(2);
|
||||
// Ordered by album then track: "Album A"/track 1 before "Album B"/track 1.
|
||||
result.Page[0].MediaItemId.ShouldBe(812);
|
||||
result.Page[1].MediaItemId.ShouldBe(811);
|
||||
|
||||
await _searchIndex.DidNotReceive().Search(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<List<string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Handle_Should_Root_Jellyfin_Artwork_Urls_With_FillHeight()
|
||||
{
|
||||
await SeedJellyfinMovieGraph();
|
||||
_searchIndex.Search(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<int>(),
|
||||
Arg.Any<List<string>>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(new SearchResult([new SearchItem(LuceneSearchIndex.MovieType, 601)], 1));
|
||||
var handler = new GetLibraryBrowseItemsHandler(_searchIndex, _db.Factory);
|
||||
|
||||
PagedLibraryBrowseItemsResponseModel result = await handler.Handle(
|
||||
new GetLibraryBrowseItems("", null, LibraryBrowseMediaType.Movie, 0, 10),
|
||||
CancellationToken.None);
|
||||
|
||||
result.TotalCount.ShouldBe(1);
|
||||
result.Page[0].Artwork.ShouldBe("/artwork/posters/jellyfin/Items/abc/Images/Primary?tag=xyz&fillHeight=440");
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -262,7 +364,7 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
result.TotalCount.ShouldBe(1);
|
||||
result.Page[0].Title.ShouldBe("Counted Artist");
|
||||
result.Page[0].ItemCount.ShouldBe(2);
|
||||
result.Page[0].Artwork.ShouldBe("artist-thumb.jpg");
|
||||
result.Page[0].Artwork.ShouldBe("/artwork/thumbnails/artist-thumb.jpg");
|
||||
result.Page[0].CollectionType.ShouldBe(CollectionType.Artist);
|
||||
result.Page[0].MediaItemId.ShouldBe(401);
|
||||
}
|
||||
@@ -456,8 +558,8 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
Seasons = [],
|
||||
ShowMetadata = [MakeShowMetadata("Season Show", "show.jpg")]
|
||||
};
|
||||
var season = MakeSeason(301, path, show, 2);
|
||||
var specials = MakeSeason(302, path, show, 0);
|
||||
var season = MakeSeason(301, path, show, 2, "season-2.jpg");
|
||||
var specials = MakeSeason(302, path, show, 0, string.Empty);
|
||||
season.Episodes.AddRange([
|
||||
MakeEpisode(311, path, season),
|
||||
MakeEpisode(312, path, season)
|
||||
@@ -472,6 +574,116 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task SeedEpisodeDrillInGraph()
|
||||
{
|
||||
await using TvContext context = _db.CreateContext();
|
||||
(LocalLibrary library, LibraryPath path) = MakeLibrary(700, "Episode Library");
|
||||
var show = new Show
|
||||
{
|
||||
Id = 700,
|
||||
LibraryPath = path,
|
||||
Collections = [],
|
||||
CollectionItems = [],
|
||||
TraktListItems = [],
|
||||
Seasons = [],
|
||||
ShowMetadata = [MakeShowMetadata("Drill Show", "show.jpg")]
|
||||
};
|
||||
var season = MakeSeason(701, path, show, 1, "season.jpg");
|
||||
|
||||
// Inserted out of episode-number order to prove the handler sorts by number.
|
||||
Episode e2 = MakeNumberedEpisode(711, path, season, 2);
|
||||
Episode e1 = MakeNumberedEpisode(712, path, season, 1);
|
||||
Episode e3 = MakeNumberedEpisode(713, path, season, 3);
|
||||
season.Episodes.AddRange([e2, e1, e3]);
|
||||
show.Seasons.Add(season);
|
||||
path.MediaItems.AddRange([show, season, e2, e1, e3]);
|
||||
|
||||
context.LocalLibraries.Add(library);
|
||||
context.Shows.Add(show);
|
||||
context.Seasons.Add(season);
|
||||
context.Episodes.AddRange(e2, e1, e3);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task SeedMusicVideoDrillInGraph()
|
||||
{
|
||||
await using TvContext context = _db.CreateContext();
|
||||
(LocalLibrary library, LibraryPath path) = MakeLibrary(800, "Music Video Library");
|
||||
var artist = new Artist
|
||||
{
|
||||
Id = 801,
|
||||
LibraryPath = path,
|
||||
Collections = [],
|
||||
CollectionItems = [],
|
||||
TraktListItems = [],
|
||||
MusicVideos = [],
|
||||
ArtistMetadata = [MakeArtistMetadata("Drill Artist", "artist.jpg")]
|
||||
};
|
||||
|
||||
MusicVideo mvB = MakeTitledMusicVideo(811, path, artist, "Track On B", "Album B", 1);
|
||||
MusicVideo mvA = MakeTitledMusicVideo(812, path, artist, "Track On A", "Album A", 1);
|
||||
artist.MusicVideos.AddRange([mvB, mvA]);
|
||||
path.MediaItems.AddRange([artist, mvB, mvA]);
|
||||
|
||||
context.LocalLibraries.Add(library);
|
||||
context.Artists.Add(artist);
|
||||
context.MusicVideos.AddRange(mvB, mvA);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private static Episode MakeNumberedEpisode(int id, LibraryPath path, Season season, int episodeNumber)
|
||||
{
|
||||
Episode episode = MakeEpisode(id, path, season);
|
||||
episode.EpisodeMetadata =
|
||||
[
|
||||
new EpisodeMetadata
|
||||
{
|
||||
Title = $"Episode {episodeNumber}",
|
||||
SortTitle = $"Episode {episodeNumber}",
|
||||
EpisodeNumber = episodeNumber,
|
||||
Artwork = [],
|
||||
Genres = [],
|
||||
Tags = [],
|
||||
Studios = [],
|
||||
Actors = [],
|
||||
Guids = [],
|
||||
Subtitles = [],
|
||||
Directors = [],
|
||||
Writers = []
|
||||
}
|
||||
];
|
||||
return episode;
|
||||
}
|
||||
|
||||
private static MusicVideo MakeTitledMusicVideo(
|
||||
int id,
|
||||
LibraryPath path,
|
||||
Artist artist,
|
||||
string title,
|
||||
string album,
|
||||
int track)
|
||||
{
|
||||
MusicVideo musicVideo = MakeMusicVideo(id, path, artist);
|
||||
musicVideo.MusicVideoMetadata =
|
||||
[
|
||||
new MusicVideoMetadata
|
||||
{
|
||||
Title = title,
|
||||
SortTitle = title,
|
||||
Album = album,
|
||||
Track = track,
|
||||
Artwork = [],
|
||||
Genres = [],
|
||||
Tags = [],
|
||||
Studios = [],
|
||||
Actors = [],
|
||||
Guids = [],
|
||||
Subtitles = []
|
||||
}
|
||||
];
|
||||
return musicVideo;
|
||||
}
|
||||
|
||||
private async Task SeedArtistGraph()
|
||||
{
|
||||
await using TvContext context = _db.CreateContext();
|
||||
@@ -497,6 +709,50 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task SeedJellyfinMovieGraph()
|
||||
{
|
||||
await using TvContext context = _db.CreateContext();
|
||||
(LocalLibrary library, LibraryPath path) = MakeLibrary(600, "Jellyfin Library");
|
||||
var movie = new Movie
|
||||
{
|
||||
Id = 601,
|
||||
LibraryPath = path,
|
||||
Collections = [],
|
||||
CollectionItems = [],
|
||||
TraktListItems = [],
|
||||
MediaVersions = [new MediaVersion { Duration = TimeSpan.FromMinutes(100) }],
|
||||
MovieMetadata =
|
||||
[
|
||||
new MovieMetadata
|
||||
{
|
||||
Title = "Jellyfin Movie",
|
||||
SortTitle = "Jellyfin Movie",
|
||||
Artwork =
|
||||
[
|
||||
new Artwork
|
||||
{
|
||||
Path = "jellyfin://Items/abc/Images/Primary?tag=xyz",
|
||||
ArtworkKind = ArtworkKind.Poster
|
||||
}
|
||||
],
|
||||
Genres = [],
|
||||
Tags = [],
|
||||
Studios = [],
|
||||
Actors = [],
|
||||
Guids = [],
|
||||
Subtitles = [],
|
||||
Directors = [],
|
||||
Writers = []
|
||||
}
|
||||
]
|
||||
};
|
||||
path.MediaItems.Add(movie);
|
||||
|
||||
context.LocalLibraries.Add(library);
|
||||
context.Movies.Add(movie);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task SeedLibraryFilteredCollectionsGraph()
|
||||
{
|
||||
await using TvContext context = _db.CreateContext();
|
||||
@@ -563,7 +819,7 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
MediaVersions = [new MediaVersion { Duration = duration }]
|
||||
};
|
||||
|
||||
private static Season MakeSeason(int id, LibraryPath path, Show show, int seasonNumber) =>
|
||||
private static Season MakeSeason(int id, LibraryPath path, Show show, int seasonNumber, string poster) =>
|
||||
new()
|
||||
{
|
||||
Id = id,
|
||||
@@ -574,7 +830,7 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
CollectionItems = [],
|
||||
TraktListItems = [],
|
||||
Episodes = [],
|
||||
SeasonMetadata = [MakeSeasonMetadata()]
|
||||
SeasonMetadata = [MakeSeasonMetadata(poster)]
|
||||
};
|
||||
|
||||
private static Episode MakeEpisode(int id, LibraryPath path, Season season) =>
|
||||
@@ -633,12 +889,14 @@ public class GetLibraryBrowseItemsHandlerTests
|
||||
Subtitles = []
|
||||
};
|
||||
|
||||
private static SeasonMetadata MakeSeasonMetadata() =>
|
||||
private static SeasonMetadata MakeSeasonMetadata(string poster = "") =>
|
||||
new()
|
||||
{
|
||||
Title = string.Empty,
|
||||
SortTitle = string.Empty,
|
||||
Artwork = [],
|
||||
Artwork = string.IsNullOrEmpty(poster)
|
||||
? []
|
||||
: [new Artwork { Path = poster, ArtworkKind = ArtworkKind.Poster }],
|
||||
Genres = [],
|
||||
Tags = [],
|
||||
Studios = [],
|
||||
|
||||
@@ -2,8 +2,11 @@ using ErsatzTV.Application;
|
||||
using ErsatzTV.Application.MediaCollections;
|
||||
using ErsatzTV.Application.Search;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.LibraryBrowse;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Core.Interfaces.Repositories;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using LanguageExt;
|
||||
using ErsatzTV.Tests.Support;
|
||||
using NSubstitute;
|
||||
@@ -130,6 +133,93 @@ public class CollectionHandlerTests : MediaCollectionHandlerTestBase
|
||||
LeftOf(result).ShouldBeOfType<NotFoundError>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_NotFoundError_When_Collection_Missing()
|
||||
{
|
||||
var handler = new GetCollectionItemsHandler(Db.Factory);
|
||||
|
||||
Either<BaseError, PagedLibraryBrowseItemsResponseModel> result =
|
||||
await handler.Handle(new GetCollectionItems(999, 0, 100), CancellationToken.None);
|
||||
|
||||
LeftOf(result).ShouldBeOfType<NotFoundError>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_Members_With_Rooted_Artwork()
|
||||
{
|
||||
await SeedCollectionWithMovie(collectionId: 1, movieId: 10, title: "Fake Movie", poster: "movie.jpg");
|
||||
var handler = new GetCollectionItemsHandler(Db.Factory);
|
||||
|
||||
Either<BaseError, PagedLibraryBrowseItemsResponseModel> result =
|
||||
await handler.Handle(new GetCollectionItems(1, 0, 100), CancellationToken.None);
|
||||
|
||||
PagedLibraryBrowseItemsResponseModel page = result.Match(
|
||||
Left: _ => throw new AssertionException("Expected a Right result"),
|
||||
Right: value => value);
|
||||
|
||||
page.TotalCount.ShouldBe(1);
|
||||
page.Page.Count.ShouldBe(1);
|
||||
page.Page[0].Title.ShouldBe("Fake Movie");
|
||||
page.Page[0].MediaItemId.ShouldBe(10);
|
||||
page.Page[0].MediaType.ShouldBe(LibraryBrowseMediaType.Movie);
|
||||
page.Page[0].Artwork.ShouldBe("/artwork/posters/movie.jpg");
|
||||
}
|
||||
|
||||
private async Task SeedCollectionWithMovie(int collectionId, int movieId, string title, string poster)
|
||||
{
|
||||
await using TvContext context = Db.CreateContext();
|
||||
var library = new LocalLibrary
|
||||
{
|
||||
Id = collectionId,
|
||||
Name = "Local",
|
||||
MediaKind = LibraryMediaKind.Movies,
|
||||
Paths = []
|
||||
};
|
||||
var path = new LibraryPath
|
||||
{
|
||||
Id = collectionId,
|
||||
Path = "/media",
|
||||
Library = library,
|
||||
LibraryFolders = [],
|
||||
MediaItems = []
|
||||
};
|
||||
library.Paths.Add(path);
|
||||
|
||||
var collection = new Collection { Id = collectionId, Name = "Collection", MediaItems = [] };
|
||||
var movie = new Movie
|
||||
{
|
||||
Id = movieId,
|
||||
LibraryPath = path,
|
||||
Collections = [collection],
|
||||
CollectionItems = [],
|
||||
TraktListItems = [],
|
||||
MediaVersions = [new MediaVersion { Duration = TimeSpan.FromMinutes(42) }],
|
||||
MovieMetadata =
|
||||
[
|
||||
new MovieMetadata
|
||||
{
|
||||
Title = title,
|
||||
SortTitle = title,
|
||||
Artwork = [new Artwork { Path = poster, ArtworkKind = ArtworkKind.Poster }],
|
||||
Genres = [],
|
||||
Tags = [],
|
||||
Studios = [],
|
||||
Actors = [],
|
||||
Guids = [],
|
||||
Subtitles = [],
|
||||
Directors = [],
|
||||
Writers = []
|
||||
}
|
||||
]
|
||||
};
|
||||
collection.MediaItems.Add(movie);
|
||||
|
||||
context.LocalLibraries.Add(library);
|
||||
context.Collections.Add(collection);
|
||||
context.Movies.Add(movie);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private static AddItemsToCollection MakeAddItems(int collectionId, List<int>? movieIds = null) =>
|
||||
new(
|
||||
collectionId,
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
using ErsatzTV.Application.Troubleshooting;
|
||||
using ErsatzTV.Application.Troubleshooting.Queries;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
using ErsatzTV.Core.Errors;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using ErsatzTV.Tests.Support;
|
||||
using LanguageExt;
|
||||
using NUnit.Framework;
|
||||
using Shouldly;
|
||||
|
||||
namespace ErsatzTV.Tests.Application.Troubleshooting;
|
||||
|
||||
[TestFixture]
|
||||
public class GetPlayoutHistoryDetailsHandlerTests
|
||||
{
|
||||
private InMemoryTvContext _db = null!;
|
||||
|
||||
[SetUp]
|
||||
public async Task SetUp() => _db = await InMemoryTvContext.CreateAsync();
|
||||
|
||||
[TearDown]
|
||||
public async Task TearDown() => await _db.DisposeAsync();
|
||||
|
||||
[Test]
|
||||
public async Task Should_Return_NotFoundError_When_Row_Missing()
|
||||
{
|
||||
var handler = new GetPlayoutHistoryDetailsHandler(_db.Factory);
|
||||
|
||||
Either<BaseError, PlayoutHistoryDetailsViewModel> result =
|
||||
await handler.Handle(new GetPlayoutHistoryDetails(999), CancellationToken.None);
|
||||
|
||||
result.IsLeft.ShouldBeTrue();
|
||||
LeftOf(result).ShouldBeOfType<NotFoundError>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Decode_Collection_Key_When_Row_Exists()
|
||||
{
|
||||
int historyId = await SeedHistory(
|
||||
"""{"CollectionType":"Collection","CollectionId":1,"PlaybackOrder":"Shuffle"}""",
|
||||
"{}",
|
||||
seedCollection: true);
|
||||
|
||||
var handler = new GetPlayoutHistoryDetailsHandler(_db.Factory);
|
||||
|
||||
Either<BaseError, PlayoutHistoryDetailsViewModel> result =
|
||||
await handler.Handle(new GetPlayoutHistoryDetails(historyId), CancellationToken.None);
|
||||
|
||||
result.IsRight.ShouldBeTrue();
|
||||
PlayoutHistoryDetailsViewModel vm = RightOf(result);
|
||||
vm.PlaybackOrder.ShouldBe(PlaybackOrder.Shuffle);
|
||||
vm.CollectionType.ShouldBe(CollectionType.Collection);
|
||||
vm.Name.ShouldBe("Cartoons");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Return_Error_When_Key_Json_Is_Malformed()
|
||||
{
|
||||
int historyId = await SeedHistory("this is not json", "{}", seedCollection: false);
|
||||
|
||||
var handler = new GetPlayoutHistoryDetailsHandler(_db.Factory);
|
||||
|
||||
Either<BaseError, PlayoutHistoryDetailsViewModel> result =
|
||||
await handler.Handle(new GetPlayoutHistoryDetails(historyId), CancellationToken.None);
|
||||
|
||||
result.IsLeft.ShouldBeTrue();
|
||||
LeftOf(result).ShouldNotBeOfType<NotFoundError>();
|
||||
}
|
||||
|
||||
private async Task<int> SeedHistory(string key, string details, bool seedCollection)
|
||||
{
|
||||
await using TvContext context = _db.CreateContext();
|
||||
|
||||
if (seedCollection)
|
||||
{
|
||||
context.Collections.Add(new Collection { Id = 1, Name = "Cartoons" });
|
||||
}
|
||||
|
||||
var history = new PlayoutHistory
|
||||
{
|
||||
PlayoutId = 1,
|
||||
BlockId = 10,
|
||||
PlaybackOrder = PlaybackOrder.Shuffle,
|
||||
Index = 0,
|
||||
Key = key,
|
||||
ChildKey = string.Empty,
|
||||
IsCurrentChild = false,
|
||||
When = DateTime.UtcNow,
|
||||
Finish = DateTime.UtcNow.AddHours(1),
|
||||
Details = details
|
||||
};
|
||||
context.PlayoutHistory.Add(history);
|
||||
await context.SaveChangesAsync();
|
||||
return history.Id;
|
||||
}
|
||||
|
||||
private static BaseError LeftOf(Either<BaseError, PlayoutHistoryDetailsViewModel> either) =>
|
||||
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected Left"));
|
||||
|
||||
private static PlayoutHistoryDetailsViewModel RightOf(Either<BaseError, PlayoutHistoryDetailsViewModel> either) =>
|
||||
either.Match(Left: _ => throw new AssertionException("Expected Right"), Right: v => v);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using ErsatzTV.Application.Troubleshooting;
|
||||
using ErsatzTV.Application.Troubleshooting.Queries;
|
||||
using ErsatzTV.Core.Interfaces.Scheduling;
|
||||
using NSubstitute;
|
||||
using NUnit.Framework;
|
||||
using Shouldly;
|
||||
|
||||
namespace ErsatzTV.Tests.Application.Troubleshooting;
|
||||
|
||||
[TestFixture]
|
||||
public class ValidateSequentialScheduleHandlerTests
|
||||
{
|
||||
private ISequentialScheduleValidator _validator = null!;
|
||||
private ValidateSequentialScheduleHandler _handler = null!;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_validator = Substitute.For<ISequentialScheduleValidator>();
|
||||
_handler = new ValidateSequentialScheduleHandler(_validator);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Report_Valid_When_No_Messages()
|
||||
{
|
||||
_validator.ToJson(Arg.Any<string>()).Returns("{ }");
|
||||
_validator.GetValidationMessages(Arg.Any<string>(), Arg.Any<bool>())
|
||||
.Returns(Task.FromResult<IList<string>>([]));
|
||||
|
||||
ValidateSequentialScheduleViewModel result =
|
||||
await _handler.Handle(new ValidateSequentialSchedule("content: []", false), CancellationToken.None);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
result.Messages.ShouldBeEmpty();
|
||||
result.Json.ShouldBe("{ }");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Report_Invalid_With_Messages()
|
||||
{
|
||||
_validator.ToJson(Arg.Any<string>()).Returns("{ }");
|
||||
_validator.GetValidationMessages(Arg.Any<string>(), Arg.Any<bool>())
|
||||
.Returns(Task.FromResult<IList<string>>(["content is required"]));
|
||||
|
||||
ValidateSequentialScheduleViewModel result =
|
||||
await _handler.Handle(new ValidateSequentialSchedule("nope: true", true), CancellationToken.None);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.Messages.ShouldBe(["content is required"]);
|
||||
result.Json.ShouldBe("{ }");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Capture_Exception_Message_When_Conversion_Throws()
|
||||
{
|
||||
_validator.ToJson(Arg.Any<string>()).Returns(_ => throw new InvalidOperationException("bad yaml"));
|
||||
|
||||
ValidateSequentialScheduleViewModel result =
|
||||
await _handler.Handle(new ValidateSequentialSchedule(": : :", false), CancellationToken.None);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.Messages.ShouldBe(["bad yaml"]);
|
||||
result.Json.ShouldBeEmpty();
|
||||
}
|
||||
}
|
||||
@@ -23,22 +23,26 @@ public class ApiControllerSecurityTests
|
||||
[Test]
|
||||
public void Every_Mutating_Api_Action_Should_Be_Globally_Protected_Or_Explicitly_Exempt()
|
||||
{
|
||||
Type[] apiControllers =
|
||||
[
|
||||
typeof(ChannelController),
|
||||
typeof(CollectionController),
|
||||
typeof(FFmpegProfileController),
|
||||
typeof(LibrariesController),
|
||||
typeof(MaintenanceController),
|
||||
typeof(PlayoutController),
|
||||
typeof(ResolutionController),
|
||||
typeof(ScannerController),
|
||||
typeof(ScheduleController),
|
||||
typeof(ScriptedScheduleController),
|
||||
typeof(SessionController),
|
||||
typeof(SettingsController),
|
||||
typeof(SmartCollectionController)
|
||||
];
|
||||
// Scan the assembly instead of hand-maintaining a list of controllers here: a
|
||||
// hardcoded array silently drifts as new controllers are added (9 were missing at
|
||||
// one point, including two with real mutating actions - ArtworkUploadController POST
|
||||
// and ChannelTemplateController POST/PUT/DELETE - that were never actually checked).
|
||||
// Note: not every controller in this namespace derives from ControllerBase (e.g.
|
||||
// ChannelController, ScannerController, SessionController, MaintenanceController,
|
||||
// TroubleshootController) - filter on [ApiController] + concrete class only, matching
|
||||
// the pattern already used by ScannerController_Should_Be_Only_Api_Key_Exempt_Api_Controller
|
||||
// below, so those controllers stay covered rather than silently dropping out of the scan.
|
||||
Type[] apiControllers = typeof(CollectionController)
|
||||
.Assembly
|
||||
.GetTypes()
|
||||
.Where(t => t.Namespace == typeof(CollectionController).Namespace)
|
||||
.Where(t => t is { IsClass: true, IsAbstract: false })
|
||||
.Where(t => t.GetCustomAttributes<ApiControllerAttribute>(inherit: true).Any())
|
||||
.ToArray();
|
||||
|
||||
// Guard against the scan silently matching nothing (e.g. a namespace rename) and
|
||||
// giving this test a false pass.
|
||||
apiControllers.Length.ShouldBeGreaterThanOrEqualTo(20);
|
||||
|
||||
foreach (Type controllerType in apiControllers)
|
||||
{
|
||||
|
||||
@@ -68,11 +68,67 @@ public class ApiErrorResponseMetadataTests
|
||||
[TestCase(typeof(ScheduleController), nameof(ScheduleController.ReplaceItems), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(ScheduleController), nameof(ScheduleController.DeleteItem), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(ScheduleController), nameof(ScheduleController.DeleteItem), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.CreateGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.CreateGroup), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.DeleteGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.GetItems), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Replace), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Preview), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Copy), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Copy), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.CreateGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.CreateGroup), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.DeleteGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.GetItems), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Replace), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Copy), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Copy), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.CreateGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.CreateGroup), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.DeleteGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Replace), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoController), nameof(DecoController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.CreateGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.CreateGroup), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.DeleteGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.GetItems), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.Replace), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(DecoTemplateController), nameof(DecoTemplateController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.UpdateDefaultDeco), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.UpdateDefaultDeco), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Update), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Update), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Delete), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.GetAlternateSchedules), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.GetAlternateSchedules), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.ReplaceAlternateSchedules), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.ReplaceAlternateSchedules), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.GetTemplates), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.GetTemplates), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.ReplaceTemplates), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.ReplaceTemplates), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.AddOne), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(FFmpegProfileController), nameof(FFmpegProfileController.AddOne), StatusCodes.Status401Unauthorized)]
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
using System.Reflection;
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Controllers.Api;
|
||||
using ErsatzTV.Controllers.Api.Requests;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.Scheduling;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
using LanguageExt;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Routing;
|
||||
using NSubstitute;
|
||||
using NUnit.Framework;
|
||||
using Shouldly;
|
||||
using static LanguageExt.Prelude;
|
||||
using Unit = LanguageExt.Unit;
|
||||
|
||||
namespace ErsatzTV.Tests.Controllers;
|
||||
|
||||
[TestFixture]
|
||||
public class BlockControllerTests
|
||||
{
|
||||
private BlockController _controller = null!;
|
||||
private IMediator _mediator = null!;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_mediator = Substitute.For<IMediator>();
|
||||
_controller = new BlockController(_mediator);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
|
||||
{
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetGroups), "GET", "/api/blocks/groups");
|
||||
ShouldHaveActionRoute(nameof(BlockController.CreateGroup), "POST", "/api/blocks/groups");
|
||||
ShouldHaveActionRoute(nameof(BlockController.DeleteGroup), "DELETE", "/api/blocks/groups/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetAll), "GET", "/api/blocks");
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetById), "GET", "/api/blocks/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Create), "POST", "/api/blocks");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Delete), "DELETE", "/api/blocks/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetItems), "GET", "/api/blocks/{id:int}/items");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Replace), "PUT", "/api/blocks/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Preview), "POST", "/api/blocks/{id:int}/preview");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Copy), "POST", "/api/blocks/{id:int}/copy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_201_With_Location_And_Body()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlockGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, BlockGroupViewModel>(new BlockGroupViewModel(5, "Prime Time")));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateBlockGroupRequest("Prime Time"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/blocks/groups/5");
|
||||
created.Value.ShouldBeOfType<BlockGroupResponseModel>().Name.ShouldBe("Prime Time");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateBlockGroup>(c => c.Name == "Prime Time"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlockGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, BlockGroupViewModel>(BaseError.New("bad")));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateBlockGroupRequest(string.Empty),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_204_When_Exists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllBlockGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockGroupViewModel> { new(3, "Prime Time") });
|
||||
_mediator.Send(Arg.Any<DeleteBlockGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BaseError>.None);
|
||||
|
||||
IActionResult result = await _controller.DeleteGroup(3, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NoContentResult>();
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<DeleteBlockGroup>(c => c.BlockGroupId == 3),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllBlockGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockGroupViewModel>());
|
||||
|
||||
IActionResult result = await _controller.DeleteGroup(99, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteBlockGroup>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAll_Should_Map_ViewModels_To_Response_Models()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllBlocks>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockViewModel> { MakeBlock(1, 2, "Morning") });
|
||||
|
||||
List<BlockResponseModel> result = await _controller.GetAll(CancellationToken.None);
|
||||
|
||||
result.Count.ShouldBe(1);
|
||||
result[0].Id.ShouldBe(1);
|
||||
result[0].GroupId.ShouldBe(2);
|
||||
result[0].Name.ShouldBe("Morning");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_201_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, BlockViewModel>(MakeBlock(8, 2, "Morning")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateBlockRequest(2, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/blocks/8");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateBlock>(c => c.BlockGroupId == 2 && c.Name == "Morning"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, BlockViewModel>(BaseError.New("dupe")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateBlockRequest(2, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_200_For_Some()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
|
||||
IActionResult result = await _controller.GetById(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<BlockResponseModel>().Id.ShouldBe(4);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_404_For_None()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.GetById(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_Should_Return_204_When_Exists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<DeleteBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BaseError>.None);
|
||||
|
||||
IActionResult result = await _controller.Delete(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Delete(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteBlock>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_200_Ordered_By_Index()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<GetBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockItemViewModel> { MakeItem(20, 1), MakeItem(10, 0) });
|
||||
|
||||
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
|
||||
|
||||
var items = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<List<BlockItemResponseModel>>();
|
||||
items.Count.ShouldBe(2);
|
||||
items[0].Index.ShouldBe(0);
|
||||
items[1].Index.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_404_When_Block_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_200_With_Refreshed_Block_And_Assign_Index_And_GroupId()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<ReplaceBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, Unit>(Unit.Default));
|
||||
_mediator.Send(Arg.Any<GetBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockItemViewModel> { MakeItem(10, 0), MakeItem(11, 1) });
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceBlockRequest(
|
||||
"Morning",
|
||||
60,
|
||||
BlockStopScheduling.BeforeDurationEnd,
|
||||
[MakeItemRequest(), MakeItemRequest()]),
|
||||
CancellationToken.None);
|
||||
|
||||
var body = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<BlockWithItemsResponseModel>();
|
||||
body.Id.ShouldBe(4);
|
||||
body.Items.Count.ShouldBe(2);
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<ReplaceBlockItems>(c =>
|
||||
c.BlockId == 4 &&
|
||||
c.BlockGroupId == 7 &&
|
||||
c.Minutes == 60 &&
|
||||
c.StopScheduling == BlockStopScheduling.BeforeDurationEnd &&
|
||||
c.Items.Count == 2 &&
|
||||
c.Items[0].Index == 0 &&
|
||||
c.Items[1].Index == 1),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_404_When_Block_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<ReplaceBlockItems>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<ReplaceBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, Unit>(BaseError.New("bad minutes")));
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 7, BlockStopScheduling.AfterDurationEnd, []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Preview_Should_Return_200_With_Preview_Items()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<PreviewBlockPlayout>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PlayoutItemPreviewViewModel>
|
||||
{
|
||||
new("Show", TimeSpan.Zero, TimeSpan.FromMinutes(30), "00:30:00")
|
||||
});
|
||||
|
||||
IActionResult result = await _controller.Preview(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, [MakeItemRequest()]),
|
||||
CancellationToken.None);
|
||||
|
||||
var items = result.ShouldBeOfType<OkObjectResult>().Value
|
||||
.ShouldBeOfType<List<BlockPreviewItemResponseModel>>();
|
||||
items.Count.ShouldBe(1);
|
||||
items[0].Title.ShouldBe("Show");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<PreviewBlockPlayout>(p => p.Data.BlockId == 4 && p.Data.BlockGroupId == 7),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Preview_Should_Return_404_When_Block_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Preview(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<PreviewBlockPlayout>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_201_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<CopyBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, BlockViewModel>(MakeBlock(9, 3, "Morning Copy")));
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyBlockRequest(3, "Morning Copy"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/blocks/9");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CopyBlock>(c => c.BlockId == 4 && c.NewBlockGroupId == 3 && c.NewBlockName == "Morning Copy"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_404_When_Source_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyBlockRequest(3, "Morning Copy"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<CopyBlock>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<CopyBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, BlockViewModel>(BaseError.New("dupe")));
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyBlockRequest(3, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
private static BlockViewModel MakeBlock(int id, int groupId, string name) =>
|
||||
new(id, groupId, "Group", name, 30, BlockStopScheduling.AfterDurationEnd);
|
||||
|
||||
private static BlockItemViewModel MakeItem(int id, int index) =>
|
||||
new(
|
||||
id,
|
||||
index,
|
||||
CollectionType.SearchQuery,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
"News",
|
||||
"news",
|
||||
PlaybackOrder.Shuffle,
|
||||
IncludeInProgramGuide: true,
|
||||
DisableWatermarks: false,
|
||||
[],
|
||||
[]);
|
||||
|
||||
private static BlockItemRequest MakeItemRequest() =>
|
||||
new(
|
||||
CollectionType.SearchQuery,
|
||||
CollectionId: null,
|
||||
MultiCollectionId: null,
|
||||
SmartCollectionId: null,
|
||||
MediaItemId: null,
|
||||
SearchTitle: "News",
|
||||
SearchQuery: "news",
|
||||
PlaybackOrder: PlaybackOrder.Shuffle,
|
||||
IncludeInProgramGuide: true,
|
||||
DisableWatermarks: false,
|
||||
WatermarkIds: [],
|
||||
GraphicsElementIds: []);
|
||||
|
||||
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
|
||||
{
|
||||
MethodInfo action = typeof(BlockController).GetMethod(actionName)
|
||||
?? throw new AssertionException($"Missing action {actionName}");
|
||||
|
||||
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
|
||||
attribute.HttpMethods.ShouldContain(httpMethod);
|
||||
attribute.Template.ShouldBe(route);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user