diff --git a/.gitea/workflows/docker-build.yml b/.gitea/workflows/docker-build.yml index 55157fe10..7d5fac7f3 100644 --- a/.gitea/workflows/docker-build.yml +++ b/.gitea/workflows/docker-build.yml @@ -50,6 +50,37 @@ jobs: - name: Restore run: dotnet restore + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '22.x' + cache: npm + cache-dependency-path: web/package-lock.json + + - name: Install SPA dependencies + working-directory: web + run: npm ci + + - name: Check generated SPA API client + working-directory: web + run: npm run check:api + + - name: Lint SPA + working-directory: web + run: npm run lint + + - name: Typecheck SPA + working-directory: web + run: npm run typecheck + + - name: Test SPA + working-directory: web + run: npm test -- --run + + - name: Build SPA + working-directory: web + run: npm run build + - name: Strip Scanner project ref (matches Docker build) run: sed -i '/Scanner/d' ErsatzTV/ErsatzTV.csproj diff --git a/.gitignore b/.gitignore index f276affa0..a886d4eeb 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ project.lock.json .DS_Store *.pyc +.worktrees/ # Claude Code .mcp/ @@ -51,3 +52,6 @@ scripts/download-test-content.sh docker-compose.override.yml ErsatzTV/wwwroot/v2/ +ErsatzTV/wwwroot/app/ +web/dist/ +web/node_modules/ diff --git a/ErsatzTV.Application/Channels/Commands/BulkDeleteChannels.cs b/ErsatzTV.Application/Channels/Commands/BulkDeleteChannels.cs new file mode 100644 index 000000000..edc962ebb --- /dev/null +++ b/ErsatzTV.Application/Channels/Commands/BulkDeleteChannels.cs @@ -0,0 +1,5 @@ +using ErsatzTV.Core; + +namespace ErsatzTV.Application.Channels; + +public record BulkDeleteChannels(IReadOnlyList ChannelIds) : IRequest>; diff --git a/ErsatzTV.Application/Channels/Commands/BulkDeleteChannelsHandler.cs b/ErsatzTV.Application/Channels/Commands/BulkDeleteChannelsHandler.cs new file mode 100644 index 000000000..58dff8705 --- /dev/null +++ b/ErsatzTV.Application/Channels/Commands/BulkDeleteChannelsHandler.cs @@ -0,0 +1,62 @@ +using System.IO.Abstractions; +using System.Threading.Channels; +using ErsatzTV.Core; +using ErsatzTV.Core.Errors; +using ErsatzTV.Core.Interfaces.Search; +using ErsatzTV.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Channel = ErsatzTV.Core.Domain.Channel; + +namespace ErsatzTV.Application.Channels; + +public class BulkDeleteChannelsHandler( + IDbContextFactory dbContextFactory, + ChannelWriter workerChannel, + IFileSystem fileSystem, + ISearchTargets searchTargets) + : IRequestHandler> +{ + public async Task> Handle( + BulkDeleteChannels request, + CancellationToken cancellationToken) + { + if (request.ChannelIds.Count == 0) + { + return Left(BaseError.New("At least one channel id is required")); + } + + await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); + await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); + + List channelIds = request.ChannelIds.Distinct().ToList(); + List channels = await dbContext.Channels + .Where(c => channelIds.Contains(c.Id)) + .ToListAsync(cancellationToken); + + if (channels.Count != channelIds.Count) + { + var found = channels.Select(c => c.Id).ToHashSet(); + int missingId = channelIds.First(id => !found.Contains(id)); + return Left(new NotFoundError($"Channel {missingId} does not exist.")); + } + + dbContext.Channels.RemoveRange(channels); + await dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + + searchTargets.SearchTargetsChanged(); + + foreach (Channel channel in channels) + { + string cacheFile = Path.Combine(FileSystemLayout.ChannelGuideCacheFolder, $"{channel.Number}.xml"); + if (fileSystem.File.Exists(cacheFile)) + { + fileSystem.File.Delete(cacheFile); + } + } + + await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken); + + return Right(Unit.Default); + } +} diff --git a/ErsatzTV.Application/Channels/Commands/BulkMoveChannelsToGroup.cs b/ErsatzTV.Application/Channels/Commands/BulkMoveChannelsToGroup.cs new file mode 100644 index 000000000..05fb8313e --- /dev/null +++ b/ErsatzTV.Application/Channels/Commands/BulkMoveChannelsToGroup.cs @@ -0,0 +1,6 @@ +using ErsatzTV.Core; + +namespace ErsatzTV.Application.Channels; + +public record BulkMoveChannelsToGroup(IReadOnlyList ChannelIds, string Group) + : IRequest>; diff --git a/ErsatzTV.Application/Channels/Commands/BulkMoveChannelsToGroupHandler.cs b/ErsatzTV.Application/Channels/Commands/BulkMoveChannelsToGroupHandler.cs new file mode 100644 index 000000000..ede6c4506 --- /dev/null +++ b/ErsatzTV.Application/Channels/Commands/BulkMoveChannelsToGroupHandler.cs @@ -0,0 +1,61 @@ +using System.Threading.Channels; +using ErsatzTV.Core; +using ErsatzTV.Core.Errors; +using ErsatzTV.Core.Interfaces.Search; +using ErsatzTV.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using static ErsatzTV.Application.Channels.ChannelValidations; +using Channel = ErsatzTV.Core.Domain.Channel; + +namespace ErsatzTV.Application.Channels; + +public class BulkMoveChannelsToGroupHandler( + IDbContextFactory dbContextFactory, + ChannelWriter workerChannel, + ISearchTargets searchTargets) + : IRequestHandler> +{ + public async Task> Handle( + BulkMoveChannelsToGroup request, + CancellationToken cancellationToken) + { + if (request.ChannelIds.Count == 0) + { + return Left(BaseError.New("At least one channel id is required")); + } + + Validation groupValidation = ValidateGroup(request.Group); + if (groupValidation.IsFail) + { + return Left(groupValidation.FailToSeq().Head()); + } + + await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); + await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); + + List channelIds = request.ChannelIds.Distinct().ToList(); + List channels = await dbContext.Channels + .Where(c => channelIds.Contains(c.Id)) + .ToListAsync(cancellationToken); + + if (channels.Count != channelIds.Count) + { + var found = channels.Select(c => c.Id).ToHashSet(); + int missingId = channelIds.First(id => !found.Contains(id)); + return Left(new NotFoundError($"Channel {missingId} does not exist.")); + } + + foreach (Channel channel in channels) + { + channel.Group = request.Group; + } + + await dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + + searchTargets.SearchTargetsChanged(); + await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken); + + return Right(Unit.Default); + } +} diff --git a/ErsatzTV.Application/Channels/Commands/UpdateChannelNumbersHandler.cs b/ErsatzTV.Application/Channels/Commands/UpdateChannelNumbersHandler.cs index c28cc3a59..c1873c15f 100644 --- a/ErsatzTV.Application/Channels/Commands/UpdateChannelNumbersHandler.cs +++ b/ErsatzTV.Application/Channels/Commands/UpdateChannelNumbersHandler.cs @@ -1,6 +1,8 @@ using System.Globalization; +using System.Text.RegularExpressions; using System.Threading.Channels; using ErsatzTV.Core; +using ErsatzTV.Core.Errors; using ErsatzTV.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Channel = ErsatzTV.Core.Domain.Channel; @@ -14,18 +16,41 @@ public class UpdateChannelNumbersHandler( { public async Task> Handle(UpdateChannelNumbers request, CancellationToken cancellationToken) { + Option validationError = ValidateRequest(request); + if (validationError.IsSome) + { + return validationError; + } + await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); try { var numberUpdates = request.Channels.ToDictionary(c => c.Id, c => c.Number); - var channelIds = numberUpdates.Keys; + List channelIds = numberUpdates.Keys.ToList(); List channelsToUpdate = await dbContext.Channels .Where(c => channelIds.Contains(c.Id)) .ToListAsync(cancellationToken); + if (channelsToUpdate.Count != channelIds.Count) + { + var found = channelsToUpdate.Select(c => c.Id).ToHashSet(); + int missingId = channelIds.First(id => !found.Contains(id)); + return new NotFoundError($"Channel {missingId} does not exist."); + } + + List requestedNumbers = numberUpdates.Values.ToList(); + bool numberConflict = await dbContext.Channels + .AnyAsync( + c => requestedNumbers.Contains(c.Number) && !channelIds.Contains(c.Id), + cancellationToken); + if (numberConflict) + { + return BaseError.New("Channel number must be unique"); + } + // give every channel a non-conflicting number foreach (var channel in channelsToUpdate) { @@ -69,4 +94,32 @@ public class UpdateChannelNumbersHandler( return BaseError.New("Failed to update channel numbers: " + ex.Message); } } + + private static Option ValidateRequest(UpdateChannelNumbers request) + { + if (request.Channels.Count == 0) + { + return BaseError.New("At least one channel is required"); + } + + if (request.Channels.Select(c => c.Id).Distinct().Count() != request.Channels.Count) + { + return BaseError.New("Channel ids must be unique"); + } + + if (request.Channels.Select(c => c.Number).Distinct(StringComparer.Ordinal).Count() != request.Channels.Count) + { + return BaseError.New("Channel number must be unique"); + } + + foreach (ChannelSortViewModel channel in request.Channels) + { + if (!Regex.IsMatch(channel.Number, Channel.NumberValidator)) + { + return BaseError.New("Invalid channel number; two decimals are allowed for subchannels"); + } + } + + return Option.None; + } } diff --git a/ErsatzTV.Application/Channels/Mapper.cs b/ErsatzTV.Application/Channels/Mapper.cs index 42e3878b9..bbe5a8c78 100644 --- a/ErsatzTV.Application/Channels/Mapper.cs +++ b/ErsatzTV.Application/Channels/Mapper.cs @@ -42,10 +42,15 @@ internal static class Mapper new( channel.Id, channel.Number, + channel.SortNumber, channel.Name, + channel.Group, + channel.Categories, channel.FFmpegProfile.Name, channel.PreferredAudioLanguageCode, - GetStreamingMode(channel)); + GetStreamingMode(channel), + channel.IsEnabled, + channel.ShowInEpg); internal static ResolutionViewModel ProjectToViewModel(Resolution resolution) => new(resolution.Height, resolution.Width); diff --git a/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApi.cs b/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApi.cs new file mode 100644 index 000000000..077ef9201 --- /dev/null +++ b/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApi.cs @@ -0,0 +1,5 @@ +using ErsatzTV.Core.Api.Channels; + +namespace ErsatzTV.Application.Channels; + +public record GetChannelStatesForApi(DateTime Now) : IRequest>; diff --git a/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApiHandler.cs b/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApiHandler.cs new file mode 100644 index 000000000..0aafff89b --- /dev/null +++ b/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApiHandler.cs @@ -0,0 +1,151 @@ +using ErsatzTV.Core.Api.Channels; +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Domain.Filler; +using ErsatzTV.Core.Interfaces.FFmpeg; +using ErsatzTV.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using PlayoutMapper = ErsatzTV.Application.Playouts.Mapper; + +namespace ErsatzTV.Application.Channels; + +public class GetChannelStatesForApiHandler( + IDbContextFactory dbContextFactory, + IFFmpegSegmenterService ffmpegSegmenterService) + : IRequestHandler> +{ + // a guide entry (program + surrounding filler) never spans anywhere near a day; the time + // bound also protects against GuideGroup values recycling (mod 10000) elsewhere in a playout + private static readonly TimeSpan GuideEntryBound = TimeSpan.FromDays(1); + + public async Task> Handle( + GetChannelStatesForApi request, + CancellationToken cancellationToken) + { + await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); + + List channels = await dbContext.Channels + .AsNoTracking() + .OrderBy(c => c.SortNumber) + .ThenBy(c => c.Number) + .ToListAsync(cancellationToken); + + if (channels.Count == 0) + { + return []; + } + + Dictionary channelLookup = channels + .ToDictionary( + c => c.Id, + c => + { + TimeSpan offset = c.PlayoutOffset ?? TimeSpan.Zero; + return (c.MirrorSourceChannelId ?? c.Id, offset, request.Now - offset); + }); + + // one covering-item query per distinct lookup time (i.e. per distinct playout offset, + // typically just one) with a cheap projection; metadata is hydrated in a second query + // for only the covering items' guide groups + var coveringBySourceAndTime = new Dictionary<(int SourceChannelId, DateTime LookupTime), CoveringItem>(); + foreach (IGrouping timeGroup in + channelLookup.Values.GroupBy(v => v.LookupTime)) + { + DateTime lookupTime = timeGroup.Key; + int[] sourceChannelIds = timeGroup.Map(v => v.SourceChannelId).Distinct().ToArray(); + + List covering = await dbContext.PlayoutItems + .AsNoTracking() + .Where(pi => sourceChannelIds.Contains(pi.Playout.ChannelId)) + .Where(pi => pi.Start <= lookupTime && pi.Finish > lookupTime) + .Select(pi => new CoveringItem(pi.Id, pi.PlayoutId, pi.Playout.ChannelId, pi.GuideGroup, pi.Start)) + .ToListAsync(cancellationToken); + + foreach (CoveringItem item in covering.OrderBy(ci => ci.Start)) + { + coveringBySourceAndTime.TryAdd((item.ChannelId, lookupTime), item); + } + } + + Dictionary<(int PlayoutId, int GuideGroup), List> itemsByGuideEntry = []; + if (coveringBySourceAndTime.Count > 0) + { + int[] playoutIds = coveringBySourceAndTime.Values.Map(ci => ci.PlayoutId).Distinct().ToArray(); + int[] guideGroups = coveringBySourceAndTime.Values.Map(ci => ci.GuideGroup).Distinct().ToArray(); + DateTime windowStart = channelLookup.Values.Min(v => v.LookupTime) - GuideEntryBound; + DateTime windowFinish = channelLookup.Values.Max(v => v.LookupTime) + GuideEntryBound; + + List guideEntryItems = await dbContext.PlayoutItems + .AsNoTracking() + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as Episode).EpisodeMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as Episode).Season) + .ThenInclude(s => s.Show) + .ThenInclude(s => s.ShowMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as Movie).MovieMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as MusicVideo).MusicVideoMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as MusicVideo).Artist) + .ThenInclude(a => a.ArtistMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as OtherVideo).OtherVideoMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as Song).SongMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as Image).ImageMetadata) + .Include(pi => pi.MediaItem) + .ThenInclude(mi => (mi as RemoteStream).RemoteStreamMetadata) + .Where(pi => playoutIds.Contains(pi.PlayoutId) && guideGroups.Contains(pi.GuideGroup)) + .Where(pi => pi.Start <= windowFinish && pi.Finish > windowStart) + .ToListAsync(cancellationToken); + + itemsByGuideEntry = guideEntryItems + .GroupBy(pi => (pi.PlayoutId, pi.GuideGroup)) + .ToDictionary(g => g.Key, g => g.OrderBy(pi => pi.Start).ToList()); + } + + return channels + .Map(channel => + { + (int sourceChannelId, TimeSpan offset, DateTime lookupTime) = channelLookup[channel.Id]; + ChannelNowPlayingResponseModel nowPlaying = null; + + if (coveringBySourceAndTime.TryGetValue((sourceChannelId, lookupTime), out CoveringItem covering) && + itemsByGuideEntry.TryGetValue( + (covering.PlayoutId, covering.GuideGroup), + out List guideEntry)) + { + // like the XMLTV guide, surface the program rather than its filler: use the + // covering item itself when it is a program part, otherwise the guide entry's + // first program item; an entry with no program item (e.g. offline fallback + // filler) stays null + PlayoutItem coveringItem = guideEntry.Find(pi => pi.Id == covering.Id); + PlayoutItem displayItem = coveringItem?.FillerKind == FillerKind.None + ? coveringItem + : guideEntry.Find(pi => pi.FillerKind == FillerKind.None); + + if (displayItem is not null) + { + DateTime start = guideEntry[0].Start; + DateTime finish = displayItem.GuideFinish ?? guideEntry.Max(pi => pi.Finish); + + nowPlaying = new ChannelNowPlayingResponseModel( + PlayoutMapper.GetDisplayTitle(displayItem.MediaItem, Optional(displayItem.ChapterTitle)), + new DateTimeOffset(start + offset, TimeSpan.Zero), + new DateTimeOffset(finish + offset, TimeSpan.Zero)); + } + } + + return new ChannelStateResponseModel( + channel.Id, + channel.Number, + ffmpegSegmenterService.IsActive(channel.Number), + nowPlaying); + }) + .ToList(); + } + + private sealed record CoveringItem(int Id, int PlayoutId, int ChannelId, int GuideGroup, DateTime Start); +} diff --git a/ErsatzTV.Core/Api/Channels/ChannelNowPlayingResponseModel.cs b/ErsatzTV.Core/Api/Channels/ChannelNowPlayingResponseModel.cs new file mode 100644 index 000000000..3c5205395 --- /dev/null +++ b/ErsatzTV.Core/Api/Channels/ChannelNowPlayingResponseModel.cs @@ -0,0 +1,8 @@ +namespace ErsatzTV.Core.Api.Channels; + +#nullable enable + +public record ChannelNowPlayingResponseModel( + string Title, + DateTimeOffset StartUtc, + DateTimeOffset FinishUtc); diff --git a/ErsatzTV.Core/Api/Channels/ChannelResponseModel.cs b/ErsatzTV.Core/Api/Channels/ChannelResponseModel.cs index 121deec5c..55ceab9d8 100644 --- a/ErsatzTV.Core/Api/Channels/ChannelResponseModel.cs +++ b/ErsatzTV.Core/Api/Channels/ChannelResponseModel.cs @@ -1,12 +1,18 @@ -using Newtonsoft.Json; +#nullable enable +using Newtonsoft.Json; namespace ErsatzTV.Core.Api.Channels; public record ChannelResponseModel( int Id, string Number, + double SortNumber, string Name, + string Group, + string Categories, [property: JsonProperty("ffmpegProfile")] string FFmpegProfile, string Language, - string StreamingMode); + string StreamingMode, + bool IsEnabled, + bool ShowInEpg); diff --git a/ErsatzTV.Core/Api/Channels/ChannelStateResponseModel.cs b/ErsatzTV.Core/Api/Channels/ChannelStateResponseModel.cs new file mode 100644 index 000000000..44c306078 --- /dev/null +++ b/ErsatzTV.Core/Api/Channels/ChannelStateResponseModel.cs @@ -0,0 +1,9 @@ +namespace ErsatzTV.Core.Api.Channels; + +#nullable enable + +public record ChannelStateResponseModel( + int ChannelId, + string ChannelNumber, + bool OnAir, + ChannelNowPlayingResponseModel? NowPlaying); diff --git a/ErsatzTV.Tests/Application/Channels/BulkDeleteChannelsHandlerTests.cs b/ErsatzTV.Tests/Application/Channels/BulkDeleteChannelsHandlerTests.cs new file mode 100644 index 000000000..dcb3dac56 --- /dev/null +++ b/ErsatzTV.Tests/Application/Channels/BulkDeleteChannelsHandlerTests.cs @@ -0,0 +1,57 @@ +using ErsatzTV.Application.Channels; +using ErsatzTV.Core; +using ErsatzTV.Core.Errors; +using ErsatzTV.Infrastructure.Data; +using ErsatzTV.Tests.Support; +using LanguageExt; +using Microsoft.EntityFrameworkCore; +using NSubstitute; +using NUnit.Framework; +using Shouldly; +using Testably.Abstractions.Testing; + +namespace ErsatzTV.Tests.Application.Channels; + +[TestFixture] +public class BulkDeleteChannelsHandlerTests : ChannelHandlerTestBase +{ + private readonly MockFileSystem _fileSystem = new(); + + private BulkDeleteChannelsHandler MakeHandler() => new(Db.Factory, Worker, _fileSystem, SearchTargets); + + [Test] + public async Task Should_Delete_All_Channels() + { + await SeedChannel(1, "5"); + await SeedChannel(2, "6"); + + Either result = + await MakeHandler().Handle(new BulkDeleteChannels([1, 2]), CancellationToken.None); + + result.IsRight.ShouldBeTrue(); + + await using TvContext context = Db.CreateContext(); + int count = await context.Channels.CountAsync(); + count.ShouldBe(0); + SearchTargets.Received(1).SearchTargetsChanged(); + } + + [Test] + public async Task Should_Return_NotFound_And_Not_Delete_When_Any_Channel_Is_Missing() + { + await SeedChannel(1, "5"); + + Either result = + await MakeHandler().Handle(new BulkDeleteChannels([1, 99]), CancellationToken.None); + + BaseError error = LeftOf(result); + error.ShouldBeOfType(); + + await using TvContext context = Db.CreateContext(); + bool exists = await context.Channels.AnyAsync(c => c.Id == 1); + exists.ShouldBeTrue(); + } + + private static BaseError LeftOf(Either either) => + either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result")); +} diff --git a/ErsatzTV.Tests/Application/Channels/BulkMoveChannelsToGroupHandlerTests.cs b/ErsatzTV.Tests/Application/Channels/BulkMoveChannelsToGroupHandlerTests.cs new file mode 100644 index 000000000..e9323e40a --- /dev/null +++ b/ErsatzTV.Tests/Application/Channels/BulkMoveChannelsToGroupHandlerTests.cs @@ -0,0 +1,74 @@ +using ErsatzTV.Application.Channels; +using ErsatzTV.Core; +using ErsatzTV.Core.Errors; +using ErsatzTV.Infrastructure.Data; +using ErsatzTV.Tests.Support; +using LanguageExt; +using Microsoft.EntityFrameworkCore; +using NSubstitute; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Tests.Application.Channels; + +[TestFixture] +public class BulkMoveChannelsToGroupHandlerTests : ChannelHandlerTestBase +{ + private BulkMoveChannelsToGroupHandler MakeHandler() => new(Db.Factory, Worker, SearchTargets); + + [Test] + public async Task Should_Move_All_Channels_To_Group() + { + await SeedChannel(1, "5"); + await SeedChannel(2, "6"); + + Either result = + await MakeHandler().Handle(new BulkMoveChannelsToGroup([1, 2], "Movies"), CancellationToken.None); + + result.IsRight.ShouldBeTrue(); + + await using TvContext context = Db.CreateContext(); + List groups = await context.Channels + .OrderBy(c => c.Id) + .Select(c => c.Group) + .ToListAsync(); + groups.ShouldBe(["Movies", "Movies"]); + SearchTargets.Received(1).SearchTargetsChanged(); + } + + [Test] + public async Task Should_Return_NotFound_And_Not_Move_When_Any_Channel_Is_Missing() + { + await SeedChannel(1, "5", group: "Original"); + + Either result = + await MakeHandler().Handle(new BulkMoveChannelsToGroup([1, 99], "Movies"), CancellationToken.None); + + BaseError error = LeftOf(result); + error.ShouldBeOfType(); + + await using TvContext context = Db.CreateContext(); + string group = await context.Channels.Where(c => c.Id == 1).Select(c => c.Group).SingleAsync(); + group.ShouldBe("Original"); + } + + [Test] + public async Task Should_Reject_Empty_Group() + { + await SeedChannel(1, "5", group: "Original"); + + Either result = + await MakeHandler().Handle(new BulkMoveChannelsToGroup([1], ""), CancellationToken.None); + + BaseError error = LeftOf(result); + error.ShouldNotBeOfType(); + error.Value.ShouldContain("group"); + + await using TvContext context = Db.CreateContext(); + string group = await context.Channels.Where(c => c.Id == 1).Select(c => c.Group).SingleAsync(); + group.ShouldBe("Original"); + } + + private static BaseError LeftOf(Either either) => + either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result")); +} diff --git a/ErsatzTV.Tests/Application/Channels/GetAllChannelsForApiHandlerTests.cs b/ErsatzTV.Tests/Application/Channels/GetAllChannelsForApiHandlerTests.cs new file mode 100644 index 000000000..c43f41c2b --- /dev/null +++ b/ErsatzTV.Tests/Application/Channels/GetAllChannelsForApiHandlerTests.cs @@ -0,0 +1,53 @@ +using ErsatzTV.Application.Channels; +using ErsatzTV.Core; +using ErsatzTV.Core.Api.Channels; +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Interfaces.Repositories; +using NSubstitute; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Tests.Application.Channels; + +[TestFixture] +public class GetAllChannelsForApiHandlerTests +{ + [Test] + public async Task Should_Project_Management_Table_Fields() + { + IChannelRepository repository = Substitute.For(); + repository.GetAll(Arg.Any()) + .Returns([ + new Channel(Guid.NewGuid()) + { + Id = 7, + Number = "7.1", + SortNumber = 7.1, + Name = "Retro Cartoons", + Group = "Kids", + Categories = "animation", + FFmpegProfile = new FFmpegProfile { Name = "HLS 720p" }, + PreferredAudioLanguageCode = "eng", + StreamingMode = StreamingMode.HttpLiveStreamingSegmenter, + IsEnabled = false, + ShowInEpg = false + } + ]); + var handler = new GetAllChannelsForApiHandler(repository); + + List result = await handler.Handle(new GetAllChannelsForApi(), CancellationToken.None); + + ChannelResponseModel channel = result.ShouldHaveSingleItem(); + channel.Id.ShouldBe(7); + channel.Number.ShouldBe("7.1"); + channel.SortNumber.ShouldBe(7.1); + channel.Name.ShouldBe("Retro Cartoons"); + channel.Group.ShouldBe("Kids"); + channel.Categories.ShouldBe("animation"); + channel.FFmpegProfile.ShouldBe("HLS 720p"); + channel.Language.ShouldBe("eng"); + channel.StreamingMode.ShouldBe("HLS Segmenter"); + channel.IsEnabled.ShouldBeFalse(); + channel.ShowInEpg.ShouldBeFalse(); + } +} diff --git a/ErsatzTV.Tests/Application/Channels/GetChannelStatesForApiHandlerTests.cs b/ErsatzTV.Tests/Application/Channels/GetChannelStatesForApiHandlerTests.cs new file mode 100644 index 000000000..0a237b30f --- /dev/null +++ b/ErsatzTV.Tests/Application/Channels/GetChannelStatesForApiHandlerTests.cs @@ -0,0 +1,329 @@ +using ErsatzTV.Application.Channels; +using ErsatzTV.Core.Api.Channels; +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Domain.Filler; +using ErsatzTV.Core.Interfaces.FFmpeg; +using ErsatzTV.Infrastructure.Data; +using ErsatzTV.Tests.Support; +using NSubstitute; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Tests.Application.Channels; + +[TestFixture] +public class GetChannelStatesForApiHandlerTests +{ + private static readonly DateTime Now = new(2026, 7, 2, 12, 0, 0, DateTimeKind.Utc); + + private InMemoryTvContext _db = null!; + private IFFmpegSegmenterService _segmenter = null!; + + [SetUp] + public async Task SetUp() + { + _db = await InMemoryTvContext.CreateAsync(); + _segmenter = Substitute.For(); + } + + [TearDown] + public async Task TearDown() => await _db.DisposeAsync(); + + [Test] + public async Task Handle_Should_Return_OnAir_And_Current_NowPlaying() + { + DateTime start = Now.AddMinutes(-10); + DateTime finish = Now.AddMinutes(20); + await SeedChannelWithMovie(start, finish); + _segmenter.IsActive("7.1").Returns(true); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + ChannelStateResponseModel state = result.ShouldHaveSingleItem(); + state.ChannelId.ShouldBe(7); + state.ChannelNumber.ShouldBe("7.1"); + state.OnAir.ShouldBeTrue(); + state.NowPlaying.ShouldNotBeNull(); + state.NowPlaying.Title.ShouldBe("Retro Cartoons"); + state.NowPlaying.StartUtc.ShouldBe(new DateTimeOffset(start, TimeSpan.Zero)); + state.NowPlaying.FinishUtc.ShouldBe(new DateTimeOffset(finish, TimeSpan.Zero)); + } + + [Test] + public async Task Handle_Should_Match_Item_When_Now_Equals_Start() + { + await SeedChannelWithMovie(Now, Now.AddMinutes(30)); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + result.ShouldHaveSingleItem().NowPlaying.ShouldNotBeNull(); + } + + [Test] + public async Task Handle_Should_Not_Match_Item_When_Now_Equals_Finish() + { + await SeedChannelWithMovie(Now.AddMinutes(-30), Now); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + result.ShouldHaveSingleItem().NowPlaying.ShouldBeNull(); + } + + [Test] + public async Task Handle_Should_Return_Null_NowPlaying_When_No_Current_Item() + { + await using TvContext context = _db.CreateContext(); + context.Channels.Add(MakeChannel(8, "8")); + await context.SaveChangesAsync(); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + ChannelStateResponseModel state = result.ShouldHaveSingleItem(); + state.OnAir.ShouldBeFalse(); + state.NowPlaying.ShouldBeNull(); + } + + [Test] + public async Task Handle_Should_Surface_Program_Not_Filler_During_MidRoll_Break() + { + // program part 1 / mid-roll filler / program part 2, all in one guide group + await using TvContext context = _db.CreateContext(); + Channel channel = MakeChannel(12, "12"); + var movie = new Movie + { + Id = 120, + MovieMetadata = [new MovieMetadata { Title = "Feature Presentation" }] + }; + var filler = new OtherVideo + { + Id = 121, + OtherVideoMetadata = [new OtherVideoMetadata { Title = "Some Bumper" }] + }; + var playout = new Playout { Id = 122, Channel = channel, ChannelId = channel.Id, Items = [] }; + PlayoutItem MakeItem(int id, MediaItem mediaItem, DateTime start, DateTime finish, FillerKind fillerKind) => + new() + { + Id = id, + MediaItem = mediaItem, + MediaItemId = mediaItem.Id, + Playout = playout, + PlayoutId = playout.Id, + Start = start, + Finish = finish, + FillerKind = fillerKind, + GuideGroup = 1, + ChapterTitle = string.Empty + }; + + context.Channels.Add(channel); + context.Movies.Add(movie); + context.OtherVideos.Add(filler); + context.Playouts.Add(playout); + context.PlayoutItems.AddRange( + MakeItem(123, movie, Now.AddMinutes(-20), Now.AddMinutes(-2), FillerKind.None), + MakeItem(124, filler, Now.AddMinutes(-2), Now.AddMinutes(2), FillerKind.MidRoll), + MakeItem(125, movie, Now.AddMinutes(2), Now.AddMinutes(40), FillerKind.None)); + await context.SaveChangesAsync(); + + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + ChannelStateResponseModel state = result.ShouldHaveSingleItem(); + state.NowPlaying.ShouldNotBeNull(); + state.NowPlaying.Title.ShouldBe("Feature Presentation"); + state.NowPlaying.StartUtc.ShouldBe(new DateTimeOffset(Now.AddMinutes(-20), TimeSpan.Zero)); + state.NowPlaying.FinishUtc.ShouldBe(new DateTimeOffset(Now.AddMinutes(40), TimeSpan.Zero)); + } + + [Test] + public async Task Handle_Should_Return_Null_NowPlaying_For_Guide_Entry_With_Only_Filler() + { + await using TvContext context = _db.CreateContext(); + Channel channel = MakeChannel(13, "13"); + var filler = new OtherVideo + { + Id = 130, + OtherVideoMetadata = [new OtherVideoMetadata { Title = "Offline Loop" }] + }; + var playout = new Playout { Id = 131, Channel = channel, ChannelId = channel.Id, Items = [] }; + var item = new PlayoutItem + { + Id = 132, + MediaItem = filler, + MediaItemId = filler.Id, + Playout = playout, + PlayoutId = playout.Id, + Start = Now.AddMinutes(-5), + Finish = Now.AddMinutes(5), + FillerKind = FillerKind.Fallback, + GuideGroup = 1, + ChapterTitle = string.Empty + }; + + context.Channels.Add(channel); + context.OtherVideos.Add(filler); + context.Playouts.Add(playout); + context.PlayoutItems.Add(item); + await context.SaveChangesAsync(); + + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + result.ShouldHaveSingleItem().NowPlaying.ShouldBeNull(); + } + + [Test] + public async Task Handle_Should_Map_Remote_Stream_NowPlaying_Title() + { + DateTime start = Now.AddMinutes(-10); + DateTime finish = Now.AddMinutes(20); + + await using TvContext context = _db.CreateContext(); + Channel channel = MakeChannel(9, "9"); + var remoteStream = new RemoteStream + { + Id = 90, + RemoteStreamMetadata = [new RemoteStreamMetadata { Title = "Live Source" }] + }; + var playout = new Playout { Id = 91, Channel = channel, ChannelId = channel.Id, Items = [] }; + var item = new PlayoutItem + { + Id = 92, + MediaItem = remoteStream, + MediaItemId = remoteStream.Id, + Playout = playout, + PlayoutId = playout.Id, + Start = start, + Finish = finish, + ChapterTitle = string.Empty + }; + + context.Channels.Add(channel); + context.RemoteStreams.Add(remoteStream); + context.Playouts.Add(playout); + context.PlayoutItems.Add(item); + await context.SaveChangesAsync(); + + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + ChannelStateResponseModel state = + (await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None)) + .ShouldHaveSingleItem(); + + state.NowPlaying.ShouldNotBeNull(); + state.NowPlaying.Title.ShouldBe("Live Source"); + } + + [Test] + public async Task Handle_Should_Resolve_Mirror_Channel_NowPlaying_From_Source_With_Offset() + { + TimeSpan offset = TimeSpan.FromHours(1); + DateTime sourceStart = Now.AddMinutes(-70); + DateTime sourceFinish = Now.AddMinutes(-40); + + await using TvContext context = _db.CreateContext(); + Channel source = MakeChannel(10, "10"); + Channel mirror = MakeChannel(11, "11"); + mirror.PlayoutSource = ChannelPlayoutSource.Mirror; + mirror.MirrorSourceChannelId = source.Id; + mirror.PlayoutOffset = offset; + + var movie = new Movie + { + Id = 110, + MovieMetadata = [new MovieMetadata { Title = "Offset Feature" }] + }; + var playout = new Playout { Id = 111, Channel = source, ChannelId = source.Id, Items = [] }; + var item = new PlayoutItem + { + Id = 112, + MediaItem = movie, + MediaItemId = movie.Id, + Playout = playout, + PlayoutId = playout.Id, + Start = sourceStart, + Finish = sourceFinish, + ChapterTitle = string.Empty + }; + + context.Channels.AddRange(source, mirror); + context.Movies.Add(movie); + context.Playouts.Add(playout); + context.PlayoutItems.Add(item); + await context.SaveChangesAsync(); + + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + ChannelStateResponseModel mirrorState = result.Single(s => s.ChannelId == mirror.Id); + mirrorState.NowPlaying.ShouldNotBeNull(); + mirrorState.NowPlaying.Title.ShouldBe("Offset Feature"); + mirrorState.NowPlaying.StartUtc.ShouldBe(new DateTimeOffset(sourceStart + offset, TimeSpan.Zero)); + mirrorState.NowPlaying.FinishUtc.ShouldBe(new DateTimeOffset(sourceFinish + offset, TimeSpan.Zero)); + + // the source's own item is 40+ minutes in the past with no offset, so its own row is off-air + ChannelStateResponseModel sourceState = result.Single(s => s.ChannelId == source.Id); + sourceState.NowPlaying.ShouldBeNull(); + } + + private async Task SeedChannelWithMovie(DateTime start, DateTime finish) + { + await using TvContext context = _db.CreateContext(); + Channel channel = MakeChannel(7, "7.1"); + var movie = new Movie + { + Id = 10, + MovieMetadata = [new MovieMetadata { Title = "Retro Cartoons" }] + }; + var playout = new Playout + { + Id = 20, + Channel = channel, + ChannelId = channel.Id, + Items = [] + }; + var item = new PlayoutItem + { + Id = 30, + MediaItem = movie, + MediaItemId = movie.Id, + Playout = playout, + PlayoutId = playout.Id, + Start = start, + Finish = finish, + ChapterTitle = string.Empty + }; + + context.Channels.Add(channel); + context.Movies.Add(movie); + context.Playouts.Add(playout); + context.PlayoutItems.Add(item); + await context.SaveChangesAsync(); + } + + private static Channel MakeChannel(int id, string number) => + new(Guid.NewGuid()) + { + Id = id, + Number = number, + SortNumber = id, + Name = $"Channel {number}", + Group = "Test", + Categories = string.Empty, + PreferredAudioLanguageCode = string.Empty + }; +} diff --git a/ErsatzTV.Tests/Application/Channels/UpdateChannelNumbersHandlerTests.cs b/ErsatzTV.Tests/Application/Channels/UpdateChannelNumbersHandlerTests.cs new file mode 100644 index 000000000..e6bfc04a3 --- /dev/null +++ b/ErsatzTV.Tests/Application/Channels/UpdateChannelNumbersHandlerTests.cs @@ -0,0 +1,111 @@ +using ErsatzTV.Application.Channels; +using ErsatzTV.Core; +using ErsatzTV.Core.Errors; +using ErsatzTV.Infrastructure.Data; +using ErsatzTV.Tests.Support; +using LanguageExt; +using Microsoft.EntityFrameworkCore; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Tests.Application.Channels; + +[TestFixture] +public class UpdateChannelNumbersHandlerTests : ChannelHandlerTestBase +{ + private UpdateChannelNumbersHandler MakeHandler() => new(Db.Factory, Worker); + + [Test] + public async Task Should_Renumber_All_Channels() + { + await SeedChannel(1, "5"); + await SeedChannel(2, "6"); + + Option result = await MakeHandler().Handle( + new UpdateChannelNumbers( + [ + new ChannelSortViewModel { Id = 1, Number = "10" }, + new ChannelSortViewModel { Id = 2, Number = "11.1" } + ]), + CancellationToken.None); + + result.IsNone.ShouldBeTrue(); + + await using TvContext context = Db.CreateContext(); + var channels = await context.Channels + .OrderBy(c => c.Id) + .Select(c => new { c.Number, c.SortNumber }) + .ToListAsync(); + channels[0].Number.ShouldBe("10"); + channels[0].SortNumber.ShouldBe(10); + channels[1].Number.ShouldBe("11.1"); + channels[1].SortNumber.ShouldBe(11.1); + } + + [Test] + public async Task Should_Return_NotFound_And_Not_Renumber_When_Any_Channel_Is_Missing() + { + await SeedChannel(1, "5"); + + Option result = await MakeHandler().Handle( + new UpdateChannelNumbers( + [ + new ChannelSortViewModel { Id = 1, Number = "10" }, + new ChannelSortViewModel { Id = 99, Number = "11" } + ]), + CancellationToken.None); + + BaseError error = ErrorOf(result); + error.ShouldBeOfType(); + + await using TvContext context = Db.CreateContext(); + string number = await context.Channels.Where(c => c.Id == 1).Select(c => c.Number).SingleAsync(); + number.ShouldBe("5"); + } + + [Test] + public async Task Should_Reject_Duplicate_Numbers_And_Not_Renumber() + { + await SeedChannel(1, "5"); + await SeedChannel(2, "6"); + + Option result = await MakeHandler().Handle( + new UpdateChannelNumbers( + [ + new ChannelSortViewModel { Id = 1, Number = "10" }, + new ChannelSortViewModel { Id = 2, Number = "10" } + ]), + CancellationToken.None); + + BaseError error = ErrorOf(result); + error.ShouldNotBeOfType(); + error.Value.ShouldContain("unique"); + + await using TvContext context = Db.CreateContext(); + List numbers = await context.Channels.OrderBy(c => c.Id).Select(c => c.Number).ToListAsync(); + numbers.ShouldBe(["5", "6"]); + } + + [Test] + public async Task Should_Reject_Invalid_Number_And_Not_Renumber() + { + await SeedChannel(1, "5"); + + Option result = await MakeHandler().Handle( + new UpdateChannelNumbers([new ChannelSortViewModel { Id = 1, Number = "10.123" }]), + CancellationToken.None); + + BaseError error = ErrorOf(result); + error.ShouldNotBeOfType(); + error.Value.ShouldContain("Invalid channel number"); + + await using TvContext context = Db.CreateContext(); + string number = await context.Channels.Where(c => c.Id == 1).Select(c => c.Number).SingleAsync(); + number.ShouldBe("5"); + } + + private static BaseError ErrorOf(Option result) => + result.Match( + Some: error => error, + None: () => throw new AssertionException("Expected an error")); +} diff --git a/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs b/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs index e290ede9c..f2691266a 100644 --- a/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs +++ b/ErsatzTV.Tests/Controllers/ApiErrorResponseMetadataTests.cs @@ -17,6 +17,12 @@ public class ApiErrorResponseMetadataTests [TestCase(typeof(ChannelController), nameof(ChannelController.Update), StatusCodes.Status422UnprocessableEntity)] [TestCase(typeof(ChannelController), nameof(ChannelController.Delete), StatusCodes.Status404NotFound)] [TestCase(typeof(ChannelController), nameof(ChannelController.Delete), StatusCodes.Status422UnprocessableEntity)] + [TestCase(typeof(ChannelController), nameof(ChannelController.BulkRenumber), StatusCodes.Status404NotFound)] + [TestCase(typeof(ChannelController), nameof(ChannelController.BulkRenumber), StatusCodes.Status422UnprocessableEntity)] + [TestCase(typeof(ChannelController), nameof(ChannelController.BulkMoveToGroup), StatusCodes.Status404NotFound)] + [TestCase(typeof(ChannelController), nameof(ChannelController.BulkMoveToGroup), StatusCodes.Status422UnprocessableEntity)] + [TestCase(typeof(ChannelController), nameof(ChannelController.BulkDelete), StatusCodes.Status404NotFound)] + [TestCase(typeof(ChannelController), nameof(ChannelController.BulkDelete), StatusCodes.Status422UnprocessableEntity)] [TestCase(typeof(ChannelController), nameof(ChannelController.ResetPlayout), StatusCodes.Status404NotFound)] [TestCase(typeof(CollectionController), nameof(CollectionController.GetById), StatusCodes.Status404NotFound)] [TestCase(typeof(CollectionController), nameof(CollectionController.Create), StatusCodes.Status404NotFound)] diff --git a/ErsatzTV.Tests/Controllers/ChannelControllerTests.cs b/ErsatzTV.Tests/Controllers/ChannelControllerTests.cs index 65def054f..5593c9164 100644 --- a/ErsatzTV.Tests/Controllers/ChannelControllerTests.cs +++ b/ErsatzTV.Tests/Controllers/ChannelControllerTests.cs @@ -36,6 +36,25 @@ public class ChannelControllerTests _controller = new ChannelController(_workerChannel.Writer, _mediator); } + [Test] + public async Task GetState_Should_Return_200_With_Channel_State() + { + var state = new ChannelStateResponseModel( + 7, + "7.1", + true, + new ChannelNowPlayingResponseModel( + "Retro Cartoons", + new DateTimeOffset(2026, 7, 2, 17, 0, 0, TimeSpan.Zero), + new DateTimeOffset(2026, 7, 2, 17, 30, 0, TimeSpan.Zero))); + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns([state]); + + List result = await _controller.GetState(CancellationToken.None); + + result.ShouldBe(new List { state }); + } + [Test] public async Task Create_Should_Return_201_With_Location_And_Body() { @@ -127,6 +146,23 @@ public class ChannelControllerTests result.ShouldBeOfType(); } + [Test] + public async Task BulkRenumber_Should_Return_204_And_Map_Request() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Option.None); + + IActionResult result = await _controller.BulkRenumber( + new BulkRenumberChannelsRequest([new BulkRenumberChannelRequest(1, "10")]), + CancellationToken.None); + + result.ShouldBeOfType(); + await _mediator.Received(1).Send( + Arg.Is( + c => c.Channels.Count == 1 && c.Channels[0].Id == 1 && c.Channels[0].Number == "10"), + Arg.Any()); + } + [Test] public async Task GetGuide_Should_Map_Query_And_Return_Model() { @@ -143,6 +179,36 @@ public class ChannelControllerTests Arg.Any()); } + [Test] + public async Task BulkRenumber_Should_Return_422_On_Validation_Error() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Option.Some(BaseError.New("bad"))); + + IActionResult result = await _controller.BulkRenumber( + new BulkRenumberChannelsRequest([new BulkRenumberChannelRequest(1, "bad")]), + CancellationToken.None); + + result.ShouldBeOfType(); + } + + [Test] + public async Task BulkMoveToGroup_Should_Return_204_And_Map_Request() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Right(Unit.Default)); + + IActionResult result = await _controller.BulkMoveToGroup( + new BulkMoveChannelsToGroupRequest([1, 2], "Movies"), + CancellationToken.None); + + result.ShouldBeOfType(); + await _mediator.Received(1).Send( + Arg.Is( + c => c.ChannelIds.SequenceEqual(new[] { 1, 2 }) && c.Group == "Movies"), + Arg.Any()); + } + [Test] public async Task GetGuide_Should_Pass_Null_Bounds_Through() { @@ -156,6 +222,48 @@ public class ChannelControllerTests Arg.Any()); } + [Test] + public async Task BulkMoveToGroup_Should_Return_404_For_NotFoundError() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Left(new NotFoundError("missing"))); + + IActionResult result = await _controller.BulkMoveToGroup( + new BulkMoveChannelsToGroupRequest([99], "Movies"), + CancellationToken.None); + + result.ShouldBeOfType(); + } + + [Test] + public async Task BulkDelete_Should_Return_204_And_Map_Request() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Right(Unit.Default)); + + IActionResult result = await _controller.BulkDelete( + new BulkDeleteChannelsRequest([1, 2]), + CancellationToken.None); + + result.ShouldBeOfType(); + await _mediator.Received(1).Send( + Arg.Is(c => c.ChannelIds.SequenceEqual(new[] { 1, 2 })), + Arg.Any()); + } + + [Test] + public async Task BulkDelete_Should_Return_404_For_NotFoundError() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Left(new NotFoundError("missing"))); + + IActionResult result = await _controller.BulkDelete( + new BulkDeleteChannelsRequest([99]), + CancellationToken.None); + + result.ShouldBeOfType(); + } + [Test] public async Task GetById_Should_Return_200_For_Some() { diff --git a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs index 1599f11c8..aa5ccaa91 100644 --- a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs +++ b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs @@ -23,6 +23,82 @@ public class OpenApiErrorResponseContractTests .ShouldContain("One"); } + [Test] + public void Static_OpenApi_Should_Document_Channel_List_Management_Fields() + { + using JsonDocument document = JsonDocument.Parse(File.ReadAllText(FindOpenApiDocument())); + + JsonElement schema = document.RootElement + .GetProperty("components") + .GetProperty("schemas") + .GetProperty("ChannelResponseModel") + .GetProperty("properties"); + + schema.TryGetProperty("group", out _).ShouldBeTrue(); + schema.TryGetProperty("isEnabled", out _).ShouldBeTrue(); + schema.TryGetProperty("showInEpg", out _).ShouldBeTrue(); + schema.TryGetProperty("sortNumber", out _).ShouldBeTrue(); + schema.TryGetProperty("categories", out _).ShouldBeTrue(); + } + + [Test] + public void Static_OpenApi_Should_Document_Channel_State_Response() + { + using JsonDocument document = JsonDocument.Parse(File.ReadAllText(FindOpenApiDocument())); + + JsonElement getState = document.RootElement + .GetProperty("paths") + .GetProperty("/api/channels/state") + .GetProperty("get"); + + JsonElement schema = getState + .GetProperty("responses") + .GetProperty("200") + .GetProperty("content") + .GetProperty("application/json") + .GetProperty("schema"); + + schema.GetProperty("type").GetString().ShouldBe("array"); + schema.GetProperty("items").GetProperty("$ref").GetString() + .ShouldBe("#/components/schemas/ChannelStateResponseModel"); + + JsonElement stateProperties = document.RootElement + .GetProperty("components") + .GetProperty("schemas") + .GetProperty("ChannelStateResponseModel") + .GetProperty("properties"); + + stateProperties.TryGetProperty("channelId", out _).ShouldBeTrue(); + stateProperties.TryGetProperty("channelNumber", out _).ShouldBeTrue(); + stateProperties.TryGetProperty("onAir", out _).ShouldBeTrue(); + stateProperties.TryGetProperty("nowPlaying", out JsonElement nowPlaying).ShouldBeTrue(); + + JsonElement nowPlayingOneOf = nowPlaying.GetProperty("oneOf"); + nowPlayingOneOf.EnumerateArray().Count().ShouldBe(2); + nowPlayingOneOf.EnumerateArray() + .Any(s => s.TryGetProperty("type", out JsonElement type) && type.GetString() == "null") + .ShouldBeTrue(); + nowPlayingOneOf.EnumerateArray() + .Any(s => s.TryGetProperty("$ref", out JsonElement schemaRef) && + schemaRef.GetString() == "#/components/schemas/ChannelNowPlayingResponseModel") + .ShouldBeTrue(); + + JsonElement nowPlayingProperties = document.RootElement + .GetProperty("components") + .GetProperty("schemas") + .GetProperty("ChannelNowPlayingResponseModel") + .GetProperty("properties"); + + nowPlayingProperties.TryGetProperty("title", out _).ShouldBeTrue(); + nowPlayingProperties.TryGetProperty("startUtc", out JsonElement startUtc).ShouldBeTrue(); + nowPlayingProperties.TryGetProperty("finishUtc", out JsonElement finishUtc).ShouldBeTrue(); + + startUtc.GetProperty("type").GetString().ShouldBe("string"); + startUtc.GetProperty("format").GetString().ShouldBe("date-time"); + finishUtc.GetProperty("type").GetString().ShouldBe("string"); + finishUtc.GetProperty("format").GetString().ShouldBe("date-time"); + } + [TestCase("/api/channels/{id}", "get", "404")] [TestCase("/api/channels", "post", "404")] [TestCase("/api/channels", "post", "422")] @@ -30,6 +106,12 @@ public class OpenApiErrorResponseContractTests [TestCase("/api/channels/{id}", "put", "422")] [TestCase("/api/channels/{id}", "delete", "404")] [TestCase("/api/channels/{id}", "delete", "422")] + [TestCase("/api/channels/bulk/renumber", "post", "404")] + [TestCase("/api/channels/bulk/renumber", "post", "422")] + [TestCase("/api/channels/bulk/group", "post", "404")] + [TestCase("/api/channels/bulk/group", "post", "422")] + [TestCase("/api/channels/bulk/delete", "post", "404")] + [TestCase("/api/channels/bulk/delete", "post", "422")] [TestCase("/api/channels/{channelNumber}/playout/reset", "post", "404")] [TestCase("/api/collections/{id}", "get", "404")] [TestCase("/api/collections", "post", "404")] diff --git a/ErsatzTV.Tests/StartupSpaHostingTests.cs b/ErsatzTV.Tests/StartupSpaHostingTests.cs new file mode 100644 index 000000000..715f861d1 --- /dev/null +++ b/ErsatzTV.Tests/StartupSpaHostingTests.cs @@ -0,0 +1,45 @@ +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Tests; + +[TestFixture] +public class StartupSpaHostingTests +{ + private static readonly string StartupSource = File.ReadAllText(FindStartupPath()); + + [Test] + public void Startup_Should_Mount_ChicoryTv_Spa_At_App_Path() + { + StartupSource.ShouldContain("ctx.Request.Path.StartsWithSegments(\"/app\")"); + StartupSource.ShouldContain("MapWhen("); + StartupSource.ShouldContain("SpaStaticFileRoot"); + StartupSource.ShouldContain("RequestPath = \"/app\""); + StartupSource.ShouldContain("appIndexFile"); + } + + [Test] + public void Startup_Should_Not_Send_App_Routes_To_Blazor_Fallback() + { + StartupSource.ShouldContain("!IsSpaPath(ctx.Request.Path)"); + StartupSource.ShouldContain("bool IsSpaPath(PathString path)"); + } + + private static string FindStartupPath() + { + DirectoryInfo? directory = new(TestContext.CurrentContext.TestDirectory); + + while (directory is not null) + { + string candidate = Path.Combine(directory.FullName, "ErsatzTV", "Startup.cs"); + if (File.Exists(candidate)) + { + return candidate; + } + + directory = directory.Parent; + } + + throw new FileNotFoundException("Could not find ErsatzTV/Startup.cs"); + } +} diff --git a/ErsatzTV.Tests/Support/ChannelHandlerTestBase.cs b/ErsatzTV.Tests/Support/ChannelHandlerTestBase.cs index be790eed5..89296299e 100644 --- a/ErsatzTV.Tests/Support/ChannelHandlerTestBase.cs +++ b/ErsatzTV.Tests/Support/ChannelHandlerTestBase.cs @@ -35,7 +35,12 @@ public abstract class ChannelHandlerTestBase await context.SaveChangesAsync(); } - protected async Task SeedChannel(int id, string number, string name = "Test", int ffmpegProfileId = 1) + protected async Task SeedChannel( + int id, + string number, + string name = "Test", + int ffmpegProfileId = 1, + string group = "ErsatzTV") { await using TvContext context = Db.CreateContext(); context.Channels.Add( @@ -44,7 +49,7 @@ public abstract class ChannelHandlerTestBase Id = id, Number = number, Name = name, - Group = "ErsatzTV", + Group = group, Categories = string.Empty, FFmpegProfileId = ffmpegProfileId, StreamSelector = string.Empty, diff --git a/ErsatzTV/Controllers/Api/ChannelController.cs b/ErsatzTV/Controllers/Api/ChannelController.cs index c5d71d8ad..4ec99cdf5 100644 --- a/ErsatzTV/Controllers/Api/ChannelController.cs +++ b/ErsatzTV/Controllers/Api/ChannelController.cs @@ -22,6 +22,13 @@ public class ChannelController(ChannelWriter workerCh [EndpointGroupName("general")] public async Task> GetAll() => await mediator.Send(new GetAllChannelsForApi()); + [HttpGet("/api/channels/state")] + [Tags("Channels")] + [EndpointSummary("Get channel runtime state")] + [EndpointGroupName("general")] + public async Task> GetState(CancellationToken cancellationToken) => + await mediator.Send(new GetChannelStatesForApi(DateTime.UtcNow), cancellationToken); + [HttpGet("/api/guide")] [Tags("Channels")] [EndpointSummary("Get the JSON channel guide (EPG)")] @@ -102,6 +109,53 @@ public class ChannelController(ChannelWriter workerCh return result.ToDeletedResult(); } + [HttpPost("/api/channels/bulk/renumber")] + [Tags("Channels")] + [EndpointSummary("Renumber channels")] + [EndpointGroupName("general")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)] + public async Task BulkRenumber( + [Required] [FromBody] BulkRenumberChannelsRequest request, + CancellationToken cancellationToken) + { + Option result = await mediator.Send(request.ToCommand(), cancellationToken); + return result.Match( + Some: error => error.ToErrorResult(), + None: () => new NoContentResult()); + } + + [HttpPost("/api/channels/bulk/group")] + [Tags("Channels")] + [EndpointSummary("Move channels to a group")] + [EndpointGroupName("general")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)] + public async Task BulkMoveToGroup( + [Required] [FromBody] BulkMoveChannelsToGroupRequest request, + CancellationToken cancellationToken) + { + Either result = await mediator.Send(request.ToCommand(), cancellationToken); + return result.ToDeletedResult(); + } + + [HttpPost("/api/channels/bulk/delete")] + [Tags("Channels")] + [EndpointSummary("Delete channels")] + [EndpointGroupName("general")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)] + public async Task BulkDelete( + [Required] [FromBody] BulkDeleteChannelsRequest request, + CancellationToken cancellationToken) + { + Either result = await mediator.Send(request.ToCommand(), cancellationToken); + return result.ToDeletedResult(); + } + [HttpPost("/api/channels/{channelNumber}/playout/reset")] [Tags("Channels")] [EndpointSummary("Reset channel playout")] diff --git a/ErsatzTV/Controllers/Api/Requests/BulkChannelRequests.cs b/ErsatzTV/Controllers/Api/Requests/BulkChannelRequests.cs new file mode 100644 index 000000000..4a7a875f5 --- /dev/null +++ b/ErsatzTV/Controllers/Api/Requests/BulkChannelRequests.cs @@ -0,0 +1,22 @@ +#nullable enable +using ErsatzTV.Application.Channels; + +namespace ErsatzTV.Controllers.Api.Requests; + +public record BulkRenumberChannelRequest(int Id, string Number); + +public record BulkRenumberChannelsRequest(List Channels) +{ + public UpdateChannelNumbers ToCommand() => + new(Channels.Select(c => new ChannelSortViewModel { Id = c.Id, Number = c.Number }).ToList()); +} + +public record BulkMoveChannelsToGroupRequest(List ChannelIds, string Group) +{ + public BulkMoveChannelsToGroup ToCommand() => new(ChannelIds, Group); +} + +public record BulkDeleteChannelsRequest(List ChannelIds) +{ + public BulkDeleteChannels ToCommand() => new(ChannelIds); +} diff --git a/ErsatzTV/Startup.cs b/ErsatzTV/Startup.cs index 0e333f292..71f265cca 100644 --- a/ErsatzTV/Startup.cs +++ b/ErsatzTV/Startup.cs @@ -681,7 +681,42 @@ public class Startup }); app.MapWhen( - ctx => !IsIptvPath(ctx.Request.Path), + ctx => ctx.Request.Path.StartsWithSegments("/app"), + spa => + { + string spaStaticFileRoot = SpaStaticFileRoot(); + IFileProvider spaFileProvider = Directory.Exists(spaStaticFileRoot) + ? new PhysicalFileProvider(spaStaticFileRoot) + : new NullFileProvider(); + + spa.UseStaticFiles( + new StaticFileOptions + { + FileProvider = spaFileProvider, + RequestPath = "/app" + }); + + spa.Run( + async context => + { + Microsoft.Extensions.FileProviders.IFileInfo appIndexFile = + spaFileProvider.GetFileInfo("index.html"); + if (!appIndexFile.Exists) + { + context.Response.StatusCode = StatusCodes.Status404NotFound; + return; + } + + context.Response.ContentType = "text/html; charset=utf-8"; + context.Response.ContentLength = appIndexFile.Length; + + await using Stream stream = appIndexFile.CreateReadStream(); + await stream.CopyToAsync(context.Response.Body); + }); + }); + + app.MapWhen( + ctx => !IsIptvPath(ctx.Request.Path) && !IsSpaPath(ctx.Request.Path), blazor => { blazor.UseRouting(); @@ -736,6 +771,16 @@ public class Startup path.StartsWithSegments("/lineup.json") || path.StartsWithSegments("/lineup_status.json"); } + + bool IsSpaPath(PathString path) => path.StartsWithSegments("/app"); + + string SpaStaticFileRoot() + { + string webRootPath = CurrentEnvironment.WebRootPath ?? + Path.Combine(CurrentEnvironment.ContentRootPath, "wwwroot"); + + return Path.Combine(webRootPath, "app"); + } } private static void CustomServices(IServiceCollection services) diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json index 72654b915..e1a7159ea 100644 --- a/ErsatzTV/wwwroot/openapi/v1.json +++ b/ErsatzTV/wwwroot/openapi/v1.json @@ -215,6 +215,45 @@ } } }, + "/api/channels/state": { + "get": { + "tags": [ + "Channels" + ], + "summary": "Get channel runtime state", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ChannelStateResponseModel" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ChannelStateResponseModel" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ChannelStateResponseModel" + } + } + } + } + } + } + } + }, "/api/guide": { "get": { "tags": [ @@ -492,6 +531,240 @@ } } }, + "/api/channels/bulk/renumber": { + "post": { + "tags": [ + "Channels" + ], + "summary": "Renumber channels", + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/BulkRenumberChannelsRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/BulkRenumberChannelsRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/BulkRenumberChannelsRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/BulkRenumberChannelsRequest" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "No Content" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "422": { + "description": "Unprocessable Entity", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, + "/api/channels/bulk/group": { + "post": { + "tags": [ + "Channels" + ], + "summary": "Move channels to a group", + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/BulkMoveChannelsToGroupRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/BulkMoveChannelsToGroupRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/BulkMoveChannelsToGroupRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/BulkMoveChannelsToGroupRequest" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "No Content" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "422": { + "description": "Unprocessable Entity", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, + "/api/channels/bulk/delete": { + "post": { + "tags": [ + "Channels" + ], + "summary": "Delete channels", + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/BulkDeleteChannelsRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/BulkDeleteChannelsRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/BulkDeleteChannelsRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/BulkDeleteChannelsRequest" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "No Content" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "422": { + "description": "Unprocessable Entity", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, "/api/channels/{channelNumber}/playout/reset": { "post": { "tags": [ @@ -3636,6 +3909,70 @@ } } }, + "BulkDeleteChannelsRequest": { + "required": [ + "channelIds" + ], + "type": "object", + "properties": { + "channelIds": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + } + } + }, + "BulkMoveChannelsToGroupRequest": { + "required": [ + "channelIds", + "group" + ], + "type": "object", + "properties": { + "channelIds": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "group": { + "type": "string" + } + } + }, + "BulkRenumberChannelRequest": { + "required": [ + "id", + "number" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "number": { + "type": "string" + } + } + }, + "BulkRenumberChannelsRequest": { + "required": [ + "channels" + ], + "type": "object", + "properties": { + "channels": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BulkRenumberChannelRequest" + } + } + } + }, "ChannelGuideChannelResponseModel": { "required": [ "number", @@ -3735,6 +4072,27 @@ ], "type": "string" }, + "ChannelNowPlayingResponseModel": { + "required": [ + "title", + "startUtc", + "finishUtc" + ], + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "startUtc": { + "type": "string", + "format": "date-time" + }, + "finishUtc": { + "type": "string", + "format": "date-time" + } + } + }, "ChannelPlayoutMode": { "enum": [ "Continuous", @@ -3753,10 +4111,15 @@ "required": [ "id", "number", + "sortNumber", "name", + "group", + "categories", "fFmpegProfile", "language", - "streamingMode" + "streamingMode", + "isEnabled", + "showInEpg" ], "type": "object", "properties": { @@ -3765,34 +4128,35 @@ "format": "int32" }, "number": { - "type": [ - "null", - "string" - ] + "type": "string" + }, + "sortNumber": { + "type": "number", + "format": "double" }, "name": { - "type": [ - "null", - "string" - ] + "type": "string" + }, + "group": { + "type": "string" + }, + "categories": { + "type": "string" }, "fFmpegProfile": { - "type": [ - "null", - "string" - ] + "type": "string" }, "language": { - "type": [ - "null", - "string" - ] + "type": "string" }, "streamingMode": { - "type": [ - "null", - "string" - ] + "type": "string" + }, + "isEnabled": { + "type": "boolean" + }, + "showInEpg": { + "type": "boolean" } } }, @@ -3803,6 +4167,37 @@ ], "type": "string" }, + "ChannelStateResponseModel": { + "required": [ + "channelId", + "channelNumber", + "onAir", + "nowPlaying" + ], + "type": "object", + "properties": { + "channelId": { + "type": "integer", + "format": "int32" + }, + "channelNumber": { + "type": "string" + }, + "onAir": { + "type": "boolean" + }, + "nowPlaying": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ChannelNowPlayingResponseModel" + } + ] + } + } + }, "ChannelStreamSelectorMode": { "enum": [ "Default", diff --git a/design-system/Canvas.dc.html b/design-system/Canvas.dc.html new file mode 100644 index 000000000..c795a2fcd --- /dev/null +++ b/design-system/Canvas.dc.html @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/design-system/SKILL.md b/design-system/SKILL.md new file mode 100644 index 000000000..35b7a0d21 --- /dev/null +++ b/design-system/SKILL.md @@ -0,0 +1,17 @@ +--- +name: chicorytv-design +description: Use this skill to generate well-branded interfaces and assets for ChicoryTV, either for production or throwaway prototypes/mocks/etc. Contains essential design guidelines, colors, type, fonts, assets, and UI kit components for prototyping. +user-invocable: true +--- + +Read the README.md file within this skill, and explore the other available files. +If creating visual artifacts (slides, mocks, throwaway prototypes, etc), copy assets out and create static HTML files for the user to view. If working on production code, you can copy assets and read the rules here to become an expert in designing with this brand. +If the user invokes this skill without any other guidance, ask them what they want to build or design, ask some questions, and act as an expert designer who outputs HTML artifacts _or_ production code, depending on the need. + +Quick map: +- `readme.md` — brand context, content & visual foundations, iconography, file index. +- `styles.css` — the single entry point; link it and use the CSS custom properties. +- `tokens/` — color, type, spacing, radius/elevation/motion tokens + font loading. +- `components/` — React primitives (forms, data-display, feedback, navigation). +- `templates/chicorytv-admin/` — full admin shell to start from / copy screens out of (incl. the library-to-lineup Channel Builder). +- `assets/` — chicory-flower mark, wordmark, app icon. diff --git a/design-system/_adherence.oxlintrc.json b/design-system/_adherence.oxlintrc.json new file mode 100644 index 000000000..9339acdb7 --- /dev/null +++ b/design-system/_adherence.oxlintrc.json @@ -0,0 +1,470 @@ +{ + "plugins": [ + "react", + "import" + ], + "rules": { + "react/forbid-elements": [ + "warn", + { + "forbid": [] + } + ], + "no-restricted-imports": [ + "warn", + { + "patterns": [ + { + "group": [ + "components/data-display/**", + "components/feedback/**", + "components/forms/**", + "components/navigation/**", + "design_handoff_channel_builder/**" + ], + "message": "Import design-system components from 'index.js', not component internals." + } + ] + } + ], + "no-restricted-syntax": [ + "warn", + { + "selector": "Literal[value=/#[0-9a-fA-F]{3,8}\\b/]", + "message": "Raw hex color — use a design-system color token via var()." + }, + { + "selector": "Literal[value=/\\b\\d+px\\b/]", + "message": "Raw px value — use a design-system spacing token via var()." + }, + { + "selector": "Literal[value=/font-family\\s*:\\s*(?!['\\\"]?(?:Geist|Geist Mono))/i]", + "message": "Font not provided by the design system. Available: Geist, Geist Mono." + }, + { + "selector": "JSXOpeningElement[name.name='Badge'] > JSXAttribute > JSXIdentifier[name!=/^(?:children|tone|solid|dot|style|key|ref|className|style|children)$/]", + "message": " doesn't accept that prop. Declared props: children, tone, solid, dot, style." + }, + { + "selector": "JSXOpeningElement[name.name='Badge'] > JSXAttribute[name.name='tone'] > Literal[value!=/^(?:neutral|accent|ok|warn|error)$/]", + "message": " tone must be one of 'neutral' | 'accent' | 'ok' | 'warn' | 'error'." + }, + { + "selector": "JSXOpeningElement[name.name='Button'] > JSXAttribute > JSXIdentifier[name!=/^(?:children|variant|size|startIcon|endIcon|disabled|loading|fullWidth|type|onClick|style|key|ref|className|style|children)$/]", + "message": " + ); +} diff --git a/design-system/components/navigation/Tabs.prompt.md b/design-system/components/navigation/Tabs.prompt.md new file mode 100644 index 000000000..f7298dbab --- /dev/null +++ b/design-system/components/navigation/Tabs.prompt.md @@ -0,0 +1,8 @@ +**Tabs** — underlined tab bar for editor sub-views and detail panes (Channel → General / Streaming / Watermark; Playout → Detail / Log). Active tab shows an accent underline. + +```jsx + +``` + +Props: `tabs` (string | {value,label,icon,count}), `value`, `onChange`. diff --git a/design-system/components/navigation/navigation.card.html b/design-system/components/navigation/navigation.card.html new file mode 100644 index 000000000..dbf54771c --- /dev/null +++ b/design-system/components/navigation/navigation.card.html @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + +
+ + + diff --git a/design-system/design_handoff_channel_builder/ChannelBuilder.jsx b/design-system/design_handoff_channel_builder/ChannelBuilder.jsx new file mode 100644 index 000000000..452c63399 --- /dev/null +++ b/design-system/design_handoff_channel_builder/ChannelBuilder.jsx @@ -0,0 +1,619 @@ +// Channel Builder — GROUND-UP replacement for the four-editor create chain +// (Channel -> Schedule -> Schedule Items -> Playout). One library-to-lineup screen. +// Left: searchable library browser. Center: the channel lineup (add by double-click +// or drag; drag to reorder). Right: friendly options + Channel Template + Advanced. +// Behind the scenes "Create" builds Channel + Collection + Schedule + Items + Playout. +(function () { + const NS = window.ChicoryTVDesignSystem_eb3b61; + const { Button, IconButton, Input, Select, Switch, Badge, ChannelLogo, Tooltip } = NS; + const Ico = window.Ico; + const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" }; + const eyebrow = { font: "var(--weight-semibold) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--text-disabled)" }; + + // ---- Mock library (shows / movies / music / docs across libraries) -------- + const LIB = [ + { id: "s1", title: "Looney Tunes", type: "Show", library: "Cartoons", sub: "247 shorts", min: 96 }, + { id: "s2", title: "Tom & Jerry", type: "Show", library: "Cartoons", sub: "164 shorts", min: 72 }, + { id: "s3", title: "Popeye", type: "Show", library: "Cartoons", sub: "108 shorts", min: 54 }, + { id: "s4", title: "The Flintstones", type: "Show", library: "Cartoons", sub: "166 episodes", min: 84 }, + { id: "s5", title: "Scooby-Doo", type: "Show", library: "Cartoons", sub: "97 episodes", min: 60 }, + { id: "s6", title: "Pink Panther", type: "Show", library: "Cartoons", sub: "124 shorts", min: 48 }, + { id: "m1", title: "Blade Runner", type: "Movie", library: "Movies", sub: "1982 · Sci-Fi", min: 117 }, + { id: "m2", title: "Alien", type: "Movie", library: "Movies", sub: "1979 · Horror", min: 117 }, + { id: "m3", title: "The Thing", type: "Movie", library: "Movies", sub: "1982 · Horror", min: 109 }, + { id: "m4", title: "Metropolis", type: "Movie", library: "Movies", sub: "1927 · Sci-Fi", min: 153 }, + { id: "m5", title: "Nosferatu", type: "Movie", library: "Movies", sub: "1922 · Horror", min: 94 }, + { id: "t1", title: "The Twilight Zone", type: "Show", library: "TV Shows", sub: "156 episodes", min: 51 }, + { id: "t2", title: "Star Trek", type: "Show", library: "TV Shows", sub: "79 episodes", min: 50 }, + { id: "t3", title: "Columbo", type: "Show", library: "TV Shows", sub: "69 episodes", min: 94 }, + { id: "t4", title: "Cheers", type: "Show", library: "TV Shows", sub: "275 episodes", min: 24 }, + { id: "u1", title: "80s Synthpop", type: "Music", library: "Music Videos", sub: "212 videos", min: 45 }, + { id: "u2", title: "90s Alt Rock", type: "Music", library: "Music Videos", sub: "188 videos", min: 45 }, + { id: "u3", title: "Chart Countdown", type: "Music", library: "Music Videos", sub: "Top 40", min: 60 }, + { id: "d1", title: "Blue Planet", type: "Doc", library: "Documentaries", sub: "8 episodes", min: 50 }, + { id: "d2", title: "Planet Earth", type: "Doc", library: "Documentaries", sub: "11 episodes", min: 50 }, + { id: "d3", title: "Cosmos", type: "Doc", library: "Documentaries", sub: "13 episodes", min: 60 }, + ]; + const LIBRARIES = ["All", "Cartoons", "Movies", "TV Shows", "Music Videos", "Documentaries"]; + const TYPE_ICON = { Show: "Tv", Movie: "Film", Music: "Music", Doc: "Radio", Multi: "Layers", Smart: "Sparkles", Manual: "FolderTree", Rerun: "Repeat" }; + + // Collections — curated groups (Manual / Smart / Multi / Rerun) addable as a + // single lineup entry, so the builder isn't limited to raw library items. + const COLLECTIONS = [ + { id: "c1", title: "Prime Time Cartoons", type: "Multi", library: "Collection", sub: "Multi · 62 items", min: 180, coll: true }, + { id: "c2", title: "Classic Sci-Fi", type: "Smart", library: "Collection", sub: "Smart · rating \u2265 8", min: 240, coll: true }, + { id: "c3", title: "Retro Station IDs", type: "Manual", library: "Collection", sub: "Manual · 24 items", min: 12, coll: true }, + { id: "c4", title: "Saturday Morning", type: "Rerun", library: "Collection", sub: "Rerun block · weekly",min: 120, coll: true }, + { id: "c5", title: "Halloween Marathon", type: "Manual", library: "Collection", sub: "Manual · 9 films", min: 900, coll: true }, + ]; + + // Channel Templates — bundle the clunky technical config; one is pre-selected. + const TEMPLATES = [ + { id: "std", name: "Standard", builtin: true, desc: "General-purpose 1080p H.264, retro bumpers.", shuffle: false, always: true, + sets: ["1080p H.264", "HLS Segmenter", "Sequential", "Always on", "Pre + post filler"] }, + { id: "music", name: "Music videos", builtin: true, desc: "Continuous rotation, no fillers, direct stream.", shuffle: true, always: true, + sets: ["720p H.264", "HLS Direct", "Shuffle", "Always on", "No filler"] }, + { id: "film", name: "Movie night", builtin: true, desc: "Film-grain HEVC, mid-roll ad breaks.", shuffle: false, always: false, + sets: ["1080p HEVC", "MPEG-TS", "Sequential", "On-demand", "Mid-roll ads"] }, + { id: "retro", name: "Retro Saturday AM", builtin: false, desc: "Your saved cartoon-block template.", shuffle: true, always: true, + sets: ["1080p H.264", "HLS Segmenter", "Shuffle", "Always on", "Bumpers + ads"] }, + ]; + + // Advanced (~30-field) override set, grouped. Values shown as template-inherited. + const ADV = [ + { group: "Streaming", fields: [ + ["Streaming mode", "HLS Segmenter"], ["FFmpeg profile", "1080p H.264"], ["Resolution", "1920×1080"], + ["Video bitrate", "8000 kbps"], ["Audio bitrate", "192 kbps"], ["Buffer size", "16000 kb"], + ]}, + { group: "Filler", fields: [ + ["Pre-roll", "Retro Bumpers"], ["Mid-roll", "Ad Break"], ["Post-roll", "Outro"], + ["Tail filler", "None"], ["Fallback", "Test Pattern"], ["Filler kind", "Pad to :00"], + ]}, + { group: "Playback", fields: [ + ["Interleave", "On"], ["Keep multi-part together", "On"], ["Watermark", "Channel logo"], + ["Subtitle mode", "Any"], ["Preferred audio", "English"], ["Preferred subtitle", "None"], + ]}, + { group: "Behavior", fields: [ + ["Guide mode default", "Normal"], ["Song video mode", "Off"], ["On-demand", "Off"], + ["Idle behavior", "Offline image"], ["Transcode audio", "Normalize"], ["Number scheme", "Auto"], + ]}, + ]; + + // deterministic low-chroma poster hue from a title + function hueOf(s) { let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) % 360; return h; } + + function fmtDur(totalMin) { + const h = Math.floor(totalMin / 60), m = totalMin % 60; + if (h && m) return h + "h " + String(m).padStart(2, "0") + "m"; + if (h) return h + "h"; + return m + "m"; + } + + // ---- Overlay scroll region — hides native bar (no reflow when it appears), + // shows a subtle thumb only while scrolling, fading out when idle. ------ + function ScrollArea({ children, innerStyle, scrollerRef }) { + const local = React.useRef(null); + const timer = React.useRef(null); + const [thumb, setThumb] = React.useState(null); + const setRef = (n) => { local.current = n; if (scrollerRef) scrollerRef.current = n; }; + const update = () => { + const el = local.current; if (!el) return; + const { scrollTop, scrollHeight, clientHeight } = el; + if (scrollHeight <= clientHeight + 2) { setThumb(null); return; } + const track = clientHeight - 8; + const h = Math.max(28, track * clientHeight / scrollHeight); + const top = 4 + (track - h) * (scrollTop / (scrollHeight - clientHeight)); + setThumb({ top, h }); + clearTimeout(timer.current); + timer.current = setTimeout(() => setThumb((t) => (t ? { ...t, hidden: true } : null)), 850); + }; + React.useEffect(() => { const id = setTimeout(update, 60); return () => { clearTimeout(id); clearTimeout(timer.current); }; }, []); + return ( +
+
+ {children} +
+ {thumb && ( +
+ )} +
+ ); + } + + // ---- Segmented control — iOS-style sliding active highlight --------------- + function Segmented({ value, options, onChange, style }) { + const idx = Math.max(0, options.findIndex((o) => o.value === value)); + return ( +
+
+ {options.map((o) => { + const on = o.value === value; + return ( + + ); + })} +
+ ); + } + + // ---- Poster placeholder (striped, tinted, mono meta) ---------------------- + function Poster({ item, w, h, mini }) { + const hue = hueOf(item.title); + return ( +
+
+
+ +
+ {!mini && ( +
+
{item.title}
+
{item.sub}
+
+ )} +
+ ); + } + + // ---- Library card ---------------------------------------------------------- + function LibCard({ item, added, compact, onAdd, onDragStart, onDragEnd }) { + if (compact) { + return ( +
+ +
+
{item.title}
+
{item.type} · {item.sub}
+
+ + + +
+ ); + } + return ( +
+
+ + {added && ( +
+ +
+ )} +
+
+ ); + } + + // ---- Lineup row ------------------------------------------------------------ + function LineupRow({ item, index, shuffle, dragging, isOver, onRemove, dragProps }) { + return ( +
+ + + {shuffle + ? + : {index + 1}} + + +
+
{item.title}
+
{item.type} · {item.library}
+
+ {fmtDur(item.min)} + +
+ ); + } + + // ---- Channel image dropzone + live logo/bug preview ----------------------- + function ImagePanel({ logoSrc, setLogoSrc, name }) { + const [sep, setSep] = React.useState(false); + const [over, setOver] = React.useState(false); + const fileRef = React.useRef(null); + const read = (file) => { if (!file) return; const r = new FileReader(); r.onload = () => setLogoSrc(r.result); r.readAsDataURL(file); }; + return ( +
+
{ e.preventDefault(); setOver(true); }} + onDragLeave={() => setOver(false)} + onDrop={(e) => { e.preventDefault(); setOver(false); read(e.dataTransfer.files && e.dataTransfer.files[0]); }} + onClick={() => fileRef.current && fileRef.current.click()} + style={{ display: "flex", gap: 12, padding: 12, borderRadius: "var(--radius-sm)", cursor: "pointer", + background: "var(--ctv-bg-sunken)", border: `1px dashed ${over ? "var(--ctv-accent)" : "var(--border-control)"}` }}> + +
+
{logoSrc ? "Channel image set" : "Drop channel image"}
+
Used as both the guide logo and the on-screen bug.
+
+ read(e.target.files && e.target.files[0])} /> +
+ + {/* live preview: listing logo + on-screen bug */} +
+
+
Guide logo
+
+ +
+
{name || "New Channel"}
+
listing
+
+
+
+
+
On-screen bug
+
+
+ +
+
+
+
+ + + {sep && ( +
+ + +
+ )} +
+ ); + } + + // ---- Advanced disclosure — one-click Override (edit) or View defaults ------ + function Advanced({ templateName, scrollerRef }) { + const [mode, setMode] = React.useState("closed"); // closed | view | override + const [vals, setVals] = React.useState(() => { const o = {}; ADV.forEach((g) => g.fields.forEach(([k, v]) => { o[k] = v; })); return o; }); + const override = mode === "override"; + const count = ADV.reduce((n, g) => n + g.fields.length, 0); + const fieldsRef = React.useRef(null); + const rootRef = React.useRef(null); + const [maxH, setMaxH] = React.useState(0); + React.useLayoutEffect(() => { + if (mode === "closed") setMaxH(0); + else if (fieldsRef.current) setMaxH(fieldsRef.current.scrollHeight); + }, [mode]); + const toggle = (m) => { + const next = mode === m ? "closed" : m; + setMode(next); + if (next !== "closed" && scrollerRef && scrollerRef.current && rootRef.current) { + const sc = scrollerRef.current; + requestAnimationFrame(() => { + const target = sc.scrollTop + rootRef.current.getBoundingClientRect().top - sc.getBoundingClientRect().top - 20; + sc.scrollTo({ top: Math.max(0, target), behavior: "smooth" }); + }); + } + }; + const tabBtn = (active) => ({ + display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6, padding: "8px 10px", + borderRadius: "var(--radius-sm)", cursor: "pointer", font: "var(--weight-medium) var(--text-xs)/1 var(--font-sans)", + background: active ? "color-mix(in srgb, var(--action-primary) 14%, transparent)" : "var(--ctv-surface-2)", + color: active ? "var(--action-primary)" : "var(--text-secondary)", + border: `1px solid ${active ? "color-mix(in srgb, var(--action-primary) 38%, transparent)" : "var(--border-hairline)"}`, + transition: "background 200ms cubic-bezier(0.16,1,0.3,1), color 200ms cubic-bezier(0.16,1,0.3,1), border-color 200ms cubic-bezier(0.16,1,0.3,1)", + }); + return ( +
+
+ + Advanced + + {count} fields · {templateName} +
+
+ + +
+
+
+
+ + {override ? "Editing these overrides the template for this channel only." : `Read-only — inherited from the ${templateName} template. Turn on Override to edit.`} +
+ {ADV.map((g) => ( +
+
{g.group}
+ {override ? ( +
+ {g.fields.map(([k]) => ( + setVals((s) => ({ ...s, [k]: e.target.value }))} /> + ))} +
+ ) : ( +
+ {g.fields.map(([k, v]) => ( +
+
{k}
+
{v}
+
+ ))} +
+ )} +
+ ))} +
+
+
+ ); + } + + // ---- Main ------------------------------------------------------------------ + function ChannelBuilder() { + const [q, setQ] = React.useState(""); + const [libFilter, setLibFilter] = React.useState("All"); + const [compact, setCompact] = React.useState(false); + const [lineup, setLineup] = React.useState(() => ["s1", "s2", "s3", "s4"].map((id) => LIB.find((x) => x.id === id))); + const [name, setName] = React.useState("Retro Cartoons"); + const [number, setNumber] = React.useState("13.1"); + const [shuffle, setShuffle] = React.useState(false); + const [always, setAlways] = React.useState(true); + const [logoSrc, setLogoSrc] = React.useState(null); + const [tpl, setTpl] = React.useState("std"); + const [tplOpen, setTplOpen] = React.useState(false); + const [source, setSource] = React.useState("library"); // library | collections + + // drag state + const [dragLib, setDragLib] = React.useState(null); // library item id being dragged + const [dragRow, setDragRow] = React.useState(null); // lineup index being dragged + const [overRow, setOverRow] = React.useState(null); + const railScrollerRef = React.useRef(null); + + const addedIds = new Set(lineup.map((i) => i.id)); + const pool = source === "collections" ? COLLECTIONS : LIB; + const filtered = pool.filter((i) => + (source === "collections" || libFilter === "All" || i.library === libFilter) && + (!q || i.title.toLowerCase().includes(q.toLowerCase()))); + + const add = (item) => setLineup((l) => (l.some((x) => x.id === item.id) ? l : [...l, item])); + const removeAt = (idx) => setLineup((l) => l.filter((_, i) => i !== idx)); + const totalMin = lineup.reduce((n, i) => n + i.min, 0); + const template = TEMPLATES.find((t) => t.id === tpl); + const canCreate = name.trim() && lineup.length > 0; + + // reorder / insert on drop at target index + const dropAt = (targetIdx) => { + if (dragRow != null) { + setLineup((l) => { const n = l.slice(); const [m] = n.splice(dragRow, 1); n.splice(targetIdx, 0, m); return n; }); + } else if (dragLib != null) { + const item = [...LIB, ...COLLECTIONS].find((x) => x.id === dragLib); + if (item && !addedIds.has(item.id)) setLineup((l) => { const n = l.slice(); n.splice(targetIdx, 0, item); return n; }); + } + setDragLib(null); setDragRow(null); setOverRow(null); + }; + const dropEnd = () => { + if (dragLib != null) { const item = [...LIB, ...COLLECTIONS].find((x) => x.id === dragLib); if (item) add(item); } + setDragLib(null); setDragRow(null); setOverRow(null); + }; + + return ( +
+ {/* builder toolbar */} +
+ +
+
New Channel
+
Build from your library — {lineup.length} in lineup · {fmtDur(totalMin)}
+
+ + + + +
+ + {/* body — library | lineup | settings */} +
+ {/* LEFT — library browser */} +
+
+
+ + + setCompact(v === "list")} options={[{ value: "grid", icon: "LayoutGrid", title: "Poster grid" }, { value: "list", icon: "Rows3", title: "Compact list" }]} /> +
+ setQ(e.target.value)} leadingIcon={} placeholder={source === "collections" ? "Search collections\u2026" : "Search shows & movies\u2026"} /> + {source === "library" && ( +
+ {LIBRARIES.map((l) => { + const on = libFilter === l; + return ( + + ); + })} +
+ )} +
+ + {filtered.length === 0 ? ( +
No titles match.
+ ) : compact ? ( +
+ {filtered.map((item) => ( + add(item)} + onDragStart={() => setDragLib(item.id)} onDragEnd={dropEnd} /> + ))} +
+ ) : ( +
+ {filtered.map((item) => ( + add(item)} + onDragStart={() => setDragLib(item.id)} onDragEnd={dropEnd} /> + ))} +
+ )} +
+
+ + {/* CENTER — lineup */} +
{ if (dragLib != null) e.preventDefault(); }} + onDrop={() => { if (dragLib != null) dropEnd(); }}> +
+ Lineup + {shuffle ? "Shuffled" : "Sequential"} + + {lineup.length > 0 && } +
+ + {lineup.length === 0 ? ( +
+ +
This channel has no content yet. Double-click or drag titles from the library to build the lineup.
+
+ ) : ( +
+ {lineup.map((item, idx) => ( + removeAt(idx)} + dragProps={{ + draggable: true, + onDragStart: () => setDragRow(idx), + onDragEnd: () => { setDragRow(null); setOverRow(null); }, + onDragOver: (e) => { e.preventDefault(); setOverRow(idx); }, + onDrop: (e) => { e.stopPropagation(); dropAt(idx); }, + }} /> + ))} +
+ Double-click or drag more titles to add +
+
+ )} +
+
+ + {/* RIGHT — friendly options + template + advanced */} + +
+
+ ); + } + + window.CTVChannelBuilder = ChannelBuilder; +})(); diff --git a/design-system/design_handoff_channel_builder/README.md b/design-system/design_handoff_channel_builder/README.md new file mode 100644 index 000000000..bf3988888 --- /dev/null +++ b/design-system/design_handoff_channel_builder/README.md @@ -0,0 +1,163 @@ +# Handoff: ChicoryTV — Channel Builder (+ admin design system) + +## Overview +The **Channel Builder** ("New Channel") is a ground-up replacement for ErsatzTV's four-editor +channel-creation chain (Channel → Schedule → Schedule Items → Playout). It is **one screen**: browse +your media library on the left, build the channel's lineup in the center, set friendly options + +a Channel Template on the right, and hit **Create Channel** — which (in the real app) builds all the +underlying entities atomically. It ships inside the **ChicoryTV admin**, a dark, dense, app-like +console and its React component library. + +## About the design files +The files in this bundle are **design references created in HTML/React** — prototypes showing the +intended look and behavior, **not production code to ship directly**. The task is to **recreate these +designs in the target codebase's environment** using its established patterns. Per the redesign brief, +the intended target is a **React SPA over the ErsatzTV REST API** (replacing Blazor/MudBlazor); if that +app doesn't exist yet, scaffold it (Vite + React + TypeScript is a reasonable default) and implement +there. Nothing here depends on Blazor. + +The prototypes are built on a real design system (React primitives + CSS-custom-property tokens + +three themes) that lives in the parent project — treat that as the component/token source of truth. + +## Fidelity +**High-fidelity.** Final colors, typography, spacing, radii, motion, and interactions are all resolved. +Recreate pixel-for-pixel using the codebase's real component library (promoting these primitives into +it, or mapping to existing equivalents). All values below are exact. + +--- + +## Screens / Views + +### New Channel — Channel Builder (primary deliverable) +**Purpose:** create a working channel by adding library items to a lineup and setting a few friendly +options; technical config comes from a selectable Channel Template. + +**Layout:** full-height column. A **builder toolbar** (fixed, 12px×20px padding, hairline bottom +border): accent icon tile + "New Channel" title + live summary (`N in lineup · total duration`) on the +left; **Cancel** (ghost) and **Create Channel** (primary, right) — Create is disabled until there's a +name + ≥1 lineup item, tooltip below. Below the toolbar, a 3-column grid, full height: +`grid-template-columns: minmax(0,1.2fr) minmax(0,1fr) 304px` (columns shrink, never overflow; the +304px rail is fixed). Each column scrolls independently. + +**Column 1 — Library browser** (`overflow:hidden` section): +- Header: a **Segmented** source toggle **Library / Collections** (sliding highlight), a spacer, and a + grid/compact **density** Segmented. Then a search input (`Search shows & movies…` / + `Search collections…`). Then, in Library mode only, pill **filter chips** (All, Cartoons, Movies, + TV Shows, Music Videos, Documentaries) — active chip uses accent-soft bg + accent text. +- Body (scrolls): **poster grid** `repeat(auto-fill, minmax(104px,1fr))`, gap 10 — each poster is a + 2:3 tinted, diagonally-striped placeholder (deterministic hue from title) with a bottom gradient + scrim, title (12px semibold) + mono meta, and a type icon top-left (Tv/Film/Music/Radio, or + Layers/Sparkles/FolderTree/Repeat for collection kinds). Compact mode is a 30×40 thumb + title + + `type · meta` row. **Double-click or drag** to add; added cards show an accent ring + a **pop-in** + check badge (top-right). + +**Column 2 — Lineup** (the channel's content, `overflow:hidden` section, accepts drops): +- Header: "LINEUP" eyebrow, a **Sequential / Shuffled** status badge (icon, informational — the real + control is the Shuffle toggle in the rail), a spacer, a **Clear** ghost button. +- Body (scrolls): ordered rows, gap 7. Each row: grip handle, order number (mono) when Sequential or a + shuffle glyph when Shuffled, a 34×46 poster thumb, title (14px semibold) + `type · library`, mono + duration, and a remove (×) button. **Drag-to-reorder** (HTML5 DnD; a `0 -2px 0 accent` top-border + marks the drop target; dragged row drops to 0.35 opacity). Empty state = dashed dropzone. A trailing + dashed "double-click or drag more titles to add" hint. + +**Column 3 — Settings rail** (fixed 304px, `background: surface-card`, scrolls via an overlay +scrollbar — hidden native bar so no reflow, subtle fading thumb): +- **Channel name** input; **Number** input with an `AUTO` mono chip trailing. +- **Channel image**: a dashed dropzone (drop or click → file input; live `FileReader` preview). Below, + two preview tiles — **Guide logo** (logo + name + "listing") and **On-screen bug** (logo bottom-right + over a striped "video frame"). A "Set logo & bug separately" disclosure reveals two image buttons. + Default: the one image drives both. +- **Shuffle** toggle (label + "Plays in a random order." / "Plays in sequence (chronological)."). Shows + an "overrides template" tag when it differs from the selected template's default. +- **Always playing** toggle — the live-TV concept. Rendered in the **live color** (`--ctv-live`) with a + tinted row + a "● LIVE" pill when on. Helper: "Like live TV — advances on schedule even when nobody is + watching." Also shows the "overrides template" tag when diverging. *(Backend gap #68 — still needs + confirmation.)* +- **Channel Template** picker: a button showing the current template (name + one-line desc + Custom + badge). Opens a list of built-ins + custom, each with a radio, name, desc; a "Save current settings as + template…" action. Selecting a template **applies its Shuffle + Always-playing defaults** and shows + its config as chips (e.g. `1080p H.264`, `HLS Segmenter`, `Sequential`, `Always on`, `Pre + post filler`). +- **Advanced** disclosure: a **SlidersHorizontal** header + `N fields ·