Captures the audio container of the music tracks

Adds a Container to the audio metadata, captured with TagLibSharp from the concrete type of the parsed file during the music library scan and stored on the track through a new column and an EF migration. The container is refreshed when a file changes, survives track and artist edits and provider enrichment, and is exposed read-only in the track responses, never settable through a request.

Extracts the container resolution into a testable resolver used by the scan pipeline and the ID3 plugin, refuses to read a file that is itself a reparse point during extraction, and updates the endpoint summaries, the API and domain documentation, and the tests.
This commit is contained in:
BinaryAlley committed 2026-10-14 13:40:28 +03:00
1 parent 4ffa81fffe
commit f29f89f31f
60 files changed
+4483 -68

No files matched your search

@@ -376,6 +376,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -454,6 +455,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -639,6 +641,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -717,6 +720,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -941,6 +945,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -1019,6 +1024,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -1283,6 +1289,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -1361,6 +1368,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -1511,6 +1519,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -518,6 +518,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -596,6 +597,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -865,6 +867,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1&
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -943,6 +946,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1&
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -1252,6 +1256,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -1330,6 +1335,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -1916,6 +1922,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -1994,6 +2001,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"container": "FLAC",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
@@ -129,6 +129,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -231,6 +232,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -452,6 +454,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"container": "FLAC",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
@@ -286,6 +286,7 @@ class Track
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"container": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
@@ -216,6 +216,11 @@ internal sealed class Id3TagDto
/// </summary>
public string? AudioCodec { get; init; }
/// <summary>
/// Gets or initializes the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV.
/// </summary>
public string? Container { get; init; }
/// <summary>
/// Gets or initializes the official website associated with the artist.
/// </summary>
@@ -164,6 +164,7 @@ internal static class Id3TagMapper
Channels: data.Channels,
BitDepth: data.BitDepth,
AudioCodec: NullIfWhiteSpace(data.AudioCodec),
Container: NullIfWhiteSpace(data.Container),
Bitrate: data.Bitrate,
MusicBrainzRecordingId: ParseGuid(data.MusicBrainzRecordingId),
MusicBrainzTrackId: ParseGuid(data.MusicBrainzReleaseTrackId),
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Plugins.ID3.Core.Tags;
/// <summary>
/// Resolves the canonical name of the container of an audio file from the concrete type the tagging library parsed it as.
/// </summary>
internal static class AudioContainerResolver
{
/// <summary>
/// Resolves the container of the audio file parsed by <paramref name="tagFile"/>.
/// </summary>
/// <param name="tagFile">The parsed audio file whose container is resolved.</param>
/// <returns>The canonical name of the container, for example MP3, FLAC, OGG, AAC, MP4 or WAV, or <see langword="null"/> when the container cannot be recognized.</returns>
public static string? Resolve(TagLib.File tagFile)
{
// The concrete type of the parsed file is the most reliable description of its container, because it is chosen by the parser from the
// actual bytes of the file, while the mime type only describes the extension. The scanning pipeline resolves the container the same way,
// so that the container captured during a scan and the one captured during metadata enrichment always agree.
return tagFile switch
{
TagLib.Mpeg.File => "MP3",
TagLib.Flac.File => "FLAC",
TagLib.Mpeg4.File => "MP4",
TagLib.Aac.File => "AAC",
TagLib.Ogg.File => "OGG",
TagLib.Riff.File => "WAV",
TagLib.Aiff.File => "AIFF",
TagLib.Ape.File => "APE",
TagLib.WavPack.File => "WAVPACK",
TagLib.Asf.File => "WMA",
TagLib.Dsf.File => "DSF",
TagLib.Matroska.File => "MATROSKA",
TagLib.MusePack.File => "MPC",
TagLib.Audible.File => "AA",
_ => ResolveFromMimeType(tagFile.MimeType)
};
}
/// <summary>
/// Resolves the container from the mime type reported by the tagging library, for the containers that have no dedicated parser.
/// </summary>
/// <param name="mimeType">The mime type reported by the tagging library.</param>
/// <returns>The name of the container, or <see langword="null"/> when it cannot be derived.</returns>
public static string? ResolveFromMimeType(string? mimeType)
{
if (string.IsNullOrWhiteSpace(mimeType))
return null;
// The library reports its mime types with the "taglib/" prefix, so only the last segment names the container.
string[] segments = mimeType.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
string? container = segments.Length > 0 ? segments[^1] : null;
return string.IsNullOrWhiteSpace(container) ? null : container.ToUpperInvariant();
}
}
@@ -166,6 +166,7 @@ internal sealed class Id3TagReader
BitDepth = audioProperties.BitsPerSample > 0 ? audioProperties.BitsPerSample : null,
Bitrate = audioProperties.AudioBitrate > 0 ? audioProperties.AudioBitrate : null,
AudioCodec = NullIfWhiteSpace(audioProperties.Description),
Container = AudioContainerResolver.Resolve(tagFile),
Website = NullIfWhiteSpace(GetExtendedField(extendedFields, "WOAR", "website")),
MusicBrainzArtistId = NullIfWhiteSpace(tag.MusicBrainzArtistId),
MusicBrainzReleaseArtistId = NullIfWhiteSpace(tag.MusicBrainzReleaseArtistId),
@@ -183,6 +183,7 @@ internal static partial class MusicBrainzMapper
Channels: null,
BitDepth: null,
AudioCodec: null,
Container: null,
Bitrate: null,
MusicBrainzRecordingId: ParseGuid(recording.Id),
MusicBrainzTrackId: null,
@@ -94,6 +94,11 @@ public class MusicLibraryScanItemMetadataEntity : IStorageEntity
/// </summary>
public string? AudioCodec { get; set; }
/// <summary>
/// Gets or sets the container of the audio file, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.
/// </summary>
public string? Container { get; set; }
/// <summary>
/// Gets or sets the bitrate of the audio in kbps, if applicable.
/// </summary>
@@ -141,6 +141,11 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? AudioCodec { get; set; }
/// <summary>
/// Gets or sets the container of the audio file, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.
/// </summary>
public string? Container { get; set; }
/// <summary>
/// Gets or sets the bitrate of the audio in kbps, if applicable.
/// </summary>
@@ -202,6 +202,9 @@ public static class AudioMetadataDtoMapping
Optional<string> audioCodec = Optional<string>.FromNullable(dto.AudioCodec);
if (!audioCodec.HasValue)
audioCodec = track.Metadata.AudioCodec;
// The container is captured from the file itself: a provider that re-reads the file supplies it, and when it is absent the track keeps the stored
// container, which the domain enforces when the metadata is applied. The preserve rule therefore lives in one place, the domain update.
Optional<string> container = Optional<string>.FromNullable(dto.Container);
Optional<int> bitrate = Optional<int>.FromNullable(dto.Bitrate);
if (!bitrate.HasValue)
bitrate = track.Metadata.Bitrate;
@@ -220,6 +223,7 @@ public static class AudioMetadataDtoMapping
originalLanguage,
bitDepth,
audioCodec,
container,
bitrate,
track.Metadata.AcoustId,
track.Metadata.ReplayGainTrackGain,
@@ -63,6 +63,7 @@ public static class MusicTrackMetadataDtoMapping
if (dto.OriginalLanguage is not null && dto.OriginalLanguage.LanguageCode is not null && dto.OriginalLanguage.LanguageName is not null)
originalLanguage = LanguageInfo.Create(dto.OriginalLanguage.LanguageCode, dto.OriginalLanguage.LanguageName, Optional<string>.FromNullable(dto.OriginalLanguage.NativeName));
// The container is captured from the file itself and is never settable through a request; on an edit the track keeps the container it already has.
return AudioMetadata.Create(
dto.Title!,
Optional<string>.FromNullable(dto.OriginalTitle),
@@ -77,6 +78,7 @@ public static class MusicTrackMetadataDtoMapping
originalLanguage,
Optional<int>.FromNullable(dto.BitDepth),
Optional<string>.FromNullable(dto.AudioCodec),
Optional<string>.None(),
Optional<int>.FromNullable(dto.Bitrate),
Optional<string>.FromNullable(dto.AcoustId),
Optional<decimal>.FromNullable(dto.ReplayGainTrackGain),
@@ -84,6 +84,7 @@ public static class TrackEntityMapping
originalLanguage,
Optional<int>.FromNullable(repositoryEntity.BitDepth),
Optional<string>.FromNullable(repositoryEntity.AudioCodec),
Optional<string>.FromNullable(repositoryEntity.Container),
Optional<int>.FromNullable(repositoryEntity.Bitrate),
Optional<string>.FromNullable(repositoryEntity.AcoustId),
Optional<decimal>.FromNullable(repositoryEntity.ReplayGainTrackGain),
@@ -259,7 +260,8 @@ public static class TrackEntityMapping
[.. repositoryEntity.Moods.ToResponses()],
[.. repositoryEntity.Isrcs.ToResponses()],
[.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))],
[.. repositoryEntity.Ratings.ToResponses()]);
[.. repositoryEntity.Ratings.ToResponses()],
repositoryEntity.Container);
}
/// <summary>
@@ -52,6 +52,7 @@ public static class TrackMapping
Channels = domainEntity.Metadata.Channels,
BitDepth = domainEntity.Metadata.BitDepth.HasValue ? domainEntity.Metadata.BitDepth.Value : null,
AudioCodec = domainEntity.Metadata.AudioCodec.HasValue ? domainEntity.Metadata.AudioCodec.Value : null,
Container = domainEntity.Metadata.Container.HasValue ? domainEntity.Metadata.Container.Value : null,
Bitrate = domainEntity.Metadata.Bitrate.HasValue ? domainEntity.Metadata.Bitrate.Value : null,
AcoustId = domainEntity.Metadata.AcoustId.HasValue ? domainEntity.Metadata.AcoustId.Value : null,
ReplayGainTrackGain = domainEntity.Metadata.ReplayGainTrackGain.HasValue ? domainEntity.Metadata.ReplayGainTrackGain.Value : null,
@@ -34,6 +34,7 @@ namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
/// <param name="Channels">The number of audio channels of the track. Required.</param>
/// <param name="BitDepth">The bit depth of the audio of the track. Optional.</param>
/// <param name="AudioCodec">The audio codec used by the track. Optional.</param>
/// <param name="Container">The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional.</param>
/// <param name="Bitrate">The bitrate of the audio of the track in kbps. Optional.</param>
/// <param name="MusicBrainzRecordingId">The MusicBrainz identifier of the recording. Optional.</param>
/// <param name="MusicBrainzTrackId">The MusicBrainz identifier of the track. Optional.</param>
@@ -62,6 +63,7 @@ public sealed record AudioMetadataDto(
int? Channels,
int? BitDepth,
string? AudioCodec,
string? Container,
int? Bitrate,
Guid? MusicBrainzRecordingId,
Guid? MusicBrainzTrackId,
@@ -33,6 +33,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Trac
/// <param name="Isrcs">The list of ISRC (International Standard Recording Code) of the track.</param>
/// <param name="Contributors">The list of references to the media contributors that performed on the track, each with the role they played.</param>
/// <param name="Ratings">The list of ratings for this track.</param>
/// <param name="Container">The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, captured from the file itself. Read only, and not settable through a request. Optional.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record TrackResponse(
Guid Id,
@@ -53,5 +54,6 @@ public record TrackResponse(
List<MoodDto>? Moods,
List<IsrcDto>? Isrcs,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings
List<AudioRatingDto>? Ratings,
string? Container = null
);
@@ -98,6 +98,9 @@ public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguratio
.HasColumnOrder(29);
builder.PrimitiveCollection(musicMetadata => musicMetadata.Moods)
.HasColumnOrder(30);
builder.Property(musicMetadata => musicMetadata.Container)
.HasMaxLength(50)
.HasColumnOrder(31);
builder.HasIndex(musicMetadata => new { musicMetadata.LibraryScanId, musicMetadata.Path })
.IsUnique(); // the metadata of the same physical file cannot be staged twice during the same scan
@@ -152,6 +152,9 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
builder.Property(track => track.ReplayGainAlbumPeak)
.HasColumnType("decimal(8,6)")
.HasColumnOrder(48);
builder.Property(track => track.Container)
.HasMaxLength(50)
.HasColumnOrder(49);
builder.HasOne(track => track.Album)
.WithMany(album => album.Tracks)
@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsAudioContainerToMusicMetadata : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Container",
table: "Tracks",
type: "TEXT",
maxLength: 50,
nullable: true)
.Annotation("Relational:ColumnOrder", 49);
migrationBuilder.AddColumn<string>(
name: "Container",
table: "MusicLibraryScanItemMetadata",
type: "TEXT",
maxLength: 50,
nullable: true)
.Annotation("Relational:ColumnOrder", 31);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Container",
table: "Tracks");
migrationBuilder.DropColumn(
name: "Container",
table: "MusicLibraryScanItemMetadata");
}
}
}
@@ -844,6 +844,11 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("INTEGER")
.HasColumnOrder(13);
b.Property<string>("Container")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(31);
b.Property<int?>("DiscNumber")
.HasColumnType("INTEGER")
.HasColumnOrder(10);
@@ -1037,6 +1042,11 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("INTEGER")
.HasColumnOrder(22);
b.Property<string>("Container")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(49);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(38);
@@ -38,6 +38,11 @@ public class AudioMetadata : BaseMetadata
/// </summary>
public Optional<string> AudioCodec { get; }
/// <summary>
/// Gets the container of the audio, as read from the file itself, for example MP3, FLAC, OGG, AAC, MP4 or WAV.
/// </summary>
public Optional<string> Container { get; }
/// <summary>
/// Gets the bitrate of the audio in kbps.
/// </summary>
@@ -82,6 +87,7 @@ public class AudioMetadata : BaseMetadata
/// <param name="originalLanguage">The optional original language of the audio.</param>
/// <param name="bitDepth">The bit depth of the audio.</param>
/// <param name="audioCodec">The audio codec used.</param>
/// <param name="container">The container of the audio.</param>
/// <param name="genres">The genres of the audio.</param>
/// <param name="tags">The tags associated with the audio.</param>
/// <param name="bitrate">The bitrate of the audio in kbps.</param>
@@ -104,6 +110,7 @@ public class AudioMetadata : BaseMetadata
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
Optional<string> container,
Optional<int> bitrate,
Optional<string> acoustId,
Optional<decimal> replayGainTrackGain,
@@ -117,6 +124,7 @@ public class AudioMetadata : BaseMetadata
Channels = channels;
BitDepth = bitDepth;
AudioCodec = audioCodec;
Container = container;
Bitrate = bitrate;
AcoustId = acoustId;
ReplayGainTrackGain = replayGainTrackGain;
@@ -139,6 +147,7 @@ public class AudioMetadata : BaseMetadata
/// <param name="originalLanguage">The optional original language of the audio.</param>
/// <param name="bitDepth">The bit depth of the audio.</param>
/// <param name="audioCodec">The audio codec used.</param>
/// <param name="container">The container of the audio.</param>
/// <param name="genres">The genres of the audio.</param>
/// <param name="tags">The tags associated with the audio.</param>
/// <param name="bitrate">The bitrate of the audio in kbps.</param>
@@ -164,6 +173,7 @@ public class AudioMetadata : BaseMetadata
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
Optional<string> container,
Optional<int> bitrate,
Optional<string> acoustId,
Optional<decimal> replayGainTrackGain,
@@ -185,6 +195,7 @@ public class AudioMetadata : BaseMetadata
originalLanguage,
bitDepth,
audioCodec,
container,
bitrate,
acoustId,
replayGainTrackGain,
@@ -193,6 +204,38 @@ public class AudioMetadata : BaseMetadata
replayGainAlbumPeak);
}
/// <summary>
/// Creates a copy of this audio metadata with the provided <paramref name="container"/>, keeping every other property unchanged.
/// </summary>
/// <param name="container">The container of the audio.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a copy of this audio metadata with the provided container, or an error message.
/// </returns>
internal Result<AudioMetadata> WithContainer(Optional<string> container)
{
return Create(
Title,
OriginalTitle,
DurationInSeconds,
SampleRate,
Channels,
ReleaseInfo,
Description,
[.. Genres],
[.. Tags],
Language,
OriginalLanguage,
BitDepth,
AudioCodec,
container,
Bitrate,
AcoustId,
ReplayGainTrackGain,
ReplayGainTrackPeak,
ReplayGainAlbumGain,
ReplayGainAlbumPeak);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
@@ -206,6 +249,7 @@ public class AudioMetadata : BaseMetadata
yield return Channels;
yield return BitDepth;
yield return AudioCodec;
yield return Container;
yield return Bitrate;
yield return AcoustId;
yield return ReplayGainTrackGain;
@@ -347,7 +347,8 @@ public sealed class Track : Entity<TrackId>
/// </summary>
/// <remarks>
/// The file system path is intentionally not editable here: it is set only when the track is created by the scanner, so that a client
/// can never point an existing track at an arbitrary file of the host.
/// can never point an existing track at an arbitrary file of the host. The container is captured from the file itself and is not part of
/// an edit either, so an update that does not carry one keeps the container already stored for the track.
/// </remarks>
/// <param name="metadata">The audio metadata of the track.</param>
/// <param name="disambiguation">The optional disambiguation comment of the track.</param>
@@ -374,7 +375,16 @@ public sealed class Track : Entity<TrackId>
Optional<MusicBrainzId> musicBrainzRecordingId,
Optional<MusicBrainzId> musicBrainzTrackId)
{
Metadata = metadata;
// The container is captured from the file itself and is never part of an edit, so an update that does not carry one keeps the stored container.
if (metadata.Container.HasValue)
Metadata = metadata;
else
{
Result<AudioMetadata> metadataWithStoredContainerResult = metadata.WithContainer(Metadata.Container);
if (metadataWithStoredContainerResult.IsFailure)
return metadataWithStoredContainerResult.Errors;
Metadata = metadataWithStoredContainerResult.Value;
}
Disambiguation = disambiguation;
TrackNumber = trackNumber;
DiscNumber = discNumber;
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
/// <summary>
/// Resolves the canonical name of the container of an audio file from the concrete type the tagging library parsed it as.
/// </summary>
internal static class AudioContainerResolver
{
/// <summary>
/// Resolves the container of the audio file parsed by <paramref name="tagFile"/>.
/// </summary>
/// <param name="tagFile">The parsed audio file whose container is resolved.</param>
/// <returns>The canonical name of the container, for example MP3, FLAC, OGG, AAC, MP4 or WAV, or <see langword="null"/> when the container cannot be recognized.</returns>
public static string? Resolve(TagLib.File tagFile)
{
// The concrete type of the parsed file is the most reliable description of its container, because it is chosen by the parser from the
// actual bytes of the file, while the mime type only describes the extension. Containers that share a parser (for example the Opus and
// Vorbis streams parsed by the Ogg parser) are reported under the name of their container, and the codec column carries the difference.
return tagFile switch
{
TagLib.Mpeg.File => "MP3",
TagLib.Flac.File => "FLAC",
TagLib.Mpeg4.File => "MP4",
TagLib.Aac.File => "AAC",
TagLib.Ogg.File => "OGG",
TagLib.Riff.File => "WAV",
TagLib.Aiff.File => "AIFF",
TagLib.Ape.File => "APE",
TagLib.WavPack.File => "WAVPACK",
TagLib.Asf.File => "WMA",
TagLib.Dsf.File => "DSF",
TagLib.Matroska.File => "MATROSKA",
TagLib.MusePack.File => "MPC",
TagLib.Audible.File => "AA",
_ => ResolveFromMimeType(tagFile.MimeType)
};
}
/// <summary>
/// Resolves the container from the mime type reported by the tagging library, for the containers that have no dedicated parser.
/// </summary>
/// <param name="mimeType">The mime type reported by the tagging library.</param>
/// <returns>The name of the container, or <see langword="null"/> when it cannot be derived.</returns>
public static string? ResolveFromMimeType(string? mimeType)
{
if (string.IsNullOrWhiteSpace(mimeType))
return null;
// The library reports its mime types with the "taglib/" prefix, so only the last segment names the container.
string[] segments = mimeType.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
string? container = segments.Length > 0 ? segments[^1] : null;
return string.IsNullOrWhiteSpace(container) ? null : container.ToUpperInvariant();
}
}
@@ -111,6 +111,7 @@ internal static class MusicMetadataAggregator
First(first.Channels, second.Channels),
First(first.BitDepth, second.BitDepth),
First(first.AudioCodec, second.AudioCodec),
First(first.Container, second.Container),
First(first.Bitrate, second.Bitrate),
First(first.MusicBrainzRecordingId, second.MusicBrainzRecordingId),
First(first.MusicBrainzTrackId, second.MusicBrainzTrackId),
@@ -306,6 +306,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
Channels = stagedItem.Channels,
BitDepth = stagedItem.BitDepth,
AudioCodec = stagedItem.AudioCodec,
Container = stagedItem.Container,
Bitrate = stagedItem.Bitrate,
AcoustId = stagedItem.AcoustId,
ReplayGainTrackGain = stagedItem.ReplayGainTrackGain,
@@ -17,6 +17,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -232,6 +233,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
int channels = 0;
int? bitDepth = null;
string? audioCodec = null;
string? container = null;
int? bitrate = null;
string? acoustId = null;
decimal? replayGainTrackGain = null;
@@ -242,64 +244,71 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
try
{
using (TagLib.File tagFile = TagLib.File.Create(path))
// A file that is itself a link is not read, so its target outside the content locations is never opened. A linked directory is a separate
// discovery level concern, so this is a defense in depth for the leaf file rather than a complete containment guarantee.
if (!IsReparsePoint(path))
{
TagLib.Tag tag = tagFile.Tag;
if (!string.IsNullOrWhiteSpace(tag.Title))
trackTitle = tag.Title;
if (!string.IsNullOrWhiteSpace(tag.Album))
releaseName = tag.Album;
// The album artist is preferred over the track artist, because it is the artist the release belongs to.
string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer;
if (!string.IsNullOrWhiteSpace(tagArtist))
artistName = tagArtist;
if (tag.Track > 0)
trackNumber = (int)tag.Track;
if (tag.Disc > 0)
discNumber = (int)tag.Disc;
if (tag.Year > 0)
releaseYear = (int)tag.Year;
using (TagLib.File tagFile = TagLib.File.Create(path))
{
TagLib.Tag tag = tagFile.Tag;
if (!string.IsNullOrWhiteSpace(tag.Title))
trackTitle = tag.Title;
if (!string.IsNullOrWhiteSpace(tag.Album))
releaseName = tag.Album;
// The album artist is preferred over the track artist, because it is the artist the release belongs to.
string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer;
if (!string.IsNullOrWhiteSpace(tagArtist))
artistName = tagArtist;
if (tag.Track > 0)
trackNumber = (int)tag.Track;
if (tag.Disc > 0)
discNumber = (int)tag.Disc;
if (tag.Year > 0)
releaseYear = (int)tag.Year;
TagLib.Properties audioProperties = tagFile.Properties;
durationInSeconds = (int)audioProperties.Duration.TotalSeconds;
sampleRate = audioProperties.AudioSampleRate;
channels = audioProperties.AudioChannels;
if (audioProperties.BitsPerSample > 0)
bitDepth = audioProperties.BitsPerSample;
if (audioProperties.AudioBitrate > 0)
bitrate = audioProperties.AudioBitrate;
if (!string.IsNullOrWhiteSpace(audioProperties.Description))
audioCodec = audioProperties.Description;
TagLib.Properties audioProperties = tagFile.Properties;
durationInSeconds = (int)audioProperties.Duration.TotalSeconds;
sampleRate = audioProperties.AudioSampleRate;
channels = audioProperties.AudioChannels;
// The container is the format of the file itself, so it is resolved from the concrete type of the parsed file and not from its tags.
container = AudioContainerResolver.Resolve(tagFile);
if (audioProperties.BitsPerSample > 0)
bitDepth = audioProperties.BitsPerSample;
if (audioProperties.AudioBitrate > 0)
bitrate = audioProperties.AudioBitrate;
if (!string.IsNullOrWhiteSpace(audioProperties.Description))
audioCodec = audioProperties.Description;
// The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames
// of the tag again for every key.
IReadOnlyDictionary<string, string[]> id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile);
// The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames
// of the tag again for every key.
IReadOnlyDictionary<string, string[]> id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile);
// The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly,
// instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so
// they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work.
musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId);
musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId);
musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId);
musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId);
musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId);
musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID"));
musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID"));
string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK");
if (!string.IsNullOrWhiteSpace(extendedWorkTitle))
workTitle = extendedWorkTitle;
// The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly,
// instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so
// they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work.
musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId);
musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId);
musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId);
musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId);
musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId);
musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID"));
musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID"));
string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK");
if (!string.IsNullOrWhiteSpace(extendedWorkTitle))
workTitle = extendedWorkTitle;
// The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single
// slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated.
acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID");
moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS")
.SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Where(mood => !string.IsNullOrWhiteSpace(mood))
.Distinct(StringComparer.OrdinalIgnoreCase)];
replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain"));
replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak"));
replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain"));
replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak"));
// The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single
// slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated.
acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID");
moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS")
.SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Where(mood => !string.IsNullOrWhiteSpace(mood))
.Distinct(StringComparer.OrdinalIgnoreCase)];
replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain"));
replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak"));
replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain"));
replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak"));
}
}
}
catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException)
@@ -330,6 +339,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
Channels = channels,
BitDepth = bitDepth,
AudioCodec = audioCodec,
Container = container,
Bitrate = bitrate,
AcoustId = acoustId,
ReplayGainTrackGain = replayGainTrackGain,
@@ -348,6 +358,17 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
};
}
/// <summary>
/// Determines whether the file stored at <paramref name="path"/> is a reparse point, such as a symbolic link.
/// </summary>
/// <param name="path">The file system path of the file to check.</param>
/// <returns><see langword="true"/> when the file is a reparse point, otherwise <see langword="false"/>.</returns>
private static bool IsReparsePoint(string path)
{
// This only detects a leaf file that is itself a link; a linked directory encountered during discovery is not caught here.
return (File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
}
/// <summary>
/// Parses the provided tag <paramref name="value"/> as a globally unique identifier.
/// </summary>
@@ -460,6 +460,7 @@ public class AddAlbumEndpointSummary : Summary<AddAlbumEndpoint, AddAlbumRequest
AlbumId: albumId,
LibraryId: libraryId,
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -552,6 +553,7 @@ public class AddAlbumEndpointSummary : Summary<AddAlbumEndpoint, AddAlbumRequest
AlbumId: albumId,
LibraryId: libraryId,
Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
Container: "FLAC",
Metadata: new(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
@@ -152,6 +152,7 @@ public class GetAlbumEndpointSummary : Summary<GetAlbumEndpoint, EmptyRequest>
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -244,6 +245,7 @@ public class GetAlbumEndpointSummary : Summary<GetAlbumEndpoint, EmptyRequest>
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
Container: "FLAC",
Metadata: new(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
@@ -33,6 +33,7 @@ public class GetAlbumTracksEndpointSummary : Summary<GetAlbumTracksEndpoint, Emp
ResponseParam<TrackResponse>(r => r.AlbumId, "The Id of the album the track belongs to.");
ResponseParam<TrackResponse>(r => r.LibraryId, "The Id of the media library the track belongs to.");
ResponseParam<TrackResponse>(r => r.Path, "The file system path of the track.");
ResponseParam<TrackResponse>(r => r.Container, "The container of the audio file of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Title, "The title of the track.");
ResponseParam<TrackResponse>(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Description, "The description of the track, if applicable.");
@@ -80,6 +81,7 @@ public class GetAlbumTracksEndpointSummary : Summary<GetAlbumTracksEndpoint, Emp
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new MusicTrackMetadataDto(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -172,6 +174,7 @@ public class GetAlbumTracksEndpointSummary : Summary<GetAlbumTracksEndpoint, Emp
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/02-youre-my-best-friend.flac",
Container: "FLAC",
Metadata: new MusicTrackMetadataDto(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
@@ -264,6 +264,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -356,6 +357,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
Container: "FLAC",
Metadata: new(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
@@ -633,6 +633,7 @@ public class AddArtistEndpointSummary : Summary<AddArtistEndpoint, AddArtistRequ
AlbumId: albumId,
LibraryId: libraryId,
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -731,6 +732,7 @@ public class AddArtistEndpointSummary : Summary<AddArtistEndpoint, AddArtistRequ
AlbumId: albumId,
LibraryId: libraryId,
Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
Container: "FLAC",
Metadata: new(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
@@ -123,6 +123,7 @@ public class GetArtistEndpointSummary : Summary<GetArtistEndpoint, EmptyRequest>
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -154,6 +154,7 @@ public class GetArtistAlbumsEndpointSummary : Summary<GetArtistAlbumsEndpoint, E
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -328,6 +329,7 @@ public class GetArtistAlbumsEndpointSummary : Summary<GetArtistAlbumsEndpoint, E
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/the-works/01-radio-ga-ga.flac",
Container: "FLAC",
Metadata: new(
Title: "Radio Ga Ga",
OriginalTitle: "Radio Ga Ga",
@@ -135,6 +135,7 @@ public class GetArtistsEndpointSummary : Summary<GetArtistsEndpoint, GetArtistsR
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -259,6 +260,7 @@ public class GetArtistsEndpointSummary : Summary<GetArtistsEndpoint, GetArtistsR
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/david-bowie/heroes/01-heroes.flac",
Container: "FLAC",
Metadata: new(
Title: "Heroes",
OriginalTitle: "Heroes",
@@ -630,6 +630,7 @@ public class UpdateArtistEndpointSummary : Summary<UpdateArtistEndpoint, UpdateA
AlbumId: albumId,
LibraryId: libraryId,
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new MusicTrackMetadataDto(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -728,6 +729,7 @@ public class UpdateArtistEndpointSummary : Summary<UpdateArtistEndpoint, UpdateA
AlbumId: albumId,
LibraryId: libraryId,
Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
Container: "FLAC",
Metadata: new MusicTrackMetadataDto(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
@@ -170,6 +170,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
ResponseParam<TrackResponse>(r => r.AlbumId, "The Id of the album the track belongs to.");
ResponseParam<TrackResponse>(r => r.LibraryId, "The Id of the media library the track belongs to.");
ResponseParam<TrackResponse>(r => r.Path, "The file system path of the track.");
ResponseParam<TrackResponse>(r => r.Container, "The container of the audio file of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Title, "The title of the track.");
ResponseParam<TrackResponse>(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Description, "The description of the track, if applicable.");
@@ -215,6 +216,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new MusicTrackMetadataDto(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -33,6 +33,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, EmptyRequest>
ResponseParam<TrackResponse>(r => r.AlbumId, "The Id of the album the track belongs to.");
ResponseParam<TrackResponse>(r => r.LibraryId, "The Id of the media library the track belongs to.");
ResponseParam<TrackResponse>(r => r.Path, "The file system path of the track.");
ResponseParam<TrackResponse>(r => r.Container, "The container of the audio file of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Title, "The title of the track.");
ResponseParam<TrackResponse>(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Description, "The description of the track, if applicable.");
@@ -78,6 +79,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, EmptyRequest>
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new MusicTrackMetadataDto(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -168,6 +168,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
ResponseParam<TrackResponse>(r => r.AlbumId, "The Id of the album the track belongs to.");
ResponseParam<TrackResponse>(r => r.LibraryId, "The Id of the media library the track belongs to.");
ResponseParam<TrackResponse>(r => r.Path, "The file system path of the track.");
ResponseParam<TrackResponse>(r => r.Container, "The container of the audio file of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Title, "The title of the track.");
ResponseParam<TrackResponse>(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable.");
ResponseParam<TrackResponse>(r => r.Metadata!.Description, "The description of the track, if applicable.");
@@ -213,6 +214,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Container: "FLAC",
Metadata: new MusicTrackMetadataDto(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
@@ -39,6 +39,7 @@ public class MusicLibraryScanItemMetadataEntityFixture
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
/// <param name="workTitle">Optional. The title of the work.</param>
/// <param name="includeMusicBrainzTags">Whether the MusicBrainz identifiers and the work title should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="MusicLibraryScanItemMetadataEntity"/>.</returns>
public MusicLibraryScanItemMetadataEntity Create(
Guid? id = null,
@@ -58,7 +59,8 @@ public class MusicLibraryScanItemMetadataEntityFixture
Guid? musicBrainzTrackId = null,
Guid? musicBrainzWorkId = null,
string? workTitle = null,
bool includeMusicBrainzTags = true)
bool includeMusicBrainzTags = true,
bool includeContainer = true)
{
return new MusicLibraryScanItemMetadataEntity
{
@@ -78,6 +80,7 @@ public class MusicLibraryScanItemMetadataEntityFixture
Channels = _faker.PickRandom(1, 2, 6),
BitDepth = Random.Shared.Next(8, 32),
AudioCodec = _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC"),
Container = includeContainer ? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV") : null,
Bitrate = Random.Shared.Next(96, 1411),
MusicBrainzArtistId = includeMusicBrainzTags ? musicBrainzArtistId ?? Guid.NewGuid() : null,
MusicBrainzReleaseArtistId = includeMusicBrainzTags ? musicBrainzReleaseArtistId ?? Guid.NewGuid() : null,
@@ -37,6 +37,7 @@ public class TrackEntityFixture
/// <param name="libraryId">Optional. The Id of the media library that owns the track.</param>
/// <param name="path">Optional. The file system path of the track.</param>
/// <param name="title">Optional. The title of the track.</param>
/// <param name="container">Optional. The container of the audio file of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="originalReleaseDate">Optional. The original release date of the track.</param>
/// <param name="originalReleaseYear">Optional. The original release year of the track.</param>
@@ -47,6 +48,7 @@ public class TrackEntityFixture
/// <param name="includeOriginalReleaseYear">Whether the original release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReReleaseDate">Whether the re-release date should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReReleaseYear">Whether the re-release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
/// <param name="metadataStatus">Optional. The metadata enrichment status of the track.</param>
/// <returns>The created <see cref="TrackEntity"/>.</returns>
public TrackEntity Create(
@@ -55,6 +57,7 @@ public class TrackEntityFixture
Guid? libraryId = null,
string? path = null,
string? title = null,
string? container = null,
int? trackNumber = null,
DateOnly? originalReleaseDate = null,
int? originalReleaseYear = null,
@@ -65,6 +68,7 @@ public class TrackEntityFixture
bool includeOriginalReleaseYear = true,
bool includeReReleaseDate = true,
bool includeReReleaseYear = true,
bool includeContainer = true,
MetadataStatus? metadataStatus = null)
{
Guid resolvedId = id ?? Guid.NewGuid();
@@ -111,6 +115,7 @@ public class TrackEntityFixture
.RuleFor(x => x.Channels, f => f.PickRandom(1, 2, 6))
.RuleFor(x => x.BitDepth, Random.Shared.Next(8, 32))
.RuleFor(x => x.AudioCodec, f => f.PickRandom("FLAC", "MP3", "AAC", "ALAC"))
.RuleFor(x => x.Container, f => includeContainer ? (container ?? f.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null)
.RuleFor(x => x.Bitrate, Random.Shared.Next(96, 1411))
.RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20))
.RuleFor(x => x.DiscNumber, Random.Shared.Next(1, 3))
@@ -61,6 +61,7 @@ public class AudioMetadataDtoFixture
/// <param name="channels">Optional. The number of audio channels.</param>
/// <param name="bitDepth">Optional. The bit depth of the audio.</param>
/// <param name="audioCodec">Optional. The audio codec used.</param>
/// <param name="container">Optional. The container of the audio file.</param>
/// <param name="bitrate">Optional. The bitrate of the audio, in kbps.</param>
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
@@ -86,6 +87,7 @@ public class AudioMetadataDtoFixture
/// <param name="includeChannels">Whether the channels should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAudioCodec">Whether the audio codec should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitrate">Whether the bitrate should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
@@ -114,6 +116,7 @@ public class AudioMetadataDtoFixture
int? channels = null,
int? bitDepth = null,
string? audioCodec = null,
string? container = null,
int? bitrate = null,
Guid? musicBrainzRecordingId = null,
Guid? musicBrainzTrackId = null,
@@ -139,6 +142,7 @@ public class AudioMetadataDtoFixture
bool includeChannels = true,
bool includeBitDepth = true,
bool includeAudioCodec = true,
bool includeContainer = true,
bool includeBitrate = true,
bool includeMusicBrainzRecordingId = true,
bool includeMusicBrainzTrackId = true,
@@ -167,6 +171,7 @@ public class AudioMetadataDtoFixture
includeChannels ? (channels ?? _faker.Random.Int(1, 8)) : null,
includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
includeAudioCodec ? (audioCodec ?? _faker.Random.ArrayElement(["FLAC", "MP3", "AAC", "ALAC"])) : null,
includeContainer ? (container ?? _faker.Random.ArrayElement(["MP3", "FLAC", "OGG", "MP4", "AAC", "WAV"])) : null,
includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null,
includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
@@ -39,6 +39,7 @@ public class TrackResponseFixture
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
/// <param name="libraryId">Optional. The Id of the media library this track belongs to.</param>
/// <param name="path">Optional. The file system path of the track.</param>
/// <param name="container">Optional. The container of the audio file of the track.</param>
/// <param name="metadata">Optional. The audio metadata of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
@@ -56,6 +57,7 @@ public class TrackResponseFixture
/// <param name="ratings">Optional. The list of ratings of the track.</param>
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="TrackResponse"/>.</returns>
public TrackResponse Create(
Guid? id = null,
@@ -78,7 +80,9 @@ public class TrackResponseFixture
List<MediaContributorReferenceDto>? contributors = null,
List<AudioRatingDto>? ratings = null,
bool includeMusicBrainzRecordingId = true,
bool includeMusicBrainzTrackId = true)
bool includeMusicBrainzTrackId = true,
bool includeContainer = true,
string? container = null)
{
return new TrackResponse(
id ?? Guid.NewGuid(),
@@ -99,7 +103,8 @@ public class TrackResponseFixture
moods ?? _moodDtoFixture.CreateMany(1),
isrcs ?? _isrcDtoFixture.CreateMany(1),
contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1),
ratings ?? _audioRatingDtoFixture.CreateMany(1));
ratings ?? _audioRatingDtoFixture.CreateMany(1),
includeContainer ? (container ?? _faker.Random.ArrayElement(["MP3", "FLAC", "OGG", "MP4", "AAC", "WAV"])) : null);
}
/// <summary>
@@ -39,6 +39,7 @@ public class AudioMetadataFixture
/// <param name="originalLanguage">Optional. The original language of the audio.</param>
/// <param name="bitDepth">Optional. The bit depth of the audio.</param>
/// <param name="audioCodec">Optional. The audio codec used.</param>
/// <param name="container">Optional. The container of the audio.</param>
/// <param name="bitrate">Optional. The bitrate of the audio, in kbps.</param>
/// <param name="acoustId">Optional. The AcoustID fingerprint identifier of the audio file.</param>
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain, in decibels.</param>
@@ -60,6 +61,7 @@ public class AudioMetadataFixture
Optional<LanguageInfo>? originalLanguage = null,
Optional<int>? bitDepth = null,
Optional<string>? audioCodec = null,
Optional<string>? container = null,
Optional<int>? bitrate = null,
Optional<string>? acoustId = null,
Optional<decimal>? replayGainTrackGain = null,
@@ -81,6 +83,7 @@ public class AudioMetadataFixture
originalLanguage ?? Optional<LanguageInfo>.None(),
bitDepth ?? Optional<int>.Some(_faker.Random.Int(8, 32)),
audioCodec ?? Optional<string>.Some("PCM"),
container ?? Optional<string>.Some(_faker.PickRandom("MP3", "FLAC", "OGG", "MP4", "AAC", "WAV")),
bitrate ?? Optional<int>.Some(_faker.Random.Int(128, 320)),
acoustId ?? Optional<string>.None(),
replayGainTrackGain ?? Optional<decimal>.None(),
@@ -0,0 +1,309 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains integration tests for the <see cref="MusicMetadataExtractionJob"/> class, probing real audio containers through the tagging library.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMetadataExtractionJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly ILibraryPathTemplateService _mockPathTemplateService;
private readonly IPathService _mockPathService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MusicMetadataExtractionJob _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryId _libraryId;
private readonly ScanId _scanId;
private readonly UserId _userId;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMetadataExtractionJobTests"/> class.
/// </summary>
public MusicMetadataExtractionJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMusicMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('\\');
_mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService);
_mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
// Default stubs that keep the happy path working, overridden per test where needed.
_mockMusicMetadataRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(_libraryPathTemplateFixture.Create()));
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>()).Returns(Result.From<Optional<ParsedLibraryPath>>(Optional<ParsedLibraryPath>.None()));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("tone");
_mockPathService.GetFileName(Arg.Any<string>()).Returns("tone.wav");
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For<Microsoft.Extensions.Logging.ILogger<MusicMetadataExtractionJob>>())
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenTheFileIsARealAudioFile_ShouldCaptureItsContainerAndAudioProperties()
{
// Arrange
using TemporaryMediaDirectory temporaryMediaDirectory = new();
string audioFilePath = temporaryMediaDirectory.CreateWavFile("tone.wav");
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [temporaryMediaDirectory.Path]);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([audioFilePath]));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().Container == "WAV"
&& items.First().SampleRate == 8000
&& items.First().Channels == 1
&& items.First().BitDepth == 16),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheContainerHasNoDedicatedParser_ShouldFallBackToTheMimeTypeName()
{
// Arrange
using TemporaryMediaDirectory temporaryMediaDirectory = new();
string imageFilePath = temporaryMediaDirectory.CreatePngFile("cover.png");
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [temporaryMediaDirectory.Path]);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([imageFilePath]));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().Container == "PNG"),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFileIsAReparsePoint_ShouldNotReadTheLinkedFile()
{
// Arrange
using TemporaryMediaDirectory temporaryMediaDirectory = new();
using TemporaryMediaDirectory outsideMediaDirectory = new();
string targetFilePath = outsideMediaDirectory.CreateWavFile("target.wav");
string linkFilePath = System.IO.Path.Combine(temporaryMediaDirectory.Path, "link.wav");
if (!TryCreateFileSymbolicLink(linkFilePath, targetFilePath))
return; // The environment does not support creating file symbolic links.
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [temporaryMediaDirectory.Path]);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([linkFilePath]));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The linked file lives outside the content location, so its audio metadata must not be read: the container stays unrecognized.
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().Container == null
&& items.First().SampleRate == 0),
Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates a file system symbolic link that points to the target file.
/// </summary>
/// <param name="linkPath">The file system path of the symbolic link to create.</param>
/// <param name="targetPath">The file system path of the file the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
private static bool TryCreateFileSymbolicLink(string linkPath, string targetPath)
{
try
{
File.CreateSymbolicLink(linkPath, targetPath);
return true;
}
catch (Exception)
{
// Creating a file symbolic link requires elevated privileges on Windows, so the environment may not support it.
return false;
}
}
/// <summary>
/// Test helper managing a temporary directory holding real media files, deleted when the test finishes.
/// </summary>
private sealed class TemporaryMediaDirectory : IDisposable
{
/// <summary>
/// A minimal, valid, one by one pixel PNG image, used to exercise a container that has no dedicated parser.
/// </summary>
private const string PNG_BYTES = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAANSURBVBhXY2BgYGAAAAAFAAGKM+MAAAAAAElFTkSuQmCC";
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="TemporaryMediaDirectory"/> class.
/// </summary>
public TemporaryMediaDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-music-probe-{Guid.NewGuid():N}");
Directory.CreateDirectory(Path);
}
/// <summary>
/// Gets the full path of the temporary directory.
/// </summary>
public string Path { get; }
/// <summary>
/// Writes a minimal, valid, one second long 16 bit PCM mono 8000 Hz WAV file into the temporary directory.
/// </summary>
/// <param name="fileName">The name of the WAV file to create.</param>
/// <returns>The full path of the created WAV file.</returns>
public string CreateWavFile(string fileName)
{
const int SAMPLE_RATE = 8000;
const short CHANNELS = 1;
const short BITS_PER_SAMPLE = 16;
int blockAlign = CHANNELS * (BITS_PER_SAMPLE / 8);
int dataSize = SAMPLE_RATE * blockAlign;
string filePath = System.IO.Path.Combine(Path, fileName);
using (FileStream stream = new(filePath, FileMode.Create, FileAccess.Write))
using (BinaryWriter writer = new(stream))
{
writer.Write("RIFF"u8.ToArray());
writer.Write(36 + dataSize);
writer.Write("WAVE"u8.ToArray());
writer.Write("fmt "u8.ToArray());
writer.Write(16);
writer.Write((short)1);
writer.Write(CHANNELS);
writer.Write(SAMPLE_RATE);
writer.Write(SAMPLE_RATE * blockAlign);
writer.Write((short)blockAlign);
writer.Write(BITS_PER_SAMPLE);
writer.Write("data"u8.ToArray());
writer.Write(dataSize);
writer.Write(new byte[dataSize]);
}
return filePath;
}
/// <summary>
/// Writes a minimal, valid PNG image into the temporary directory.
/// </summary>
/// <param name="fileName">The name of the PNG file to create.</param>
/// <returns>The full path of the created PNG file.</returns>
public string CreatePngFile(string fileName)
{
string filePath = System.IO.Path.Combine(Path, fileName);
File.WriteAllBytes(filePath, Convert.FromBase64String(PNG_BYTES));
return filePath;
}
/// <summary>
/// Deletes the temporary directory, ignoring the failures of the files that are still in use.
/// </summary>
public void Dispose()
{
if (_disposed)
return;
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
// Best effort cleanup of the temporary directory.
}
_disposed = true;
}
}
}
@@ -56,6 +56,7 @@ public class Id3TrackMetadataProviderTests : IDisposable
Assert.Equal("The Track", result.Title);
Assert.Equal(MusicKey.CSharpMinor, result.Key);
Assert.Equal(128, result.Bpm);
Assert.Equal("WAV", result.Container);
Assert.NotNull(result.Contributors);
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Artist");
}
@@ -15,6 +15,11 @@ namespace Lumina.Plugins.ID3.IntegrationTests.Core.Tags;
[ExcludeFromCodeCoverage]
public class Id3TagReaderTests : IDisposable
{
/// <summary>
/// A minimal, valid, one by one pixel PNG image, used to exercise a container that has no dedicated parser.
/// </summary>
private const string PNG_BYTES = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAANSURBVBhXY2BgYGAAAAAFAAGKM+MAAAAAAElFTkSuQmCC";
private readonly Id3TagReader _sut = new();
private readonly string _temporaryDirectory;
@@ -131,6 +136,7 @@ public class Id3TagReaderTests : IDisposable
Assert.Equal(16, result.BitDepth);
Assert.True(result.Bitrate > 0);
Assert.Equal("PCM Audio", result.AudioCodec);
Assert.Equal("WAV", result.Container);
Assert.Equal("https://artist.example", result.Website);
Assert.Equal(artistId.ToString(), result.MusicBrainzArtistId);
Assert.Equal(releaseArtistId.ToString(), result.MusicBrainzReleaseArtistId);
@@ -192,6 +198,7 @@ public class Id3TagReaderTests : IDisposable
Assert.Equal(1, result.Channels);
Assert.Equal(16, result.BitDepth);
Assert.Equal("PCM Audio", result.AudioCodec);
Assert.Equal("WAV", result.Container);
Assert.Null(result.Website);
Assert.Null(result.MusicBrainzArtistId);
Assert.Null(result.MusicBrainzReleaseArtistId);
@@ -216,6 +223,21 @@ public class Id3TagReaderTests : IDisposable
Assert.Null(result);
}
[Fact]
public void Read_WhenTheContainerHasNoDedicatedParser_ShouldFallBackToTheMimeTypeName()
{
// Arrange
string path = Path.Combine(_temporaryDirectory, "cover.png");
File.WriteAllBytes(path, Convert.FromBase64String(PNG_BYTES));
// Act
Id3TagDto? result = _sut.Read(path);
// Assert
Assert.NotNull(result);
Assert.Equal("PNG", result.Container);
}
[Fact]
public void Read_WhenCalledTwiceForTheSamePath_ShouldReturnTheCachedSnapshot()
{
@@ -284,6 +284,30 @@ public class UpdateArtistCommandMappingTests
Assert.Equal(disambiguation, updatedTrack.Disambiguation.Value);
}
[Fact]
public void ToDomainEntity_WhenTheTrackMetadataCarriesNoContainer_ShouldKeepTheTrackContainer()
{
// Arrange
Guid libraryId = Guid.NewGuid();
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId);
AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]);
UpdateArtistCommand command = _updateArtistCommandFixture.Create(
libraryId: libraryId.ToString(),
artistId: artist.Id.Value.ToString(),
albums: [albumCommand]);
// Act
Result<Artist> result = command.ToDomainEntity(artist);
// Assert
Assert.False(result.IsFailure);
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
// The stored container is pinned to a known value, so the assertion cannot pass by coincidence.
// The container is captured from the file itself, so reconciling a track during an artist edit keeps the stored container.
Assert.Equal("FLAC", updatedTrack.Metadata.Container.Value);
}
/// <summary>
/// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
/// </summary>
@@ -296,7 +320,7 @@ public class UpdateArtistCommandMappingTests
AlbumEntity albumEntity = _albumEntityFixture.Create(
id: albumId,
libraryId: libraryId,
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]);
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, container: "FLAC")]);
ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]);
Result<Artist> artistResult = artistEntity.ToDomainEntity();
return (artistResult.Value, albumId, trackId);
@@ -50,6 +50,7 @@ public class AudioMetadataDtoMappingTests
Assert.Equal(dto.Channels, track.Metadata.Channels);
Assert.Equal(dto.BitDepth, track.Metadata.BitDepth.Value);
Assert.Equal(dto.AudioCodec, track.Metadata.AudioCodec.Value);
Assert.Equal(dto.Container, track.Metadata.Container.Value);
Assert.Equal(dto.Bitrate, track.Metadata.Bitrate.Value);
Assert.True(track.Script.HasValue);
Assert.Equal(dto.Script, track.Script.Value);
@@ -80,12 +81,14 @@ public class AudioMetadataDtoMappingTests
int storedChannels = track.Metadata.Channels;
bool hadStoredWork = track.Work.HasValue;
int storedIsrcCount = track.Isrcs.Count;
string? storedContainer = track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null;
AudioMetadataDto dto = _audioMetadataDtoFixture.Create(
includeDurationInSeconds: false,
includeSampleRate: false,
includeChannels: false,
includeBitDepth: false,
includeAudioCodec: false,
includeContainer: false,
includeBitrate: false,
includeWork: false,
includeIsrcs: false,
@@ -99,6 +102,7 @@ public class AudioMetadataDtoMappingTests
Assert.Equal(storedDuration, track.Metadata.DurationInSeconds);
Assert.Equal(storedSampleRate, track.Metadata.SampleRate);
Assert.Equal(storedChannels, track.Metadata.Channels);
Assert.Equal(storedContainer, track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null);
Assert.Equal(hadStoredWork, track.Work.HasValue);
Assert.Equal(storedIsrcCount, track.Isrcs.Count);
}
@@ -27,7 +27,7 @@ public class MusicTrackMetadataDtoMappingTests
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
[Fact]
public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly()
public void ToDomainValueObject_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly()
{
// Arrange
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create();
@@ -70,6 +70,8 @@ public class MusicTrackMetadataDtoMappingTests
Assert.Equal(dto.BitDepth, metadata.BitDepth.Value);
Assert.True(metadata.AudioCodec.HasValue);
Assert.Equal(dto.AudioCodec, metadata.AudioCodec.Value);
// The container is captured locally from the file itself, so it can never be set through the metadata of a request.
Assert.False(metadata.Container.HasValue);
Assert.True(metadata.Bitrate.HasValue);
Assert.Equal(dto.Bitrate, metadata.Bitrate.Value);
Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name));
@@ -77,7 +79,7 @@ public class MusicTrackMetadataDtoMappingTests
}
[Fact]
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults()
public void ToDomainValueObject_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults()
{
// Arrange
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(
@@ -123,7 +125,7 @@ public class MusicTrackMetadataDtoMappingTests
}
[Fact]
public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone()
public void ToDomainValueObject_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone()
{
// Arrange
LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false);
@@ -141,7 +143,7 @@ public class MusicTrackMetadataDtoMappingTests
}
[Fact]
public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError()
public void ToDomainValueObject_WhenReleaseInfoIsInvalid_ShouldReturnError()
{
// Arrange
ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create(
@@ -158,7 +160,7 @@ public class MusicTrackMetadataDtoMappingTests
}
[Fact]
public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError()
public void ToDomainValueObject_WhenGenreIsInvalid_ShouldReturnError()
{
// Arrange
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]);
@@ -172,7 +174,7 @@ public class MusicTrackMetadataDtoMappingTests
}
[Fact]
public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError()
public void ToDomainValueObject_WhenTagIsInvalid_ShouldReturnError()
{
// Arrange
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]);
@@ -74,6 +74,7 @@ public class TrackEntityMappingTests
Assert.Equal(entity.Channels, track.Metadata.Channels);
Assert.Equal(entity.BitDepth, track.Metadata.BitDepth.Value);
Assert.Equal(entity.AudioCodec, track.Metadata.AudioCodec.Value);
Assert.Equal(entity.Container, track.Metadata.Container.Value);
Assert.Equal(entity.Bitrate, track.Metadata.Bitrate.Value);
Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), track.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name));
Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), track.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name));
@@ -95,6 +96,20 @@ public class TrackEntityMappingTests
Assert.Equal(entity.UpdatedOnUtc, track.UpdatedOnUtc.Value);
}
[Fact]
public void ToDomainEntity_WhenTheEntityHasNoContainer_ShouldMapMetadataWithoutAContainer()
{
// Arrange
TrackEntity entity = _trackEntityFixture.Create(includeContainer: false);
// Act
Result<Track> result = entity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.Metadata.Container.HasValue);
}
[Fact]
public void ToDomainEntity_WhenReleaseDateAndYearDoNotMatch_ShouldReturnError()
{
@@ -226,6 +241,7 @@ public class TrackEntityMappingTests
Assert.Equal(entity.Bitrate, result.Metadata.Bitrate);
Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), result.Metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name));
Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), result.Metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name));
Assert.Equal(entity.Container, result.Container);
Assert.Equal(entity.TrackNumber, result.TrackNumber);
Assert.Equal(entity.DiscNumber, result.DiscNumber);
Assert.Equal(entity.Script, result.Script);
@@ -68,6 +68,7 @@ public class TrackMappingTests
Assert.Equal(track.Metadata.Channels, result.Channels);
Assert.Equal(track.Metadata.BitDepth.HasValue ? track.Metadata.BitDepth.Value : null, result.BitDepth);
Assert.Equal(track.Metadata.AudioCodec.HasValue ? track.Metadata.AudioCodec.Value : null, result.AudioCodec);
Assert.Equal(track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null, result.Container);
Assert.Equal(track.Metadata.Bitrate.HasValue ? track.Metadata.Bitrate.Value : null, result.Bitrate);
Assert.Equal(track.TrackNumber, result.TrackNumber);
Assert.Equal(track.DiscNumber.HasValue ? track.DiscNumber.Value : null, result.DiscNumber);
@@ -134,6 +135,7 @@ public class TrackMappingTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
Track track = _trackFixture.Create(
metadata: metadata,
@@ -169,6 +171,7 @@ public class TrackMappingTests
Assert.Null(result.OriginalLanguageNativeName);
Assert.Null(result.BitDepth);
Assert.Null(result.AudioCodec);
Assert.Null(result.Container);
Assert.Null(result.Bitrate);
Assert.Null(result.DiscNumber);
Assert.Null(result.Script);
@@ -286,6 +286,32 @@ public class UpdateTrackCommandMappingTests
Assert.False(updatedTrack.Disambiguation.HasValue);
}
[Fact]
public void ToDomainEntity_WhenTheMetadataCarriesNoContainer_ShouldKeepTheTrackContainer()
{
// Arrange
Guid libraryId = Guid.NewGuid();
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
Track storedTrack = artist.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
Optional<string> storedContainer = storedTrack.Metadata.Container;
UpdateTrackCommand command = _updateTrackCommandFixture.Create(
libraryId: libraryId.ToString(),
artistId: artist.Id.Value.ToString(),
albumId: albumId.ToString(),
trackId: trackId.ToString());
// Act
Result<Artist> result = command.ToDomainEntity(artist);
// Assert
Assert.False(result.IsFailure);
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
// The stored container is pinned to a known value, so the assertion cannot pass by coincidence.
Assert.Equal("FLAC", storedContainer.Value);
// The container is captured from the file itself and is never part of the edit metadata, so an update keeps the stored container.
Assert.Equal("FLAC", updatedTrack.Metadata.Container.Value);
}
/// <summary>
/// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
/// </summary>
@@ -298,7 +324,7 @@ public class UpdateTrackCommandMappingTests
AlbumEntity albumEntity = _albumEntityFixture.Create(
id: albumId,
libraryId: libraryId,
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]);
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, container: "FLAC")]);
ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]);
Result<Artist> artistResult = artistEntity.ToDomainEntity();
return (artistResult.Value, albumId, trackId);
@@ -41,6 +41,7 @@ public class AudioMetadataTests
Optional<LanguageInfo>.None(),
Optional<int>.Some(16),
Optional<string>.Some("PCM"),
Optional<string>.Some("WAV"),
Optional<int>.Some(1411),
Optional<string>.Some("f0e9c1a2-0000-0000-0000-000000000000"),
Optional<decimal>.Some(-6.53m),
@@ -57,6 +58,7 @@ public class AudioMetadataTests
Assert.Equal("A song by the British rock band Queen.", result.Value.Description.Value);
Assert.Equal(16, result.Value.BitDepth.Value);
Assert.Equal("PCM", result.Value.AudioCodec.Value);
Assert.Equal("WAV", result.Value.Container.Value);
Assert.Equal(1411, result.Value.Bitrate.Value);
Assert.Single(result.Value.Genres);
Assert.Single(result.Value.Tags);
@@ -80,6 +82,7 @@ public class AudioMetadataTests
Optional<LanguageInfo>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<decimal>.None(),
@@ -91,6 +94,7 @@ public class AudioMetadataTests
Assert.False(result.IsFailure);
Assert.False(result.Value.BitDepth.HasValue);
Assert.False(result.Value.AudioCodec.HasValue);
Assert.False(result.Value.Container.HasValue);
Assert.False(result.Value.Bitrate.HasValue);
}
@@ -115,6 +119,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
@@ -130,6 +135,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
// Assert
@@ -157,6 +163,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
@@ -172,6 +179,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
// Assert
@@ -200,6 +208,7 @@ public class AudioMetadataTests
Optional<LanguageInfo>.Some(originalLanguage),
Optional<int>.Some(16),
Optional<string>.Some("PCM"),
Optional<string>.Some("WAV"),
Optional<int>.Some(1411),
Optional<string>.Some("f0e9c1a2-0000-0000-0000-000000000000"),
Optional<decimal>.Some(-6.53m),
@@ -237,6 +246,7 @@ public class AudioMetadataTests
Optional<LanguageInfo>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<decimal>.None(),
@@ -271,6 +281,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Love of My Life",
@@ -286,6 +297,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
// Assert
@@ -334,6 +346,50 @@ public class AudioMetadataTests
Assert.NotEqual(firstResult, secondResult);
}
[Fact]
public void Equals_WithDifferentContainer_ShouldReturnFalse()
{
// Arrange
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
// Act
AudioMetadata firstResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.Some("MP3"),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.Some("FLAC"),
bitrate: Optional<int>.None());
// Assert
Assert.NotEqual(firstResult, secondResult);
}
[Fact]
public void Equals_WithDifferentGenres_ShouldReturnFalse()
{
@@ -355,6 +411,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
@@ -370,6 +427,7 @@ public class AudioMetadataTests
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
container: Optional<string>.None(),
bitrate: Optional<int>.None());
// Assert
@@ -239,6 +239,62 @@ public class TrackTests
Assert.Equal(originalMoods, track.Moods);
}
[Fact]
public void UpdateDetails_WhenTheMetadataCarriesNoContainer_ShouldKeepTheStoredContainer()
{
// Arrange
Track track = _trackFixture.Create();
Optional<string> storedContainer = track.Metadata.Container;
AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional<string>.None());
// Act
Result<Updated> result = track.UpdateDetails(
metadata,
track.Disambiguation,
track.TrackNumber,
track.DiscNumber,
track.Script,
track.Key,
track.Bpm,
track.IsVideo,
track.Work,
track.MusicBrainzRecordingId,
track.MusicBrainzTrackId);
// Assert
Assert.False(result.IsFailure);
// The container is captured from the file itself and is never part of an edit, so an update that does not carry one keeps the stored container.
Assert.Equal(storedContainer, track.Metadata.Container);
// The rest of the metadata still comes from the update.
Assert.Equal(metadata.Title, track.Metadata.Title);
}
[Fact]
public void UpdateDetails_WhenTheMetadataCarriesAContainer_ShouldReplaceTheStoredContainer()
{
// Arrange
Track track = _trackFixture.Create();
AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional<string>.Some("OGG"));
// Act
Result<Updated> result = track.UpdateDetails(
metadata,
track.Disambiguation,
track.TrackNumber,
track.DiscNumber,
track.Script,
track.Key,
track.Bpm,
track.IsVideo,
track.Work,
track.MusicBrainzRecordingId,
track.MusicBrainzTrackId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("OGG", track.Metadata.Container.Value);
}
[Fact]
public void Create_WhenOptionalValuesAndCollectionsAreEmpty_ShouldCreateTrackWithoutThem()
{
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="AudioContainerResolver"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AudioContainerResolverTests
{
[Theory]
[InlineData(null, null)] // an absent mime type leaves the container unrecognized
[InlineData("", null)] // an empty mime type leaves the container unrecognized
[InlineData(" ", null)] // a blank mime type leaves the container unrecognized
[InlineData("taglib/wav", "WAV")] // the taglib prefix is dropped and the container is upper cased
[InlineData("taglib/png", "PNG")] // a container the resolver has no dedicated parser for still yields its name
[InlineData("audio/x-wavpack", "X-WAVPACK")] // the last segment of a standard mime type names the container
public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer)
{
// Act
string? container = AudioContainerResolver.ResolveFromMimeType(mimeType);
// Assert
Assert.Equal(expectedContainer, container);
}
}
@@ -91,6 +91,34 @@ public class MusicMetadataAggregatorTests
Assert.Equal(360, merged.DurationInSeconds);
}
[Fact]
public void Merge_WhenTheFirstAudioMetadataHasAContainer_ShouldKeepTheFirstContainer()
{
// Arrange
AudioMetadataDto first = _audioMetadataDtoFixture.Create(container: "MP3");
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
// Act
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("MP3", merged.Container);
}
[Fact]
public void Merge_WhenTheFirstAudioMetadataHasNoContainer_ShouldTakeTheSecondContainer()
{
// Arrange
AudioMetadataDto first = _audioMetadataDtoFixture.Create(includeContainer: false);
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
// Act
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("FLAC", merged.Container);
}
[Fact]
public void Merge_WhenTheFirstMetadataHasOnlyAReleaseYearAndTheSecondHasAReleaseDate_ShouldDeriveTheYearFromTheDate()
{
@@ -116,6 +116,33 @@ public class MusicMediaLibraryScanItemMaterializerTests
AlbumEntity secondAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == secondReleaseId);
Assert.Equal(firstRecordingId, Assert.Single(firstAlbum.Tracks).MusicBrainzRecordingId);
Assert.Equal(secondRecordingId, Assert.Single(secondAlbum.Tracks).MusicBrainzRecordingId);
// The container read from the file itself is carried from the staged metadata to the materialized track.
Assert.Equal(firstStagedItem.Container, Assert.Single(firstAlbum.Tracks).Container);
}
[Fact]
public async Task MaterializeItemsAsync_WhenTheStagedItemHasNoContainer_ShouldMaterializeTheTrackWithoutAContainer()
{
// Arrange
MusicLibraryScanItemMetadataEntity stagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Some Artist",
releaseName: "Some Release",
path: "/music/some-artist/some-release/track.mp3",
includeMusicBrainzTags: false,
includeContainer: false);
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [stagedItem.Path], CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
ArtistEntity artist = Assert.Single(_insertedArtists);
AlbumEntity album = Assert.Single(artist.Albums);
// A file whose container the scan could not recognize materializes its track without a container, rather than failing the scan.
Assert.Null(Assert.Single(album.Tracks).Container);
}
[Fact]
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.ID3.Core.Tags;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.ID3.UnitTests.Core.Tags;
/// <summary>
/// Contains unit tests for the <see cref="AudioContainerResolver"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AudioContainerResolverTests
{
[Theory]
[InlineData(null, null)] // an absent mime type leaves the container unrecognized
[InlineData("", null)] // an empty mime type leaves the container unrecognized
[InlineData(" ", null)] // a blank mime type leaves the container unrecognized
[InlineData("taglib/wav", "WAV")] // the taglib prefix is dropped and the container is upper cased
[InlineData("taglib/png", "PNG")] // a container the resolver has no dedicated parser for still yields its name
[InlineData("audio/x-wavpack", "X-WAVPACK")] // the last segment of a standard mime type names the container
public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer)
{
// Act
string? container = AudioContainerResolver.ResolveFromMimeType(mimeType);
// Assert
Assert.Equal(expectedContainer, container);
}
}