fix(177): map Album/Track in the Jellyfin music video projection #555

Merged
timothy merged 1 commits from issue-177-jellyfin-mv-album-track into main 2026-07-21 23:50:19 +02:00
5 changed files with 179 additions and 1 deletions
@@ -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<MusicVideoMetadata> 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<IJellyfinPathReplacementService>(),
Substitute.For<IFallbackMetadataProvider>(),
new SingleResponseHttpClientFactory(response),
Substitute.For<ILogger<JellyfinApiClient>>());
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<MusicVideo> 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));
@@ -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(),
@@ -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<string> Genres { get; set; }
public List<string> 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<string> Tags { get; set; }
public int ProductionYear { get; set; }
public JellyfinProviderIdsResponse ProviderIds { get; set; }
@@ -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;
@@ -389,6 +389,85 @@ public class JellyfinMusicVideoLibraryScannerTests
.AddArtist(Arg.Any<MusicVideoMetadata>(), Arg.Is<MusicVideoArtist>(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<IArtistRepository>();
artistRepository.GetArtistByMetadata(Arg.Any<int>(), Arg.Any<ArtistMetadata>())
.Returns(Some(new Artist { Id = 3, ArtistMetadata = new List<ArtistMetadata>() }));
artistRepository.DeleteEmptyArtists(Arg.Any<LibraryPath>()).Returns(new List<int>());
var musicVideoRepository = Substitute.For<IMusicVideoRepository>();
musicVideoRepository
.GetOrAdd(Arg.Any<Artist>(), Arg.Any<LibraryPath>(), Arg.Any<LibraryFolder>(), Arg.Any<string>())
.Returns(Right<BaseError, MediaItemScanResult<MusicVideo>>(
new MediaItemScanResult<MusicVideo>(existing) { IsAdded = false }));
musicVideoRepository.FindMusicVideoPaths(Arg.Any<LibraryPath>())
.Returns(new List<string> { VideoPath }.AsEnumerable());
var metadataRepository = Substitute.For<IMetadataRepository>();
metadataRepository.Update(Arg.Any<ErsatzTV.Core.Domain.Metadata>()).Returns(true);
metadataRepository.UpdateStatistics(Arg.Any<MediaItem>(), Arg.Any<MediaVersion>(), Arg.Any<bool>())
.Returns(false);
var libraryRepository = Substitute.For<ILibraryRepository>();
libraryRepository.GetParentFolderId(Arg.Any<LibraryPath>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Option<int>.None);
libraryRepository.GetOrAddFolder(Arg.Any<LibraryPath>(), Arg.Any<Option<int>>(), Arg.Any<string>())
.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,