diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs
index 598e44de..b5b41a02 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs
@@ -53,6 +53,20 @@ public interface IPathService
/// An containing the path segments of the path up one level from , or an error.
Result> GoUpOneLevel(string path);
+ ///
+ /// Gets the name of the file or directory stored at , using the path separator of the current platform.
+ ///
+ /// The path whose name is retrieved.
+ /// The name of the file or directory stored at .
+ string GetFileName(string path);
+
+ ///
+ /// Gets the name of the file stored at without its extension, using the path separator of the current platform.
+ ///
+ /// The path whose file name is retrieved.
+ /// The name of the file stored at without its extension.
+ string GetFileNameWithoutExtension(string path);
+
///
/// Returns a collection of characters that are invalid for paths.
///
diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs
index 18f0d79b..c2e5929a 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs
@@ -105,6 +105,32 @@ public class PathService : IPathService
return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
}
+ ///
+ /// Gets the name of the file or directory stored at , using the path separator of the current platform.
+ ///
+ /// The path whose name is retrieved.
+ /// The name of the file or directory stored at .
+ public string GetFileName(string path)
+ {
+ if (string.IsNullOrEmpty(path))
+ return path;
+ string trimmedPath = path.TrimEnd(PathSeparator);
+ int lastSeparatorIndex = trimmedPath.LastIndexOf(PathSeparator);
+ return lastSeparatorIndex < 0 ? trimmedPath : trimmedPath[(lastSeparatorIndex + 1)..];
+ }
+
+ ///
+ /// Gets the name of the file stored at without its extension, using the path separator of the current platform.
+ ///
+ /// The path whose file name is retrieved.
+ /// The name of the file stored at without its extension.
+ public string GetFileNameWithoutExtension(string path)
+ {
+ string fileName = GetFileName(path);
+ int lastDotIndex = fileName.LastIndexOf('.');
+ return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex];
+ }
+
///
/// Returns a collection of characters that are invalid for paths.
///
diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
index 1bb36aad..10e7c307 100644
--- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
+++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
@@ -130,6 +130,7 @@ public static class InfrastructureLayerServices
services.AddTransient();
services.AddTransient();
+ services.AddSingleton();
services.AddSingleton();
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs
index cc5143b6..714a60f4 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
-using System.IO;
using System.Text.RegularExpressions;
#endregion
@@ -10,32 +10,43 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio
///
/// Derives the structure of a music library on disk from the file system path of a music file.
///
-internal static class MusicLibraryPathStructure
+internal sealed class MusicLibraryPathStructure
{
///
/// Matches the name of a directory that holds one disc of a multi-disc album, like "Disc 1" or "CD2".
///
private static readonly Regex s_discDirectoryPattern = new(@"^(?:disk|disc|cd)\s*\d+$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+ private readonly IPathService _pathService;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service used to determine the path separator of the current platform.
+ public MusicLibraryPathStructure(IPathService pathService)
+ {
+ _pathService = pathService;
+ }
+
///
/// Gets the on-disk directory of the album the track stored at belongs to.
/// A multi-disc album nests its tracks in disc subdirectories, so the directory of a disc is skipped in favor of its parent.
///
/// The file system path of the track whose album directory is retrieved.
/// The file system path of the album directory, or the directory of the track when it cannot be resolved.
- public static string GetAlbumDirectory(string trackPath)
+ public string GetAlbumDirectory(string trackPath)
{
if (string.IsNullOrEmpty(trackPath))
return trackPath;
- string? trackDirectory = Path.GetDirectoryName(trackPath);
+ string? trackDirectory = GetParentDirectoryPath(trackPath);
if (string.IsNullOrEmpty(trackDirectory))
return trackPath;
- if (!s_discDirectoryPattern.IsMatch(Path.GetFileName(trackDirectory)))
+ if (!s_discDirectoryPattern.IsMatch(GetLastSegment(trackDirectory)))
return trackDirectory;
- string? albumDirectory = Path.GetDirectoryName(trackDirectory);
+ string? albumDirectory = GetParentDirectoryPath(trackDirectory);
return string.IsNullOrEmpty(albumDirectory) ? trackDirectory : albumDirectory;
}
@@ -46,14 +57,40 @@ internal static class MusicLibraryPathStructure
///
/// The file system path of the track whose release type directory is retrieved.
/// The name of the on-disk release type directory, or when the library does not use one.
- public static string? GetReleaseTypeDirectoryName(string trackPath)
+ public string? GetReleaseTypeDirectoryName(string trackPath)
{
string albumDirectory = GetAlbumDirectory(trackPath);
- string? releaseTypeDirectory = Path.GetDirectoryName(albumDirectory);
+ string? releaseTypeDirectory = GetParentDirectoryPath(albumDirectory);
if (string.IsNullOrEmpty(releaseTypeDirectory))
return null;
- string releaseTypeName = Path.GetFileName(releaseTypeDirectory);
+ string releaseTypeName = GetLastSegment(releaseTypeDirectory);
return Enum.TryParse(releaseTypeName, ignoreCase: true, out MusicReleaseType _) ? releaseTypeName : null;
}
+
+ ///
+ /// Gets the parent directory of the file or directory stored at , using the path separator of the current platform.
+ ///
+ /// The path whose parent directory is retrieved.
+ /// The parent directory of the path, or when the path has no parent directory.
+ private string? GetParentDirectoryPath(string path)
+ {
+ string trimmedPath = path.TrimEnd(_pathService.PathSeparator);
+ int lastSeparatorIndex = trimmedPath.LastIndexOf(_pathService.PathSeparator);
+ if (lastSeparatorIndex <= 0)
+ return null;
+ return trimmedPath[..lastSeparatorIndex];
+ }
+
+ ///
+ /// Gets the last segment, the file or directory name, of , using the path separator of the current platform.
+ ///
+ /// The path whose last segment is retrieved.
+ /// The last segment of the path.
+ private string GetLastSegment(string path)
+ {
+ string trimmedPath = path.TrimEnd(_pathService.PathSeparator);
+ int lastSeparatorIndex = trimmedPath.LastIndexOf(_pathService.PathSeparator);
+ return lastSeparatorIndex < 0 ? trimmedPath : trimmedPath[(lastSeparatorIndex + 1)..];
+ }
}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs
index 862e4455..17ff4a58 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs
@@ -41,6 +41,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
private const int ENRICHMENT_PAGE_SIZE = 200; // The number of artists or albums that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger _logger;
+ private readonly MusicLibraryPathStructure _musicLibraryPathStructure;
///
/// The media library type that this artwork enricher supports.
@@ -52,10 +53,12 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
///
/// Injected factory for creating scopes in which services are requested.
/// Injected logger used to report the issues encountered while resolving the artwork.
- public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ /// Injected service used to derive the release type directory of the tracks from their file system paths.
+ public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger, MusicLibraryPathStructure musicLibraryPathStructure)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
+ _musicLibraryPathStructure = musicLibraryPathStructure;
}
///
@@ -367,7 +370,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
// The release type directory groups the artwork of the releases of the artist that share a title, so the album, the single and the live release of the same songs do not collide.
// It is read from the file system, because the structure on disk is the source of truth of the release type of an album.
- string? releaseTypeName = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(firstTrackPath);
+ string? releaseTypeName = _musicLibraryPathStructure.GetReleaseTypeDirectoryName(firstTrackPath);
return await EnrichArtworkAsync(
artworkLookup,
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs
index 9c40388c..1eaf37a6 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs
@@ -2,11 +2,11 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -22,11 +22,25 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
private const string UNKNOWN_ARTIST_NAME = "Unknown Artist";
private const string UNKNOWN_ALBUM_TITLE = "Unknown Album";
+ private readonly MusicLibraryPathStructure _musicLibraryPathStructure;
+ private readonly IPathService _pathService;
+
///
/// The media library type that this materializer supports.
///
public LibraryType SupportedLibraryType => LibraryType.Music;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service used to derive the album directory of the tracks from their file system paths.
+ /// Injected service used to derive the file name of a track from its file system path.
+ public MusicMediaLibraryScanItemMaterializer(MusicLibraryPathStructure musicLibraryPathStructure, IPathService pathService)
+ {
+ _musicLibraryPathStructure = musicLibraryPathStructure;
+ _pathService = pathService;
+ }
+
///
/// Resets the enrichment state of the tracks stored at the provided , together with their albums and artists.
///
@@ -86,11 +100,11 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
// A brand new artist is accumulated together with all its new albums, so that the whole aggregate is inserted in a single call.
ArtistEntity? newArtist = null;
- foreach (IGrouping albumGroup in artistGroup.GroupBy(stagedItem => MusicLibraryPathStructure.GetAlbumDirectory(stagedItem.Path), StringComparer.OrdinalIgnoreCase))
+ foreach (IGrouping albumGroup in artistGroup.GroupBy(stagedItem => _musicLibraryPathStructure.GetAlbumDirectory(stagedItem.Path), StringComparer.OrdinalIgnoreCase))
{
List albumStagedItems = [.. albumGroup];
string albumTitle = GetAlbumTitle(albumStagedItems[0]);
- string albumDirectory = MusicLibraryPathStructure.GetAlbumDirectory(albumStagedItems[0].Path);
+ string albumDirectory = _musicLibraryPathStructure.GetAlbumDirectory(albumStagedItems[0].Path);
Guid? musicBrainzReleaseId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseId).FirstOrDefault(musicBrainzId => musicBrainzId is not null);
Guid? musicBrainzReleaseGroupId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseGroupId).FirstOrDefault(musicBrainzId => musicBrainzId is not null);
Guid? musicBrainzReleaseArtistId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseArtistId).FirstOrDefault(musicBrainzId => musicBrainzId is not null);
@@ -276,7 +290,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
/// The Id of the album the track belongs to.
/// The staged music metadata item of the track.
/// The created track entity.
- private static TrackEntity CreateTrackEntity(Guid libraryId, Guid albumId, MusicLibraryScanItemMetadataEntity stagedItem)
+ private TrackEntity CreateTrackEntity(Guid libraryId, Guid albumId, MusicLibraryScanItemMetadataEntity stagedItem)
{
return new TrackEntity
{
@@ -284,7 +298,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
AlbumId = albumId,
LibraryId = libraryId,
Path = stagedItem.Path,
- Title = string.IsNullOrWhiteSpace(stagedItem.TrackTitle) ? Path.GetFileNameWithoutExtension(stagedItem.Path) : stagedItem.TrackTitle,
+ Title = string.IsNullOrWhiteSpace(stagedItem.TrackTitle) ? _pathService.GetFileNameWithoutExtension(stagedItem.Path) : stagedItem.TrackTitle,
TrackNumber = stagedItem.TrackNumber ?? 0,
DiscNumber = stagedItem.DiscNumber,
DurationInSeconds = stagedItem.DurationInSeconds,
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs
index b89f3a1b..f96b6d29 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs
@@ -310,7 +310,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
}
if (string.IsNullOrWhiteSpace(trackTitle))
- trackTitle = Path.GetFileNameWithoutExtension(path);
+ trackTitle = pathService.GetFileNameWithoutExtension(path);
return new MusicLibraryScanItemMetadataEntity
{
@@ -527,7 +527,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
return relativePath;
}
}
- return Path.GetFileName(path);
+ return pathService.GetFileName(path);
}
///
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs
index 735ae418..10993745 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs
@@ -14,7 +14,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using System;
using System.Collections.Generic;
-using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
@@ -176,9 +175,9 @@ internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanI
///
/// The file system path of the book.
/// The derived title.
- private static string GetTitleFromPath(string path)
+ private string GetTitleFromPath(string path)
{
- string fileName = Path.GetFileNameWithoutExtension(path);
+ string fileName = _pathService.GetFileNameWithoutExtension(path);
string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim();
return title.Length > 0 ? title : fileName;
}
@@ -201,6 +200,6 @@ internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanI
return relativePath;
}
}
- return Path.GetFileName(path);
+ return pathService.GetFileName(path);
}
}
diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs
index 13260534..a61eca6c 100644
--- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs
+++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs
@@ -817,4 +817,76 @@ public class PathServiceTests
Assert.False(result);
_mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any(), Arg.Any());
}
+
+ [Theory]
+ [InlineData('\\', @"C:\Music\Queen\Bohemian Rhapsody.mp3", "Bohemian Rhapsody.mp3")] // Windows separated path
+ [InlineData('/', "/music/queen/bohemian-rhapsody.mp3", "bohemian-rhapsody.mp3")] // Unix separated path
+ public void GetFileName_WhenPathHasDirectories_ShouldReturnTheLastSegment(char separator, string path, string expectedFileName)
+ {
+ // Arrange
+ _mockPathStrategy.PathSeparator.Returns(separator);
+
+ // Act
+ string result = _sut.GetFileName(path);
+
+ // Assert
+ Assert.Equal(expectedFileName, result);
+ }
+
+ [Theory]
+ [InlineData('\\')] // Windows separated path
+ [InlineData('/')] // Unix separated path
+ public void GetFileName_WhenPathHasNoDirectory_ShouldReturnThePath(char separator)
+ {
+ // Arrange
+ _mockPathStrategy.PathSeparator.Returns(separator);
+
+ // Act
+ string result = _sut.GetFileName("Bohemian Rhapsody.mp3");
+
+ // Assert
+ Assert.Equal("Bohemian Rhapsody.mp3", result);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public void GetFileName_WhenPathIsNullOrEmpty_ShouldReturnThePath(string? path)
+ {
+ // Act
+ string result = _sut.GetFileName(path!);
+
+ // Assert
+ Assert.Equal(path, result);
+ }
+
+ [Theory]
+ [InlineData('\\', @"C:\Music\Queen\Bohemian Rhapsody.mp3", "Bohemian Rhapsody")] // Windows separated path
+ [InlineData('/', "/music/queen/bohemian-rhapsody.mp3", "bohemian-rhapsody")] // Unix separated path
+ public void GetFileNameWithoutExtension_WhenPathHasDirectories_ShouldReturnTheFileNameWithoutItsExtension(char separator, string path, string expectedFileName)
+ {
+ // Arrange
+ _mockPathStrategy.PathSeparator.Returns(separator);
+
+ // Act
+ string result = _sut.GetFileNameWithoutExtension(path);
+
+ // Assert
+ Assert.Equal(expectedFileName, result);
+ }
+
+ [Theory]
+ [InlineData('\\')] // Windows separated path
+ [InlineData('/')] // Unix separated path
+ public void GetFileNameWithoutExtension_WhenFileNameHasNoExtension_ShouldReturnTheFileName(char separator)
+ {
+ // Arrange
+ _mockPathStrategy.PathSeparator.Returns(separator);
+
+ // Act
+ string result = _sut.GetFileNameWithoutExtension("Bohemian Rhapsody");
+
+ // Assert
+ Assert.Equal("Bohemian Rhapsody", result);
+ }
}
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs
index bc50eb7f..032222b0 100644
--- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs
@@ -1,5 +1,7 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
+using NSubstitute;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -11,121 +13,146 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.
[ExcludeFromCodeCoverage]
public class MusicLibraryPathStructureTests
{
- private const string ALBUM_DIRECTORY = @"C:\Music\Queen\A Night at the Opera";
- private const string TRACK_PATH = @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac";
+ private readonly IPathService _mockPathService;
+ private readonly MusicLibraryPathStructure _sut;
- [Fact]
- public void GetAlbumDirectory_WhenTheTrackIsInTheAlbumDirectory_ShouldReturnTheTrackDirectory()
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public MusicLibraryPathStructureTests()
{
- // Act
- string result = MusicLibraryPathStructure.GetAlbumDirectory(TRACK_PATH);
-
- // Assert
- Assert.Equal(ALBUM_DIRECTORY, result);
+ _mockPathService = Substitute.For();
+ _sut = new MusicLibraryPathStructure(_mockPathService);
}
[Theory]
- [InlineData("Disc 1")] // canonical disc directory name
- [InlineData("disc 2")] // lowercase disc directory name
- [InlineData("CD3")] // compact disc directory name
- [InlineData("disk4")] // disk directory name
- public void GetAlbumDirectory_WhenTheTrackIsInADiscDirectory_ShouldReturnTheParentAlbumDirectory(string discDirectoryName)
+ [InlineData('\\', @"C:\Music\Queen\A Night at the Opera", @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac")] // Windows separated path
+ [InlineData('/', "/music/queen/a-night-at-the-opera", "/music/queen/a-night-at-the-opera/bohemian-rhapsody.flac")] // Unix separated path
+ public void GetAlbumDirectory_WhenTheTrackIsInTheAlbumDirectory_ShouldReturnTheTrackDirectory(char separator, string albumDirectory, string trackPath)
{
// Arrange
- string trackPath = $@"{ALBUM_DIRECTORY}\{discDirectoryName}\Bohemian Rhapsody.flac";
+ _mockPathService.PathSeparator.Returns(separator);
// Act
- string result = MusicLibraryPathStructure.GetAlbumDirectory(trackPath);
+ string result = _sut.GetAlbumDirectory(trackPath);
// Assert
- Assert.Equal(ALBUM_DIRECTORY, result);
+ Assert.Equal(albumDirectory, result);
}
- [Fact]
- public void GetAlbumDirectory_WhenTheDirectoryIsNotADiscDirectory_ShouldReturnTheTrackDirectory()
+ [Theory]
+ [InlineData('\\', "Disc 1")] // canonical disc directory name, Windows separated path
+ [InlineData('\\', "disc 2")] // lowercase disc directory name, Windows separated path
+ [InlineData('\\', "CD3")] // compact disc directory name, Windows separated path
+ [InlineData('\\', "disk4")] // disk directory name, Windows separated path
+ [InlineData('/', "Disc 1")] // canonical disc directory name, Unix separated path
+ [InlineData('/', "disc 2")] // lowercase disc directory name, Unix separated path
+ [InlineData('/', "CD3")] // compact disc directory name, Unix separated path
+ [InlineData('/', "disk4")] // disk directory name, Unix separated path
+ public void GetAlbumDirectory_WhenTheTrackIsInADiscDirectory_ShouldReturnTheParentAlbumDirectory(char separator, string discDirectoryName)
{
// Arrange
- const string NON_DISC_TRACK_PATH = @"C:\Music\Queen\Live\Bohemian Rhapsody.flac";
+ _mockPathService.PathSeparator.Returns(separator);
+ string albumDirectory = string.Join(separator, "music", "queen", "a-night-at-the-opera");
+ string trackPath = string.Join(separator, albumDirectory, discDirectoryName, "bohemian-rhapsody.flac");
// Act
- string result = MusicLibraryPathStructure.GetAlbumDirectory(NON_DISC_TRACK_PATH);
+ string result = _sut.GetAlbumDirectory(trackPath);
// Assert
- Assert.Equal(@"C:\Music\Queen\Live", result);
+ Assert.Equal(albumDirectory, result);
+ }
+
+ [Theory]
+ [InlineData('\\')] // Windows separated path
+ [InlineData('/')] // Unix separated path
+ public void GetAlbumDirectory_WhenTheDirectoryIsNotADiscDirectory_ShouldReturnTheTrackDirectory(char separator)
+ {
+ // Arrange
+ _mockPathService.PathSeparator.Returns(separator);
+ string albumDirectory = string.Join(separator, "music", "queen", "live");
+ string trackPath = string.Join(separator, albumDirectory, "bohemian-rhapsody.flac");
+
+ // Act
+ string result = _sut.GetAlbumDirectory(trackPath);
+
+ // Assert
+ Assert.Equal(albumDirectory, result);
}
[Fact]
public void GetAlbumDirectory_WhenThePathIsNullOrEmpty_ShouldReturnTheProvidedPath()
{
// Act
- string nullResult = MusicLibraryPathStructure.GetAlbumDirectory(null!);
- string emptyResult = MusicLibraryPathStructure.GetAlbumDirectory(string.Empty);
+ string nullResult = _sut.GetAlbumDirectory(null!);
+ string emptyResult = _sut.GetAlbumDirectory(string.Empty);
// Assert
Assert.Null(nullResult);
Assert.Equal(string.Empty, emptyResult);
}
- [Fact]
- public void GetAlbumDirectory_WhenThePathHasNoDirectory_ShouldReturnTheProvidedPath()
+ [Theory]
+ [InlineData('\\')] // Windows separated path
+ [InlineData('/')] // Unix separated path
+ public void GetAlbumDirectory_WhenThePathHasNoDirectory_ShouldReturnTheProvidedPath(char separator)
{
// Arrange
+ _mockPathService.PathSeparator.Returns(separator);
const string FILE_NAME_ONLY = "Bohemian Rhapsody.flac";
// Act
- string result = MusicLibraryPathStructure.GetAlbumDirectory(FILE_NAME_ONLY);
+ string result = _sut.GetAlbumDirectory(FILE_NAME_ONLY);
// Assert
Assert.Equal(FILE_NAME_ONLY, result);
}
- [Fact]
- public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsAReleaseType_ShouldReturnIt()
+ [Theory]
+ [InlineData('\\', "Album")] // canonical release type directory, Windows separated path
+ [InlineData('\\', "album")] // lowercase release type directory, Windows separated path
+ [InlineData('/', "Album")] // canonical release type directory, Unix separated path
+ [InlineData('/', "album")] // lowercase release type directory, Unix separated path
+ public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsAReleaseType_ShouldReturnIt(char separator, string releaseTypeDirectoryName)
{
// Arrange
- const string RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\Album\A Night at the Opera\Bohemian Rhapsody.flac";
+ _mockPathService.PathSeparator.Returns(separator);
+ string trackPath = string.Join(separator, "music", "queen", releaseTypeDirectoryName, "a-night-at-the-opera", "bohemian-rhapsody.flac");
// Act
- string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(RELEASE_TYPE_TRACK_PATH);
+ string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
+
+ // Assert
+ Assert.Equal(releaseTypeDirectoryName, result);
+ }
+
+ [Theory]
+ [InlineData('\\')] // Windows separated path
+ [InlineData('/')] // Unix separated path
+ public void GetReleaseTypeDirectoryName_WhenTheAlbumIsMultiDisc_ShouldReturnTheReleaseTypeDirectory(char separator)
+ {
+ // Arrange
+ _mockPathService.PathSeparator.Returns(separator);
+ string trackPath = string.Join(separator, "music", "queen", "Album", "a-night-at-the-opera", "Disc 1", "bohemian-rhapsody.flac");
+
+ // Act
+ string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
// Assert
Assert.Equal("Album", result);
}
- [Fact]
- public void GetReleaseTypeDirectoryName_WhenTheReleaseTypeDirectoryIsLowercase_ShouldReturnIt()
+ [Theory]
+ [InlineData('\\')] // Windows separated path
+ [InlineData('/')] // Unix separated path
+ public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsNotAReleaseType_ShouldReturnNull(char separator)
{
// Arrange
- const string LOWERCASE_RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\album\A Night at the Opera\Bohemian Rhapsody.flac";
+ _mockPathService.PathSeparator.Returns(separator);
+ string trackPath = string.Join(separator, "music", "queen", "a-night-at-the-opera", "bohemian-rhapsody.flac");
// Act
- string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(LOWERCASE_RELEASE_TYPE_TRACK_PATH);
-
- // Assert
- Assert.Equal("album", result);
- }
-
- [Fact]
- public void GetReleaseTypeDirectoryName_WhenTheAlbumIsMultiDisc_ShouldReturnTheReleaseTypeDirectory()
- {
- // Arrange
- const string MULTI_DISC_TRACK_PATH = @"C:\Music\Queen\Album\A Night at the Opera\Disc 1\Bohemian Rhapsody.flac";
-
- // Act
- string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(MULTI_DISC_TRACK_PATH);
-
- // Assert
- Assert.Equal("Album", result);
- }
-
- [Fact]
- public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsNotAReleaseType_ShouldReturnNull()
- {
- // Arrange
- const string NON_RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac";
-
- // Act
- string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(NON_RELEASE_TYPE_TRACK_PATH);
+ string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
// Assert
Assert.Null(result);
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs
index 8c22d6a0..3c5e645b 100644
--- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs
@@ -22,6 +22,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
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;
@@ -60,6 +61,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
private readonly IMusicArtworkService _mockMusicArtworkService;
private readonly IFileHashService _mockFileHashService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
+ private readonly IPathService _mockPathService;
private readonly TestArtworkProvider _artistProvider;
private readonly TestArtworkProvider _albumProvider;
private readonly MusicMediaLibraryScanArtworkEnricher _sut;
@@ -108,7 +110,10 @@ public class MusicMediaLibraryScanArtworkEnricherTests
_mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any())
.Returns(ValueTask.CompletedTask);
- // the enricher resolves the keyed artwork providers from the scope of the service provider, and specializes them by the lookup they accept,
+ _mockPathService = Substitute.For();
+ _mockPathService.PathSeparator.Returns('/');
+
+ // The enricher resolves the keyed artwork providers from the scope of the service provider, and specializes them by the lookup they accept,
// so a real container is used to honor the keyed registration of the typed providers.
ServiceCollection services = new();
services.AddScoped(_ => _mockUnitOfWork);
@@ -119,7 +124,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
services.AddKeyedSingleton(_albumPluginId, _albumProvider);
_serviceProvider = services.BuildServiceProvider();
- _sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService(), NullLogger.Instance);
+ _sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService(), NullLogger.Instance, new MusicLibraryPathStructure(_mockPathService));
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs
index edb7e677..1b2a54ac 100644
--- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using NSubstitute;
using System;
@@ -27,6 +28,7 @@ public class MusicMediaLibraryScanItemMaterializerTests
private readonly IAlbumRepository _mockAlbumRepository;
private readonly ITrackRepository _mockTrackRepository;
private readonly IMusicLibraryScanItemMetadataRepository _mockStagedMetadataRepository;
+ private readonly IPathService _mockPathService;
private readonly MusicMediaLibraryScanItemMaterializer _sut;
private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = new();
private readonly List _insertedArtists = [];
@@ -63,7 +65,11 @@ public class MusicMediaLibraryScanItemMaterializerTests
_mockStagedMetadataRepository.DeleteByScanIdAsync(Arg.Any(), Arg.Any())
.Returns(Result.From(new Deleted()));
- _sut = new MusicMediaLibraryScanItemMaterializer();
+ _mockPathService = Substitute.For();
+ _mockPathService.PathSeparator.Returns('/');
+ _mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns("track");
+
+ _sut = new MusicMediaLibraryScanItemMaterializer(new MusicLibraryPathStructure(_mockPathService), _mockPathService);
}
[Fact]
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs
index ab24cd4b..5051be57 100644
--- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs
@@ -273,5 +273,7 @@ public class MusicMetadataExtractionJobTests
{
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(Arg.Any(), Arg.Any())
.Returns(Result.From>(paths));
+ _mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns("Bohemian Rhapsody");
+ _mockPathService.GetFileName(Arg.Any()).Returns("Bohemian Rhapsody.mp3");
}
}
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs
index 53222d92..19c71a21 100644
--- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs
@@ -86,8 +86,16 @@ public class MediaLibraryScanResultsSaveJobTests
// The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available.
ILibraryPathTemplateService mockPathTemplateService = Substitute.For();
mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty()));
+ IPathService mockPathService = Substitute.For();
+ mockPathService.GetFileName(Arg.Any()).Returns(callInfo => callInfo.Arg());
+ mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns(callInfo =>
+ {
+ string fileName = callInfo.Arg();
+ int lastDotIndex = fileName.LastIndexOf('.');
+ return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex];
+ });
_mockServiceProvider.GetService(typeof(IEnumerable))
- .Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, Substitute.For()) });
+ .Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, mockPathService) });
_mockDomainEventPublisher = Substitute.For();
_mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any())
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs
index 08b6719e..6e7cfab0 100644
--- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs
@@ -57,6 +57,7 @@ public class BooksMediaLibraryScanItemMaterializerTests
_mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>())
.Returns(Result.From(LibraryPathTemplate.Empty()));
_mockPathService.PathSeparator.Returns('\\');
+ _mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns("track");
_mockBookRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any())
.Returns(Result.From>([]));
_mockBookRepository.InsertAsync(Arg.Any(), Arg.Any())
@@ -75,6 +76,7 @@ public class BooksMediaLibraryScanItemMaterializerTests
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any())
.Returns(Result.From(library));
_mockPathService.IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music").Returns(false);
+ _mockPathService.GetFileName("C:\\MusicBackup\\track.epub").Returns("track.epub");
// Act
Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\MusicBackup\\track.epub"], CancellationToken.None);