Uses the file system path service for music and book path parsing

This commit is contained in:
BinaryAlley committed 2026-10-10 15:48:41 +03:00
1 parent 15d27adc1f
commit 09c31a4fe6
15 files changed
+303 -87

No files matched your search

@@ -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>
@@ -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>();
@@ -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)..];
}
}
@@ -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,
@@ -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,
@@ -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>
@@ -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);
}
}