Adds dynamic path templates for media libraries, so that the scanner can derive the meaning of each path part

This commit is contained in:
BinaryAlley committed 2026-10-05 18:42:00 +03:00
1 parent 62b0e9297a
commit ca4f308b0a
86 files changed
+7406 -151

No files matched your search

@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate;
/// <summary>
/// Catalog of the path parts available for music libraries, together with the default structure the application expects on disk.
/// </summary>
public sealed class MusicLibraryPathPartCatalog : ILibraryPathPartCatalog
{
/// <summary>
/// Gets the media library type that this catalog supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Music;
/// <summary>
/// Gets the parts that can be used in the path template of a music library.
/// </summary>
/// <returns>The available path parts.</returns>
public IReadOnlyList<LibraryPathPartDefinition> GetPartDefinitions()
{
return
[
new(LibraryPathPartKind.Literal, LibraryPathValueType.None, string.Empty, false),
new(LibraryPathPartKind.Separator, LibraryPathValueType.None, string.Empty, false),
new(LibraryPathPartKind.Artist, LibraryPathValueType.Text, "{0}", false),
new(LibraryPathPartKind.ReleaseType, LibraryPathValueType.Enum, "{0}", false),
new(LibraryPathPartKind.ReleaseYear, LibraryPathValueType.Year, "{0}", false),
new(LibraryPathPartKind.ReleaseName, LibraryPathValueType.Text, "{0}", false),
new(LibraryPathPartKind.TrackNumber, LibraryPathValueType.Integer, "{0:00}", false),
new(LibraryPathPartKind.TrackName, LibraryPathValueType.Text, "{0}", false),
new(LibraryPathPartKind.Extension, LibraryPathValueType.Text, "{0}", false),
new(LibraryPathPartKind.DiscNumber, LibraryPathValueType.Integer, "{0:00}", true)
];
}
/// <summary>
/// Gets the default path template of a music library, describing the ideal structure the application expects. The disc segment is
/// optional, so that both single disc and multi disc releases are understood.
/// </summary>
/// <returns>The default path template.</returns>
public LibraryPathTemplate GetDefaultTemplate()
{
return LibraryPathTemplate.Create(
[
LibraryPathPart.Create(LibraryPathPartKind.Artist, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value,
LibraryPathPart.Create(LibraryPathPartKind.ReleaseType, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value,
LibraryPathPart.Create(LibraryPathPartKind.ReleaseYear, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.ReleaseName, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Separator, null, true).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, "Disk ", true).Value,
LibraryPathPart.Create(LibraryPathPartKind.DiscNumber, "{0:00}", true).Value,
LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value,
LibraryPathPart.Create(LibraryPathPartKind.TrackNumber, "{0:00}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.TrackName, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, ".", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Extension, "{0}", false).Value
]);
}
}
@@ -0,0 +1,121 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the metadata derived from the file system path of a music library item.
/// </summary>
public class MusicLibraryPathMetadata : ValueObject
{
/// <summary>
/// Gets the name of the artist derived from the path, if applicable.
/// </summary>
public Optional<string> ArtistName { get; }
/// <summary>
/// Gets the type of the release derived from the path, if applicable.
/// </summary>
public Optional<MusicReleaseType> ReleaseType { get; }
/// <summary>
/// Gets the release year derived from the path, if applicable.
/// </summary>
public Optional<int> ReleaseYear { get; }
/// <summary>
/// Gets the name of the release derived from the path, if applicable.
/// </summary>
public Optional<string> ReleaseName { get; }
/// <summary>
/// Gets the number of the track derived from the path, if applicable.
/// </summary>
public Optional<int> TrackNumber { get; }
/// <summary>
/// Gets the number of the disc the track belongs to, derived from the path, if applicable.
/// </summary>
public Optional<int> DiscNumber { get; }
/// <summary>
/// Gets the title of the track derived from the path, if applicable.
/// </summary>
public Optional<string> TrackTitle { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryPathMetadata"/> class.
/// </summary>
/// <param name="artistName">The name of the artist derived from the path, if applicable.</param>
/// <param name="releaseType">The type of the release derived from the path, if applicable.</param>
/// <param name="releaseYear">The release year derived from the path, if applicable.</param>
/// <param name="releaseName">The name of the release derived from the path, if applicable.</param>
/// <param name="trackNumber">The number of the track derived from the path, if applicable.</param>
/// <param name="discNumber">The number of the disc derived from the path, if applicable.</param>
/// <param name="trackTitle">The title of the track derived from the path, if applicable.</param>
private MusicLibraryPathMetadata(
Optional<string> artistName,
Optional<MusicReleaseType> releaseType,
Optional<int> releaseYear,
Optional<string> releaseName,
Optional<int> trackNumber,
Optional<int> discNumber,
Optional<string> trackTitle)
{
ArtistName = artistName;
ReleaseType = releaseType;
ReleaseYear = releaseYear;
ReleaseName = releaseName;
TrackNumber = trackNumber;
DiscNumber = discNumber;
TrackTitle = trackTitle;
}
/// <summary>
/// Creates a new instance of the <see cref="MusicLibraryPathMetadata"/> class from the values captured from a path template.
/// </summary>
/// <param name="parsedPath">The values captured from the path of the music library item.</param>
/// <returns>The metadata derived from the captured values.</returns>
public static MusicLibraryPathMetadata FromParsedLibraryPath(ParsedLibraryPath parsedPath)
{
Optional<MusicReleaseType> releaseType = Optional<MusicReleaseType>.None();
Optional<string> releaseTypeValue = parsedPath.GetString(LibraryPathPartKind.ReleaseType);
if (releaseTypeValue.HasValue)
{
// An unrecognized release type folder does not prevent the rest of the path from being derived, it is simply reported as the catch-all type.
releaseType = Enum.TryParse(releaseTypeValue.Value, ignoreCase: true, out MusicReleaseType parsedReleaseType)
? Optional<MusicReleaseType>.Some(parsedReleaseType)
: Optional<MusicReleaseType>.Some(MusicReleaseType.Other);
}
return new MusicLibraryPathMetadata(
parsedPath.GetString(LibraryPathPartKind.Artist),
releaseType,
parsedPath.GetInt(LibraryPathPartKind.ReleaseYear),
parsedPath.GetString(LibraryPathPartKind.ReleaseName),
parsedPath.GetInt(LibraryPathPartKind.TrackNumber),
parsedPath.GetInt(LibraryPathPartKind.DiscNumber),
parsedPath.GetString(LibraryPathPartKind.TrackName));
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
yield return ArtistName;
yield return ReleaseType;
yield return ReleaseYear;
yield return ReleaseName;
yield return TrackNumber;
yield return DiscNumber;
yield return TrackTitle;
}
}
@@ -76,6 +76,11 @@ public class Library : AggregateRoot<LibraryId>
/// </summary>
public bool ShouldSkipUnchangedDirectoriesDuringScan { get; private set; }
/// <summary>
/// Gets the template describing the structure of the media library on disk, always populated, with the ideal structure of the library type as its default.
/// </summary>
public LibraryPathTemplate PathTemplate { get; private set; }
/// <summary>
/// Gets the list of objects representing the file system paths that make up the media library.
/// </summary>
@@ -100,6 +105,7 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="canDownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
/// <param name="pathTemplate">The template describing the structure of the media library on disk.</param>
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
private Library(
LibraryId id,
@@ -113,6 +119,7 @@ public class Library : AggregateRoot<LibraryId>
bool canDownloadMetadataFromWeb,
bool shouldSaveMetadataInMediaDirectories,
bool shouldSkipUnchangedDirectoriesDuringScan,
LibraryPathTemplate pathTemplate,
List<ScanId> scanIds) : base(id)
{
UserId = userId;
@@ -125,6 +132,7 @@ public class Library : AggregateRoot<LibraryId>
CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb;
ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories;
ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan;
PathTemplate = pathTemplate;
_scanIds = scanIds;
}
@@ -141,6 +149,7 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="canDownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
/// <param name="pathTemplate">The template describing the structure of the media library on disk.</param>
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
@@ -156,6 +165,7 @@ public class Library : AggregateRoot<LibraryId>
bool canDownloadMetadataFromWeb,
bool shouldSaveMetadataInMediaDirectories,
bool shouldSkipUnchangedDirectoriesDuringScan,
LibraryPathTemplate pathTemplate,
List<ScanId> scanIds)
{
List<FileSystemPathId> tempContentLocations = [];
@@ -179,6 +189,7 @@ public class Library : AggregateRoot<LibraryId>
canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
pathTemplate,
scanIds
);
}
@@ -197,6 +208,7 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="canDownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
/// <param name="pathTemplate">The template describing the structure of the media library on disk.</param>
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
@@ -213,6 +225,7 @@ public class Library : AggregateRoot<LibraryId>
bool canDownloadMetadataFromWeb,
bool shouldSaveMetadataInMediaDirectories,
bool shouldSkipUnchangedDirectoriesDuringScan,
LibraryPathTemplate pathTemplate,
List<ScanId> scanIds)
{
List<FileSystemPathId> tempContentLocations = [];
@@ -236,6 +249,7 @@ public class Library : AggregateRoot<LibraryId>
canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
pathTemplate,
scanIds
);
}
@@ -0,0 +1,91 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for one part of a media library path template.
/// </summary>
/// <remarks>
/// A part is either a <see cref="LibraryPathPartKind.Separator"/>, which renders the platform path separator, a <see cref="LibraryPathPartKind.Literal"/>, which renders its
/// <see cref="Representation"/> verbatim, or a typed value part, whose <see cref="Representation"/> is a mask that contains a single <c>{0}</c> placeholder where the captured value goes,
/// optionally with a fixed digit width for numeric kinds, like <c>{0:00}</c>.
/// </remarks>
public class LibraryPathPart : ValueObject
{
/// <summary>
/// Matches the value placeholder of a typed part, capturing the optional fixed digit width.
/// </summary>
private static readonly Regex s_placeholderRegex = new(@"\{0(?::(?<width>0+))?\}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>
/// Gets the kind of the path part.
/// </summary>
public LibraryPathPartKind Kind { get; }
/// <summary>
/// Gets the representation of the path part, which is the literal text for a literal part, and the value mask for a typed part.
/// </summary>
public string Representation { get; }
/// <summary>
/// Gets whether the path part can be absent from the path.
/// </summary>
public bool IsOptional { get; }
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathPart"/> class.
/// </summary>
/// <param name="kind">The kind of the path part.</param>
/// <param name="representation">The literal text or the value mask of the path part.</param>
/// <param name="isOptional">Whether the path part can be absent from the path.</param>
private LibraryPathPart(LibraryPathPartKind kind, string representation, bool isOptional)
{
Kind = kind;
Representation = representation;
IsOptional = isOptional;
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryPathPart"/> class.
/// </summary>
/// <param name="kind">The kind of the path part.</param>
/// <param name="representation">The literal text or the value mask of the path part.</param>
/// <param name="isOptional">Whether the path part can be absent from the path.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="LibraryPathPart"/>, or an error message.
/// </returns>
public static Result<LibraryPathPart> Create(LibraryPathPartKind kind, string? representation, bool isOptional)
{
// a separator carries no representation, it always renders the platform path separator.
if (kind == LibraryPathPartKind.Separator)
return new LibraryPathPart(kind, string.Empty, isOptional);
if (string.IsNullOrWhiteSpace(representation))
return DomainErrors.Library.PathTemplateLiteralCannotBeEmpty;
// typed parts must carry exactly one value placeholder, so that the position of the captured value is unambiguous.
if (kind != LibraryPathPartKind.Literal && s_placeholderRegex.Matches(representation).Count != 1)
return DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder;
return new LibraryPathPart(kind, representation, isOptional);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
yield return Kind;
yield return Representation;
yield return IsOptional;
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the ordered sequence of parts that make up the structure of a media library on disk.
/// </summary>
public class LibraryPathTemplate : ValueObject
{
private readonly List<LibraryPathPart> _parts;
/// <summary>
/// Gets the ordered parts that make up the path template.
/// </summary>
public IReadOnlyList<LibraryPathPart> Parts => _parts.AsReadOnly();
/// <summary>
/// Gets whether the template carries no parts, which means no path derived metadata can be obtained from it.
/// </summary>
public bool IsEmpty => _parts.Count == 0;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathTemplate"/> class.
/// </summary>
/// <param name="parts">The ordered parts that make up the path template.</param>
private LibraryPathTemplate(List<LibraryPathPart> parts)
{
_parts = parts;
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryPathTemplate"/> class.
/// </summary>
/// <param name="parts">The ordered parts that make up the path template.</param>
/// <returns>The created path template.</returns>
public static LibraryPathTemplate Create(IEnumerable<LibraryPathPart> parts)
{
return new LibraryPathTemplate([.. parts]);
}
/// <summary>
/// Creates an empty path template, used by the library types that have no path part catalog yet.
/// </summary>
/// <returns>The created empty path template.</returns>
public static LibraryPathTemplate Empty()
{
return new LibraryPathTemplate([]);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
return _parts;
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
/// <summary>
/// Interface for the catalog of the path parts available for a given media library type.
/// </summary>
public interface ILibraryPathPartCatalog
{
/// <summary>
/// Gets the media library type that this catalog supports.
/// </summary>
LibraryType SupportedLibraryType { get; }
/// <summary>
/// Gets the parts that can be used in the path template of the supported library type.
/// </summary>
/// <returns>The available path parts.</returns>
IReadOnlyList<LibraryPathPartDefinition> GetPartDefinitions();
/// <summary>
/// Gets the default path template of the supported library type, describing the ideal structure the application expects.
/// </summary>
/// <returns>The default path template.</returns>
LibraryPathTemplate GetDefaultTemplate();
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
/// <summary>
/// Interface for the service that validates media library path templates and derives metadata from paths using them.
/// </summary>
public interface ILibraryPathTemplateService
{
/// <summary>
/// Gets the default path template of the provided <paramref name="libraryType"/>, or an empty template when the type has no path part catalog yet.
/// </summary>
/// <param name="libraryType">The media library type whose default path template is retrieved.</param>
/// <returns>The default path template.</returns>
LibraryPathTemplate GetDefaultTemplate(LibraryType libraryType);
/// <summary>
/// Validates the provided <paramref name="template"/> against the catalog of the provided <paramref name="libraryType"/>.
/// </summary>
/// <param name="libraryType">The media library type the template belongs to.</param>
/// <param name="template">The path template to validate.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Result<Success> Validate(LibraryType libraryType, LibraryPathTemplate template);
/// <summary>
/// Derives the metadata of a media library item from its relative path, using the provided <paramref name="template"/>.
/// </summary>
/// <param name="libraryType">The media library type the template belongs to.</param>
/// <param name="template">The path template used to parse the path.</param>
/// <param name="relativePath">The path of the media library item, relative to the root of its content location.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the derived metadata, or an error. A successful result whose value is <see langword="null"/>
/// means the path does not match the template.
/// </returns>
Result<ParsedLibraryPath?> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator);
}
@@ -0,0 +1,197 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
/// <summary>
/// Validates media library path templates and derives metadata from paths using them.
/// </summary>
public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
{
/// <summary>
/// Matches the value placeholder of a typed part, capturing the optional fixed digit width.
/// </summary>
private static readonly Regex s_placeholderRegex = new(@"\{0(?::(?<width>0+))?\}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IReadOnlyList<ILibraryPathPartCatalog> _catalogs;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathTemplateService"/> class.
/// </summary>
/// <param name="catalogs">The path part catalogs of all the supported media library types.</param>
public LibraryPathTemplateService(IEnumerable<ILibraryPathPartCatalog> catalogs)
{
_catalogs = [.. catalogs];
}
/// <summary>
/// Gets the default path template of the provided <paramref name="libraryType"/>, or an empty template when the type has no path part catalog yet.
/// </summary>
/// <param name="libraryType">The media library type whose default path template is retrieved.</param>
/// <returns>The default path template.</returns>
public LibraryPathTemplate GetDefaultTemplate(LibraryType libraryType)
{
return ResolveCatalog(libraryType)?.GetDefaultTemplate() ?? LibraryPathTemplate.Empty();
}
/// <summary>
/// Validates the provided <paramref name="template"/> against the catalog of the provided <paramref name="libraryType"/>.
/// </summary>
/// <param name="libraryType">The media library type the template belongs to.</param>
/// <param name="template">The path template to validate.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> Validate(LibraryType libraryType, LibraryPathTemplate template)
{
if (template.IsEmpty)
return Result.Success;
ILibraryPathPartCatalog? catalog = ResolveCatalog(libraryType);
if (catalog is null)
return DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType;
HashSet<LibraryPathPartKind> supportedKinds = [.. catalog.GetPartDefinitions().Select(definition => definition.Kind)];
foreach (LibraryPathPart part in template.Parts)
if (!supportedKinds.Contains(part.Kind))
return DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType;
return Result.Success;
}
/// <summary>
/// Derives the metadata of a media library item from its relative path, using the provided <paramref name="template"/>.
/// </summary>
/// <param name="libraryType">The media library type the template belongs to.</param>
/// <param name="template">The path template used to parse the path.</param>
/// <param name="relativePath">The path of the media library item, relative to the root of its content location.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the derived metadata, or an error. A successful result whose value is <see langword="null"/>
/// means the path does not match the template.
/// </returns>
public Result<ParsedLibraryPath?> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator)
{
if (string.IsNullOrWhiteSpace(relativePath) || template.IsEmpty)
return Result<ParsedLibraryPath?>.Success(null);
Result<Success> validationResult = Validate(libraryType, template);
if (validationResult.IsFailure)
return validationResult.Errors;
ILibraryPathPartCatalog catalog = ResolveCatalog(libraryType)!;
Dictionary<LibraryPathPartKind, LibraryPathPartDefinition> definitions = catalog.GetPartDefinitions()
.ToDictionary(definition => definition.Kind);
Regex pattern = BuildPattern(template, definitions, pathSeparator);
Match match = pattern.Match(relativePath);
if (!match.Success)
return Result<ParsedLibraryPath?>.Success(null);
Dictionary<LibraryPathPartKind, string> values = [];
foreach (LibraryPathPart part in template.Parts)
{
if (part.Kind == LibraryPathPartKind.Literal || part.Kind == LibraryPathPartKind.Separator)
continue;
// a kind can legitimately appear more than once, like the title and the author appearing both in the directory and in the file name,
// so the first non-empty capture is kept.
if (values.ContainsKey(part.Kind))
continue;
Group group = match.Groups[part.Kind.ToString()];
if (!group.Success)
continue;
string? value = group.Captures.Cast<Capture>().Select(capture => capture.Value).FirstOrDefault(captured => !string.IsNullOrWhiteSpace(captured));
if (!string.IsNullOrWhiteSpace(value))
values[part.Kind] = value;
}
return Result<ParsedLibraryPath?>.Success(ParsedLibraryPath.Create(values));
}
/// <summary>
/// Resolves the catalog of the provided <paramref name="libraryType"/>.
/// </summary>
/// <param name="libraryType">The media library type whose catalog is resolved.</param>
/// <returns>The resolved catalog, or <see langword="null"/> when the type has no catalog.</returns>
private ILibraryPathPartCatalog? ResolveCatalog(LibraryType libraryType)
{
return _catalogs.FirstOrDefault(catalog => catalog.SupportedLibraryType == libraryType);
}
/// <summary>
/// Builds the regular expression that matches the provided <paramref name="template"/>.
/// </summary>
/// <param name="template">The path template to compile.</param>
/// <param name="definitions">The available part definitions of the template's library type.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>The compiled regular expression.</returns>
private static Regex BuildPattern(LibraryPathTemplate template, IReadOnlyDictionary<LibraryPathPartKind, LibraryPathPartDefinition> definitions, char pathSeparator)
{
StringBuilder patternBuilder = new("^");
int index = 0;
while (index < template.Parts.Count)
{
int runStart = index;
bool isOptionalRun = template.Parts[index].IsOptional;
do
{
index++;
}
while (index < template.Parts.Count && template.Parts[index].IsOptional == isOptionalRun);
StringBuilder runBuilder = new();
for (int runIndex = runStart; runIndex < index; runIndex++)
runBuilder.Append(BuildFragment(template.Parts[runIndex], definitions, pathSeparator));
if (isOptionalRun)
patternBuilder.Append("(?:").Append(runBuilder).Append(")?");
else
patternBuilder.Append(runBuilder);
}
patternBuilder.Append('$');
return new Regex(patternBuilder.ToString(), RegexOptions.Compiled | RegexOptions.CultureInvariant);
}
/// <summary>
/// Builds the regular expression fragment of a single path part.
/// </summary>
/// <param name="part">The path part to compile.</param>
/// <param name="definitions">The available part definitions of the template's library type.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>The compiled regular expression fragment.</returns>
private static string BuildFragment(LibraryPathPart part, IReadOnlyDictionary<LibraryPathPartKind, LibraryPathPartDefinition> definitions, char pathSeparator)
{
if (part.Kind == LibraryPathPartKind.Separator)
return Regex.Escape(pathSeparator.ToString());
if (part.Kind == LibraryPathPartKind.Literal)
return Regex.Escape(part.Representation);
LibraryPathPartDefinition definition = definitions[part.Kind];
Match placeholder = s_placeholderRegex.Match(part.Representation);
string prefix = part.Representation[..placeholder.Index];
string suffix = part.Representation[(placeholder.Index + placeholder.Length)..];
Group width = placeholder.Groups["width"];
// a fixed width narrows the capture to an exact number of digits, otherwise the base pattern of the value type is used.
string valuePattern = width.Success ? $@"\d{{{width.Value.Length}}}" : GetValuePattern(definition.ValueType);
return Regex.Escape(prefix) + $"(?<{part.Kind}>{valuePattern})" + Regex.Escape(suffix);
}
/// <summary>
/// Gets the base regular expression pattern of the provided <paramref name="valueType"/>.
/// </summary>
/// <param name="valueType">The value type whose base pattern is retrieved.</param>
/// <returns>The base regular expression pattern.</returns>
private static string GetValuePattern(LibraryPathValueType valueType)
{
return valueType switch
{
LibraryPathValueType.Year => @"\d{4}",
LibraryPathValueType.Integer => @"\d+",
_ => @"[^/\\]+"
};
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Value Object that describes one available part of a media library path template, for a given library type.
/// </summary>
public sealed class LibraryPathPartDefinition : ValueObject
{
/// <summary>
/// Gets the kind of the described part.
/// </summary>
public LibraryPathPartKind Kind { get; }
/// <summary>
/// Gets the value type captured by the described part.
/// </summary>
public LibraryPathValueType ValueType { get; }
/// <summary>
/// Gets the default representation of the described part, pre-filled for the user when the part is added to a template.
/// </summary>
public string DefaultRepresentation { get; }
/// <summary>
/// Gets whether the described part is optional by default.
/// </summary>
public bool IsOptionalByDefault { get; }
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathPartDefinition"/> class.
/// </summary>
/// <param name="kind">The kind of the described part.</param>
/// <param name="valueType">The value type captured by the described part.</param>
/// <param name="defaultRepresentation">The default representation of the described part.</param>
/// <param name="isOptionalByDefault">Whether the described part is optional by default.</param>
public LibraryPathPartDefinition(LibraryPathPartKind kind, LibraryPathValueType valueType, string defaultRepresentation, bool isOptionalByDefault)
{
Kind = kind;
ValueType = valueType;
DefaultRepresentation = defaultRepresentation;
IsOptionalByDefault = isOptionalByDefault;
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
yield return Kind;
yield return ValueType;
yield return DefaultRepresentation;
yield return IsOptionalByDefault;
}
}
@@ -0,0 +1,89 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Value Object for the values captured from the relative path of a media library item, keyed by the semantic kind of the path part that produced them.
/// </summary>
public class ParsedLibraryPath : ValueObject
{
private readonly IReadOnlyDictionary<LibraryPathPartKind, string> _values;
/// <summary>
/// Gets the captured values, keyed by their part kind.
/// </summary>
public IReadOnlyDictionary<LibraryPathPartKind, string> Values => _values;
/// <summary>
/// Initializes a new instance of the <see cref="ParsedLibraryPath"/> class.
/// </summary>
/// <param name="values">The captured values, keyed by their part kind.</param>
private ParsedLibraryPath(IReadOnlyDictionary<LibraryPathPartKind, string> values)
{
_values = values;
}
/// <summary>
/// Creates a new instance of the <see cref="ParsedLibraryPath"/> class.
/// </summary>
/// <param name="values">The captured values, keyed by their part kind.</param>
/// <returns>The created parsed path.</returns>
public static ParsedLibraryPath Create(IReadOnlyDictionary<LibraryPathPartKind, string> values)
{
return new ParsedLibraryPath(values);
}
/// <summary>
/// Gets the captured value of the part of the provided <paramref name="kind"/>.
/// </summary>
/// <param name="kind">The kind of the part whose value is retrieved.</param>
/// <returns>An <see cref="Optional{TValue}"/> containing the captured value, or no value when the part was not captured.</returns>
public Optional<string> GetString(LibraryPathPartKind kind)
{
return _values.TryGetValue(kind, out string? value) && !string.IsNullOrWhiteSpace(value)
? Optional<string>.Some(value.Trim())
: Optional<string>.None();
}
/// <summary>
/// Gets the captured integer value of the part of the provided <paramref name="kind"/>.
/// </summary>
/// <param name="kind">The kind of the part whose value is retrieved.</param>
/// <returns>An <see cref="Optional{TValue}"/> containing the captured integer, or no value when the part was not captured or is not an integer.</returns>
public Optional<int> GetInt(LibraryPathPartKind kind)
{
return _values.TryGetValue(kind, out string? value) && int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed)
? Optional<int>.Some(parsed)
: Optional<int>.None();
}
/// <summary>
/// Gets the captured values as a dictionary, for callers that need to iterate over all of them.
/// </summary>
/// <returns>The captured values keyed by part kind.</returns>
public IReadOnlyDictionary<LibraryPathPartKind, string> ToDictionary()
{
return _values.ToDictionary(pair => pair.Key, pair => pair.Value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
// the captured values are stored in a dictionary, so they are ordered by their kind to keep equality independent of insertion order.
foreach (KeyValuePair<LibraryPathPartKind, string> capturedValue in _values.OrderBy(capturedValue => capturedValue.Key))
{
yield return capturedValue.Key;
yield return capturedValue.Value;
}
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate;
/// <summary>
/// Catalog of the path parts available for book libraries, together with the default structure the application expects on disk.
/// </summary>
/// <remarks>
/// The default structure mirrors the Calibre library layout, where each book lives in an author directory and a book directory named after
/// the title and the Calibre identifier, holding the book file named after the title and the author.
/// </remarks>
public sealed class BookLibraryPathPartCatalog : ILibraryPathPartCatalog
{
/// <summary>
/// Gets the media library type that this catalog supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Book;
/// <summary>
/// Gets the parts that can be used in the path template of a book library.
/// </summary>
/// <returns>The available path parts.</returns>
public IReadOnlyList<LibraryPathPartDefinition> GetPartDefinitions()
{
return
[
new(LibraryPathPartKind.Literal, LibraryPathValueType.None, string.Empty, false),
new(LibraryPathPartKind.Separator, LibraryPathValueType.None, string.Empty, false),
new(LibraryPathPartKind.Author, LibraryPathValueType.Text, "{0}", false),
new(LibraryPathPartKind.Title, LibraryPathValueType.Text, "{0}", false),
new(LibraryPathPartKind.Series, LibraryPathValueType.Text, "{0}", true),
new(LibraryPathPartKind.SeriesNumber, LibraryPathValueType.Integer, "{0}", true),
new(LibraryPathPartKind.BookId, LibraryPathValueType.Integer, "{0}", false),
new(LibraryPathPartKind.Extension, LibraryPathValueType.Text, "{0}", false)
];
}
/// <summary>
/// Gets the default path template of a book library, describing the Calibre structure the application expects.
/// </summary>
/// <returns>The default path template.</returns>
public LibraryPathTemplate GetDefaultTemplate()
{
return LibraryPathTemplate.Create(
[
LibraryPathPart.Create(LibraryPathPartKind.Author, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Title, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, " (", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.BookId, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, ")", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Title, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Author, "{0}", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Literal, ".", false).Value,
LibraryPathPart.Create(LibraryPathPartKind.Extension, "{0}", false).Value
]);
}
}