feat(525): download external-url logo on channel create + create-from-lineup

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-21 13:13:21 +02:00
co-authored by Claude Opus 4.8
parent 1f21f0f30e
commit 93188eeb5e
5 changed files with 218 additions and 6 deletions
@@ -8,6 +8,7 @@ using ErsatzTV.Core.Api.LibraryBrowse;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Images;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
@@ -21,6 +22,7 @@ public class CreateChannelFromLineupHandler(
ChannelWriter<IBackgroundServiceRequest> workerChannel,
IDbContextFactory<TvContext> dbContextFactory,
ISearchTargets searchTargets,
IRemoteLogoCacher remoteLogoCacher,
ILogger<CreateChannelFromLineupHandler> logger)
: IRequestHandler<CreateChannelFromLineup, Either<BaseError, CreateChannelFromLineupResponseModel>>
{
@@ -37,7 +39,42 @@ public class CreateChannelFromLineupHandler(
Either<BaseError, PreparedCreate> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Match(
Left: error => Task.FromResult<Either<BaseError, CreateChannelFromLineupResponseModel>>(error),
Right: prepared => PersistAndDispatch(dbContext, prepared, cancellationToken));
Right: async prepared =>
{
Either<BaseError, PreparedCreate> resolved =
await ResolveExternalLogo(request, prepared, cancellationToken);
return await resolved.Match(
Left: error => Task.FromResult<Either<BaseError, CreateChannelFromLineupResponseModel>>(error),
Right: p => PersistAndDispatch(dbContext, p, cancellationToken));
});
}
// The lineup logo artwork is built (in BuildChannel) with the raw request path. When that path is
// an external http(s) URL, download + cache it and swap the cache name onto the logo artwork before
// persisting (a cacher Left fails the whole create); a blank or already-local/cached path is left
// unchanged. (ersatztv#525)
private async Task<Either<BaseError, PreparedCreate>> ResolveExternalLogo(
CreateChannelFromLineup request,
PreparedCreate prepared,
CancellationToken cancellationToken)
{
string path = request.Logo?.Path ?? string.Empty;
if (!Artwork.IsExternalUrl(path))
{
return prepared;
}
Either<BaseError, string> cached = await remoteLogoCacher.CacheFromUrl(new Uri(path), cancellationToken);
return cached.Map(name =>
{
foreach (Artwork logo in prepared.Channel.Artwork.Where(a => a.ArtworkKind == ArtworkKind.Logo))
{
logo.Path = name;
}
return prepared;
});
}
private async Task<Either<BaseError, CreateChannelFromLineupResponseModel>> PersistAndDispatch(
@@ -1,9 +1,10 @@
using System.Globalization;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Interfaces.Images;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -16,7 +17,8 @@ namespace ErsatzTV.Application.Channels;
public class CreateChannelHandler(
ChannelWriter<IBackgroundServiceRequest> workerChannel,
IDbContextFactory<TvContext> dbContextFactory,
ISearchTargets searchTargets)
ISearchTargets searchTargets,
IRemoteLogoCacher remoteLogoCacher)
: IRequestHandler<CreateChannel, Either<BaseError, CreateChannelResult>>
{
public async Task<Either<BaseError, CreateChannelResult>> Handle(
@@ -25,7 +27,52 @@ public class CreateChannelHandler(
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Channel> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(c => PersistChannel(dbContext, c));
return await validation.Match(
Succ: async channel =>
{
Either<BaseError, string> resolvedLogo = await ResolveLogoPath(request, cancellationToken);
return await resolvedLogo.Match(
Right: async logoPath =>
{
ApplyResolvedLogo(request, channel, logoPath);
return Right<BaseError, CreateChannelResult>(await PersistChannel(dbContext, channel));
},
Left: e => Task.FromResult(Left<BaseError, CreateChannelResult>(e)));
},
Fail: errors => Task.FromResult(Left<BaseError, CreateChannelResult>(errors.Head)));
}
// Resolve the incoming logo path into a value safe to persist. An external http(s) URL is
// downloaded and cached (a cacher Left fails the whole save); an empty path or an
// already-local/cached path passes through unchanged. (ersatztv#525)
private async Task<Either<BaseError, string>> ResolveLogoPath(
CreateChannel request,
CancellationToken cancellationToken)
{
string path = request.Logo?.Path ?? string.Empty;
if (!Artwork.IsExternalUrl(path))
{
return path;
}
Either<BaseError, string> cached = await remoteLogoCacher.CacheFromUrl(new Uri(path), cancellationToken);
return cached;
}
// When the incoming logo was an external URL, swap the downloaded cache name onto the logo
// artwork built during validation so no URL is ever persisted in Artwork.Path. (ersatztv#525)
private static void ApplyResolvedLogo(CreateChannel request, Channel channel, string resolvedLogoPath)
{
if (!Artwork.IsExternalUrl(request.Logo?.Path ?? string.Empty))
{
return;
}
foreach (Artwork logo in channel.Artwork.Where(a => a.ArtworkKind == ArtworkKind.Logo))
{
logo.Path = resolvedLogoPath;
}
}
private async Task<CreateChannelResult> PersistChannel(TvContext dbContext, Channel channel)
@@ -9,6 +9,7 @@ using ErsatzTV.Core.Api.LibraryBrowse;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Images;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
@@ -19,6 +20,7 @@ using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using DomainChannel = ErsatzTV.Core.Domain.Channel;
using DomainPlaylistItem = ErsatzTV.Core.Domain.PlaylistItem;
@@ -30,6 +32,7 @@ public class CreateChannelFromLineupHandlerTests
private Channel<IBackgroundServiceRequest> _background = null!;
private InMemoryTvContext _db = null!;
private ISearchTargets _searchTargets = null!;
private IRemoteLogoCacher _remoteLogoCacher = null!;
[SetUp]
public async Task SetUp()
@@ -37,6 +40,7 @@ public class CreateChannelFromLineupHandlerTests
_background = System.Threading.Channels.Channel.CreateUnbounded<IBackgroundServiceRequest>();
_db = await InMemoryTvContext.CreateAsync();
_searchTargets = Substitute.For<ISearchTargets>();
_remoteLogoCacher = Substitute.For<IRemoteLogoCacher>();
}
[TearDown]
@@ -610,6 +614,71 @@ public class CreateChannelFromLineupHandlerTests
LeftOf(result).Value.ShouldContain("External logo url is invalid");
}
[Test]
public async Task Should_Download_External_Url_Logo_And_Store_Cache_Name()
{
await SeedTemplateDependencies();
await SeedTemplate();
await SeedMovie(42);
_remoteLogoCacher.CacheFromUrl(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, string>("cachedhash"));
var logo = new ArtworkContentTypeModel("https://example.com/logo.png", string.Empty);
Either<BaseError, CreateChannelFromLineupResponseModel> result =
await MakeHandler().Handle(MakeRequest(logo: logo), CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext context = _db.CreateContext();
Artwork artwork = (await context.Channels.Include(c => c.Artwork).SingleAsync())
.Artwork.Single(a => a.ArtworkKind == ArtworkKind.Logo);
artwork.Path.ShouldBe("cachedhash");
artwork.IsExternalUrl().ShouldBeFalse();
}
[Test]
public async Task Should_Fail_The_Create_When_The_Logo_Download_Fails()
{
await SeedTemplateDependencies();
await SeedTemplate();
await SeedMovie(42);
_remoteLogoCacher.CacheFromUrl(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, string>(BaseError.New("Could not download logo: host timed out")));
var logo = new ArtworkContentTypeModel("https://example.com/logo.png", string.Empty);
Either<BaseError, CreateChannelFromLineupResponseModel> result =
await MakeHandler().Handle(MakeRequest(logo: logo), CancellationToken.None);
LeftOf(result).Value.ShouldContain("Could not download logo");
// nothing is persisted when the download fails (resolution runs before PersistAndDispatch)
await using TvContext context = _db.CreateContext();
(await context.Channels.CountAsync()).ShouldBe(0);
(await context.Playouts.CountAsync()).ShouldBe(0);
}
[Test]
public async Task Should_Not_Call_The_Cacher_For_An_Uploaded_Logo_Path()
{
await SeedTemplateDependencies();
await SeedTemplate();
await SeedMovie(42);
var logo = new ArtworkContentTypeModel("iptv/logos/deadbeef", string.Empty);
Either<BaseError, CreateChannelFromLineupResponseModel> result =
await MakeHandler().Handle(MakeRequest(logo: logo), CancellationToken.None);
result.IsRight.ShouldBeTrue();
await _remoteLogoCacher.DidNotReceive().CacheFromUrl(Arg.Any<Uri>(), Arg.Any<CancellationToken>());
await using TvContext context = _db.CreateContext();
Artwork artwork = (await context.Channels.Include(c => c.Artwork).SingleAsync())
.Artwork.Single(a => a.ArtworkKind == ArtworkKind.Logo);
artwork.Path.ShouldBe("deadbeef");
}
[Test]
public async Task Should_Return_NotFound_When_Lineup_Target_Is_Missing()
{
@@ -638,6 +707,7 @@ public class CreateChannelFromLineupHandlerTests
_background.Writer,
_db.Factory,
_searchTargets,
_remoteLogoCacher,
NullLogger<CreateChannelFromLineupHandler>.Instance);
private async Task SeedTemplateDependencies()
@@ -1,19 +1,22 @@
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using LanguageExt;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
namespace ErsatzTV.Tests.Application.Channels;
[TestFixture]
public class CreateChannelHandlerTests : ChannelHandlerTestBase
{
private CreateChannelHandler MakeHandler() => new(Worker, Db.Factory, SearchTargets);
private CreateChannelHandler MakeHandler() => new(Worker, Db.Factory, SearchTargets, RemoteLogoCacher);
[Test]
public async Task Should_Create_Channel_When_Valid()
@@ -99,6 +102,61 @@ public class CreateChannelHandlerTests : ChannelHandlerTestBase
error.Value.ShouldContain("FFmpegProfile");
}
[Test]
public async Task Should_Download_External_Url_Logo_And_Store_Cache_Name()
{
await SeedFFmpegProfile();
RemoteLogoCacher.CacheFromUrl(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, string>("cachedhash"));
Either<BaseError, CreateChannelResult> result = await MakeHandler().Handle(
MakeCreate(number: "20", logoPath: "https://example.com/logo.png"),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext db = Db.CreateContext();
Artwork logo = db.Channels.Include(c => c.Artwork).Single(c => c.Number == "20")
.Artwork.Single(a => a.ArtworkKind == ArtworkKind.Logo);
logo.Path.ShouldBe("cachedhash");
logo.IsExternalUrl().ShouldBeFalse();
}
[Test]
public async Task Should_Fail_The_Create_When_The_Logo_Download_Fails()
{
await SeedFFmpegProfile();
RemoteLogoCacher.CacheFromUrl(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, string>(BaseError.New("Could not download logo: host timed out")));
Either<BaseError, CreateChannelResult> result = await MakeHandler().Handle(
MakeCreate(number: "21", logoPath: "https://example.com/logo.png"),
CancellationToken.None);
result.IsLeft.ShouldBeTrue();
LeftOf(result).Value.ShouldContain("Could not download logo");
await using TvContext db = Db.CreateContext();
(await db.Channels.AnyAsync(c => c.Number == "21")).ShouldBeFalse();
}
[Test]
public async Task Should_Not_Call_The_Cacher_For_An_Uploaded_Logo_Path()
{
await SeedFFmpegProfile();
Either<BaseError, CreateChannelResult> result = await MakeHandler().Handle(
MakeCreate(number: "22", logoPath: "iptv/logos/deadbeef"),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
await RemoteLogoCacher.DidNotReceive().CacheFromUrl(Arg.Any<Uri>(), Arg.Any<CancellationToken>());
await using TvContext db = Db.CreateContext();
Artwork logo = db.Channels.Include(c => c.Artwork).Single(c => c.Number == "22")
.Artwork.Single(a => a.ArtworkKind == ArtworkKind.Logo);
logo.Path.ShouldBe("deadbeef");
}
private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
}
@@ -21,7 +21,7 @@ public class ChannelLifecycleIntegrationTests : ChannelHandlerTestBase
{
await SeedFFmpegProfile();
var createHandler = new CreateChannelHandler(Worker, Db.Factory, SearchTargets);
var createHandler = new CreateChannelHandler(Worker, Db.Factory, SearchTargets, RemoteLogoCacher);
Either<BaseError, CreateChannelResult> created =
await createHandler.Handle(MakeCreate(number: "42", name: "Integration"), CancellationToken.None);