mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Uses the file system path service for music and book path parsing
This commit is contained in:
1 parent
15d27adc1f
commit
09c31a4fe6
15 files changed
+303
-87
No files matched your search
+14
@@ -53,6 +53,20 @@ public interface IPathService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
Result<IEnumerable<PathSegment>> GoUpOneLevel(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the file or directory stored at <paramref name="path"/>, using the path separator of the current platform.
|
||||
/// </summary>
|
||||
/// <param name="path">The path whose name is retrieved.</param>
|
||||
/// <returns>The name of the file or directory stored at <paramref name="path"/>.</returns>
|
||||
string GetFileName(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the file stored at <paramref name="path"/> without its extension, using the path separator of the current platform.
|
||||
/// </summary>
|
||||
/// <param name="path">The path whose file name is retrieved.</param>
|
||||
/// <returns>The name of the file stored at <paramref name="path"/> without its extension.</returns>
|
||||
string GetFileNameWithoutExtension(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
|
||||
+26
@@ -105,6 +105,32 @@ public class PathService : IPathService
|
||||
return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the file or directory stored at <paramref name="path"/>, using the path separator of the current platform.
|
||||
/// </summary>
|
||||
/// <param name="path">The path whose name is retrieved.</param>
|
||||
/// <returns>The name of the file or directory stored at <paramref name="path"/>.</returns>
|
||||
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)..];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the file stored at <paramref name="path"/> without its extension, using the path separator of the current platform.
|
||||
/// </summary>
|
||||
/// <param name="path">The path whose file name is retrieved.</param>
|
||||
/// <returns>The name of the file stored at <paramref name="path"/> without its extension.</returns>
|
||||
public string GetFileNameWithoutExtension(string path)
|
||||
{
|
||||
string fileName = GetFileName(path);
|
||||
int lastDotIndex = fileName.LastIndexOf('.');
|
||||
return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
|
||||
@@ -130,6 +130,7 @@ public static class InfrastructureLayerServices
|
||||
services.AddTransient<IMediaLibraryScanArtworkEnricher, BooksMediaLibraryScanArtworkEnricher>();
|
||||
services.AddTransient<IMediaLibraryScanArtworkEnricher, MusicMediaLibraryScanArtworkEnricher>();
|
||||
|
||||
services.AddSingleton<MusicLibraryPathStructure>();
|
||||
|
||||
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
|
||||
|
||||
|
||||
+46
-9
@@ -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
|
||||
/// <summary>
|
||||
/// Derives the structure of a music library on disk from the file system path of a music file.
|
||||
/// </summary>
|
||||
internal static class MusicLibraryPathStructure
|
||||
internal sealed class MusicLibraryPathStructure
|
||||
{
|
||||
/// <summary>
|
||||
/// Matches the name of a directory that holds one disc of a multi-disc album, like "Disc 1" or "CD2".
|
||||
/// </summary>
|
||||
private static readonly Regex s_discDirectoryPattern = new(@"^(?:disk|disc|cd)\s*\d+$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
private readonly IPathService _pathService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicLibraryPathStructure"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pathService">Injected service used to determine the path separator of the current platform.</param>
|
||||
public MusicLibraryPathStructure(IPathService pathService)
|
||||
{
|
||||
_pathService = pathService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the on-disk directory of the album the track stored at <paramref name="trackPath"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="trackPath">The file system path of the track whose album directory is retrieved.</param>
|
||||
/// <returns>The file system path of the album directory, or the directory of the track when it cannot be resolved.</returns>
|
||||
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
|
||||
/// </summary>
|
||||
/// <param name="trackPath">The file system path of the track whose release type directory is retrieved.</param>
|
||||
/// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the library does not use one.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the parent directory of the file or directory stored at <paramref name="path"/>, using the path separator of the current platform.
|
||||
/// </summary>
|
||||
/// <param name="path">The path whose parent directory is retrieved.</param>
|
||||
/// <returns>The parent directory of the path, or <see langword="null"/> when the path has no parent directory.</returns>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last segment, the file or directory name, of <paramref name="path"/>, using the path separator of the current platform.
|
||||
/// </summary>
|
||||
/// <param name="path">The path whose last segment is retrieved.</param>
|
||||
/// <returns>The last segment of the path.</returns>
|
||||
private string GetLastSegment(string path)
|
||||
{
|
||||
string trimmedPath = path.TrimEnd(_pathService.PathSeparator);
|
||||
int lastSeparatorIndex = trimmedPath.LastIndexOf(_pathService.PathSeparator);
|
||||
return lastSeparatorIndex < 0 ? trimmedPath : trimmedPath[(lastSeparatorIndex + 1)..];
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -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<MusicMediaLibraryScanArtworkEnricher> _logger;
|
||||
private readonly MusicLibraryPathStructure _musicLibraryPathStructure;
|
||||
|
||||
/// <summary>
|
||||
/// The media library type that this artwork enricher supports.
|
||||
@@ -52,10 +53,12 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while resolving the artwork.</param>
|
||||
public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger<MusicMediaLibraryScanArtworkEnricher> logger)
|
||||
/// <param name="musicLibraryPathStructure">Injected service used to derive the release type directory of the tracks from their file system paths.</param>
|
||||
public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger<MusicMediaLibraryScanArtworkEnricher> logger, MusicLibraryPathStructure musicLibraryPathStructure)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
_musicLibraryPathStructure = musicLibraryPathStructure;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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,
|
||||
|
||||
+19
-5
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The media library type that this materializer supports.
|
||||
/// </summary>
|
||||
public LibraryType SupportedLibraryType => LibraryType.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanItemMaterializer"/> class.
|
||||
/// </summary>
|
||||
/// <param name="musicLibraryPathStructure">Injected service used to derive the album directory of the tracks from their file system paths.</param>
|
||||
/// <param name="pathService">Injected service used to derive the file name of a track from its file system path.</param>
|
||||
public MusicMediaLibraryScanItemMaterializer(MusicLibraryPathStructure musicLibraryPathStructure, IPathService pathService)
|
||||
{
|
||||
_musicLibraryPathStructure = musicLibraryPathStructure;
|
||||
_pathService = pathService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the enrichment state of the tracks stored at the provided <paramref name="paths"/>, together with their albums and artists.
|
||||
/// </summary>
|
||||
@@ -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<string, MusicLibraryScanItemMetadataEntity> albumGroup in artistGroup.GroupBy(stagedItem => MusicLibraryPathStructure.GetAlbumDirectory(stagedItem.Path), StringComparer.OrdinalIgnoreCase))
|
||||
foreach (IGrouping<string, MusicLibraryScanItemMetadataEntity> albumGroup in artistGroup.GroupBy(stagedItem => _musicLibraryPathStructure.GetAlbumDirectory(stagedItem.Path), StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
List<MusicLibraryScanItemMetadataEntity> 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
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="stagedItem">The staged music metadata item of the track.</param>
|
||||
/// <returns>The created track entity.</returns>
|
||||
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,
|
||||
|
||||
+2
-2
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+3
-4
@@ -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
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <returns>The derived title.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+72
@@ -817,4 +817,76 @@ public class PathServiceTests
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
+88
-61
@@ -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()
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicLibraryPathStructureTests"/> class.
|
||||
/// </summary>
|
||||
public MusicLibraryPathStructureTests()
|
||||
{
|
||||
// Act
|
||||
string result = MusicLibraryPathStructure.GetAlbumDirectory(TRACK_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ALBUM_DIRECTORY, result);
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_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);
|
||||
|
||||
+7
-2
@@ -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<ArtistMetadataLookupDto> _artistProvider;
|
||||
private readonly TestArtworkProvider<AlbumMetadataLookupDto> _albumProvider;
|
||||
private readonly MusicMediaLibraryScanArtworkEnricher _sut;
|
||||
@@ -108,7 +110,10 @@ public class MusicMediaLibraryScanArtworkEnricherTests
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.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<IPathService>();
|
||||
_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<IUnitOfWork>(_ => _mockUnitOfWork);
|
||||
@@ -119,7 +124,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_albumPluginId, _albumProvider);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanArtworkEnricher>.Instance);
|
||||
_sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanArtworkEnricher>.Instance, new MusicLibraryPathStructure(_mockPathService));
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
|
||||
+7
-1
@@ -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<ArtistEntity> _insertedArtists = [];
|
||||
@@ -63,7 +65,11 @@ public class MusicMediaLibraryScanItemMaterializerTests
|
||||
_mockStagedMetadataRepository.DeleteByScanIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Deleted()));
|
||||
|
||||
_sut = new MusicMediaLibraryScanItemMaterializer();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('/');
|
||||
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("track");
|
||||
|
||||
_sut = new MusicMediaLibraryScanItemMaterializer(new MusicLibraryPathStructure(_mockPathService), _mockPathService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+2
@@ -273,5 +273,7 @@ public class MusicMetadataExtractionJobTests
|
||||
{
|
||||
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(paths));
|
||||
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("Bohemian Rhapsody");
|
||||
_mockPathService.GetFileName(Arg.Any<string>()).Returns("Bohemian Rhapsody.mp3");
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -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<ILibraryPathTemplateService>();
|
||||
mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
|
||||
IPathService mockPathService = Substitute.For<IPathService>();
|
||||
mockPathService.GetFileName(Arg.Any<string>()).Returns(callInfo => callInfo.Arg<string>());
|
||||
mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns(callInfo =>
|
||||
{
|
||||
string fileName = callInfo.Arg<string>();
|
||||
int lastDotIndex = fileName.LastIndexOf('.');
|
||||
return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex];
|
||||
});
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanItemMaterializer>))
|
||||
.Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, Substitute.For<IPathService>()) });
|
||||
.Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, mockPathService) });
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
|
||||
+2
@@ -57,6 +57,7 @@ public class BooksMediaLibraryScanItemMaterializerTests
|
||||
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>())
|
||||
.Returns(Result.From(LibraryPathTemplate.Empty()));
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("track");
|
||||
_mockBookRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
@@ -75,6 +76,7 @@ public class BooksMediaLibraryScanItemMaterializerTests
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockPathService.IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music").Returns(false);
|
||||
_mockPathService.GetFileName("C:\\MusicBackup\\track.epub").Returns("track.epub");
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\MusicBackup\\track.epub"], CancellationToken.None);
|
||||
|
||||
Reference in new issue
Block a user