From b45dcc71900c0e85ac82be9624bfe4d4bbf3e01b Mon Sep 17 00:00:00 2001 From: Timothy Date: Tue, 21 Jul 2026 23:21:10 +0200 Subject: [PATCH] fix(177): map Album/Track in the Jellyfin music video projection Jellyfin-sourced music videos rendered weaker MTV-style credits than local NFO libraries: the Scriban credits templates expose Album/Track, and MusicVideoNfoReader has always mapped both, but the Jellyfin projection never did. ChronologicalMediaComparer orders music videos by the same two fields, so they were also ordering worse. Verified against the live server (1437 MusicVideo items): Album comes back on 111 and IndexNumber on 4, both WITHOUT being named in the `fields` query param -- Album is a plain BaseItemDto property, not an ItemFields value, so no Refit `fields` change is needed (and adding one would be wrong). ParentIndexNumber is deliberately NOT used for Track: on live data, where both are present ParentIndexNumber is 1 while IndexNumber carries the real ordinal, and where only ParentIndexNumber is present it is a collection/disc grouping that tracks the Album ("Glastonbury: 2022" -> 230). The fix is two layers, not one. The projection alone would only ever reach music videos ADDED after it -- UpdateMetadata copies scalars field by field, so an existing item whose album/track is set or corrected in Jellyfin would keep a stale value forever. That is the same class of bug #497 fixed for child collections, one layer up. Also strips a pre-existing UTF-8 BOM from JellyfinLibraryItemResponse.cs, which the format gate flags once the file is touched (format-as-you-touch). fixes #177 --- .../Jellyfin/JellyfinApiClientTests.cs | 81 +++++++++++++++++++ .../Jellyfin/JellyfinApiClient.cs | 6 ++ .../Models/JellyfinLibraryItemResponse.cs | 7 +- .../JellyfinMusicVideoLibraryScanner.cs | 7 ++ .../JellyfinMusicVideoLibraryScannerTests.cs | 79 ++++++++++++++++++ 5 files changed, 179 insertions(+), 1 deletion(-) diff --git a/ErsatzTV.Infrastructure.Tests/Jellyfin/JellyfinApiClientTests.cs b/ErsatzTV.Infrastructure.Tests/Jellyfin/JellyfinApiClientTests.cs index 2dc74150d..9bf3b087d 100644 --- a/ErsatzTV.Infrastructure.Tests/Jellyfin/JellyfinApiClientTests.cs +++ b/ErsatzTV.Infrastructure.Tests/Jellyfin/JellyfinApiClientTests.cs @@ -190,6 +190,87 @@ public class JellyfinApiClientTests } } + // ersatztv#177: Jellyfin-sourced music videos rendered weaker MTV-style credits than local NFO + // libraries because the projection never mapped Album or Track. Verified against the live server + // (1437 MusicVideo items): Album comes back on 111 of them and IndexNumber on 4, both WITHOUT being + // named in the `fields` query param — Album is a plain BaseItemDto property, not an ItemFields value, + // so no Refit `fields` change is needed (and adding one would be wrong). + [TestFixture] + public class GetMusicVideoLibraryItems + { + [Test] + public async Task Should_Project_Album_And_Track() + { + MusicVideoMetadata metadata = await ProjectSingleMusicVideo( + "\"Album\": \"Back in Black\", \"IndexNumber\": 3,"); + + metadata.Album.ShouldBe("Back in Black"); + metadata.Track.ShouldBe(3); + } + + // The overwhelming majority of real items have neither (1326 of 1437 live) — absent must stay + // null rather than becoming "" or 0, so the credits template can omit the line entirely. + [Test] + public async Task Should_Leave_Album_And_Track_Null_When_Absent() + { + MusicVideoMetadata metadata = await ProjectSingleMusicVideo(string.Empty); + + metadata.Album.ShouldBeNull(); + metadata.Track.ShouldBeNull(); + } + + private static async Task ProjectSingleMusicVideo(string albumAndTrackJson) + { + string response = $$""" + { + "Items": [ + { + "Name": "Hells Bells", + "Id": "item-1", + "Path": "/data/music/ACDC/hells-bells.mkv", + "Type": "MusicVideo", + "LocationType": "FileSystem", + "RunTimeTicks": 3120000000, + "DateCreated": "2026-07-01T00:00:00Z", + "Artists": ["AC/DC"], + {{albumAndTrackJson}} + "ProviderIds": {} + } + ], + "TotalRecordCount": 1 + } + """; + + var client = new JellyfinApiClient( + new MemoryCache(new MemoryCacheOptions()), + Substitute.For(), + Substitute.For(), + new SingleResponseHttpClientFactory(response), + Substitute.For>()); + + var library = new JellyfinLibrary + { + Id = 42, + MediaSourceId = 1, + ItemId = "library-1", + + // no PathInfos => the network-path replacement loop (which would need a MediaSource) is skipped + PathInfos = null + }; + + List musicVideos = []; + await foreach ((MusicVideo musicVideo, int _) in client.GetMusicVideoLibraryItems( + "http://jellyfin.example", + "MediaBrowser Token=abc", + library)) + { + musicVideos.Add(musicVideo); + } + + return musicVideos.Single().MusicVideoMetadata.Single(); + } + } + private sealed class SingleResponseHttpClientFactory(string response) : IHttpClientFactory { public HttpClient CreateClient(string name) => new(new SingleResponseHttpMessageHandler(response)); diff --git a/ErsatzTV.Infrastructure/Jellyfin/JellyfinApiClient.cs b/ErsatzTV.Infrastructure/Jellyfin/JellyfinApiClient.cs index 55930f11c..110fa8848 100644 --- a/ErsatzTV.Infrastructure/Jellyfin/JellyfinApiClient.cs +++ b/ErsatzTV.Infrastructure/Jellyfin/JellyfinApiClient.cs @@ -739,6 +739,12 @@ public class JellyfinApiClient : IJellyfinApiClient Plot = item.Overview, Year = item.ProductionYear, DateAdded = dateAdded, + + // ersatztv#177: Album/Track drive the MTV-style credits overlay (Scriban templates expose both) + // and MusicVideo ordering in ChronologicalMediaComparer. Local NFO libraries have always mapped + // them; the Jellyfin projection did not, so Jellyfin-sourced music videos rendered weaker credits. + Album = item.Album, + Track = item.IndexNumber, Genres = Optional(item.Genres).Flatten().Map(g => new Genre { Name = g }).ToList(), Tags = Optional(item.Tags).Flatten().Map(t => new Tag { Name = t }).ToList(), Studios = Optional(item.Studios).Flatten().Map(s => new Studio { Name = s.Name }).ToList(), diff --git a/ErsatzTV.Infrastructure/Jellyfin/Models/JellyfinLibraryItemResponse.cs b/ErsatzTV.Infrastructure/Jellyfin/Models/JellyfinLibraryItemResponse.cs index 7babac1eb..d40d5b16a 100644 --- a/ErsatzTV.Infrastructure/Jellyfin/Models/JellyfinLibraryItemResponse.cs +++ b/ErsatzTV.Infrastructure/Jellyfin/Models/JellyfinLibraryItemResponse.cs @@ -1,4 +1,4 @@ -namespace ErsatzTV.Infrastructure.Jellyfin.Models; +namespace ErsatzTV.Infrastructure.Jellyfin.Models; public class JellyfinLibraryItemResponse { @@ -11,6 +11,11 @@ public class JellyfinLibraryItemResponse public long RunTimeTicks { get; set; } public List Genres { get; set; } public List Artists { get; set; } + + // Music videos only. Jellyfin serializes Album on BaseItemDto whenever it is set; it is NOT an + // ItemFields value, so it must not be added to the `fields` query param (see IJellyfinApi). + public string Album { get; set; } + public List Tags { get; set; } public int ProductionYear { get; set; } public JellyfinProviderIdsResponse ProviderIds { get; set; } diff --git a/ErsatzTV.Scanner/Core/Jellyfin/JellyfinMusicVideoLibraryScanner.cs b/ErsatzTV.Scanner/Core/Jellyfin/JellyfinMusicVideoLibraryScanner.cs index 90c5f5528..743c4e8ce 100644 --- a/ErsatzTV.Scanner/Core/Jellyfin/JellyfinMusicVideoLibraryScanner.cs +++ b/ErsatzTV.Scanner/Core/Jellyfin/JellyfinMusicVideoLibraryScanner.cs @@ -259,6 +259,13 @@ public class JellyfinMusicVideoLibraryScanner : IJellyfinMusicVideoLibraryScanne existing.SortTitle = incoming.SortTitle; existing.Plot = incoming.Plot; existing.Year = incoming.Year; + + // ersatztv#177: Album/Track are scalars, so they must be copied here too — otherwise the + // projection fix only ever reaches music videos ADDED after it, and an existing item whose + // album/track is set (or corrected) in Jellyfin never picks it up. Same shape as the #497 + // collection bug below, one layer up. + existing.Album = incoming.Album; + existing.Track = incoming.Track; existing.ReleaseDate = incoming.ReleaseDate; existing.DateUpdated = DateTime.UtcNow; existing.MetadataKind = MetadataKind.External; diff --git a/ErsatzTV.Tests/Integration/JellyfinMusicVideoLibraryScannerTests.cs b/ErsatzTV.Tests/Integration/JellyfinMusicVideoLibraryScannerTests.cs index d1354f379..8fd8ddebe 100644 --- a/ErsatzTV.Tests/Integration/JellyfinMusicVideoLibraryScannerTests.cs +++ b/ErsatzTV.Tests/Integration/JellyfinMusicVideoLibraryScannerTests.cs @@ -389,6 +389,85 @@ public class JellyfinMusicVideoLibraryScannerTests .AddArtist(Arg.Any(), Arg.Is(a => a.Name == "Artist 1")); } + // ersatztv#177: Album/Track are scalars copied field-by-field in UpdateMetadata, so the projection fix + // alone would only ever reach music videos ADDED after it — an EXISTING item whose album/track is set or + // corrected in Jellyfin would keep its stale value forever. Same shape as the #497 collection bug, one + // layer up. Non-vacuous: reverting the two assignments in UpdateMetadata fails both assertions below. + [Test] + public async Task ScanLibrary_Should_Update_Album_And_Track_On_Rescan_Of_Existing_Item() + { + JellyfinLibrary library = BuildLibrary(1, "/data/music"); + var connectionParameters = new JellyfinConnectionParameters("http://jellyfin", "api-key", 1); + const string VideoPath = "/data/music/artist1/song1.mkv"; + + var existingMetadata = new MusicVideoMetadata + { + Id = 11, + Album = "Stale Album", + Track = 1, + Genres = [], + Tags = [], + Studios = [], + Artists = [new MusicVideoArtist { Name = "Artist 1" }] + }; + + var existing = new MusicVideo + { + Id = 7, + ArtistId = 3, + MediaVersions = + [ + new MediaVersion + { + MediaFiles = [new MediaFile { Path = VideoPath }], + Streams = [] + } + ], + MusicVideoMetadata = [existingMetadata] + }; + + var artistRepository = Substitute.For(); + artistRepository.GetArtistByMetadata(Arg.Any(), Arg.Any()) + .Returns(Some(new Artist { Id = 3, ArtistMetadata = new List() })); + artistRepository.DeleteEmptyArtists(Arg.Any()).Returns(new List()); + + var musicVideoRepository = Substitute.For(); + musicVideoRepository + .GetOrAdd(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Right>( + new MediaItemScanResult(existing) { IsAdded = false })); + musicVideoRepository.FindMusicVideoPaths(Arg.Any()) + .Returns(new List { VideoPath }.AsEnumerable()); + + var metadataRepository = Substitute.For(); + metadataRepository.Update(Arg.Any()).Returns(true); + metadataRepository.UpdateStatistics(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(false); + + var libraryRepository = Substitute.For(); + libraryRepository.GetParentFolderId(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Option.None); + libraryRepository.GetOrAddFolder(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(new LibraryFolder { Id = 5, Path = "/data/music/artist1" }); + + MusicVideo incoming = BuildIncoming(VideoPath, "Artist 1", "Song 1"); + incoming.MusicVideoMetadata[0].Album = "Corrected Album"; + incoming.MusicVideoMetadata[0].Track = 4; + + JellyfinMusicVideoLibraryScanner scanner = BuildScannerWith( + FakeApi(() => incoming), + artistRepository, + musicVideoRepository, + libraryRepository, + metadataRepository); + + (await scanner.ScanLibrary(connectionParameters, library, deepScan: false, CancellationToken.None)) + .IsRight.ShouldBeTrue(); + + existingMetadata.Album.ShouldBe("Corrected Album"); + existingMetadata.Track.ShouldBe(4); + } + private JellyfinMusicVideoLibraryScanner BuildScannerWith( IJellyfinApiClient apiClient, IArtistRepository artistRepository, -- 2.47.3