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

@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using System.Diagnostics;
#endregion
@@ -17,6 +18,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
/// <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="PathTemplateParts">The ordered parts of the template describing the structure of the media library on disk.</param>
[DebuggerDisplay("Title: {Title}")]
public record AddLibraryCommand(
string? Title,
@@ -27,5 +29,6 @@ public record AddLibraryCommand(
bool IsLocked,
bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
bool ShouldSkipUnchangedDirectoriesDuringScan,
LibraryPathTemplatePartDto[]? PathTemplateParts
) : ICommand;
@@ -11,6 +11,8 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
@@ -39,6 +41,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
private readonly IEnvironmentContext _environmentContext;
private readonly IAuthorizationService _authorizationService;
private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore;
private readonly ILibraryPathTemplateService _pathTemplateService;
private readonly IValidator<AddLibraryCommand> _validator;
/// <summary>
@@ -49,6 +52,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="providerConfigurationStore">Injected store of the provider configurations of the media libraries.</param>
/// <param name="pathTemplateService">Injected service for validating and resolving the path templates of the media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public AddLibraryCommandHandler(
@@ -57,6 +61,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IMediaLibraryProviderConfigurationStore providerConfigurationStore,
ILibraryPathTemplateService pathTemplateService,
IUnitOfWork unitOfWork,
IValidator<AddLibraryCommand> validator)
{
@@ -66,6 +71,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
_environmentContext = environmentContext;
_authorizationService = authorizationService;
_providerConfigurationStore = providerConfigurationStore;
_pathTemplateService = pathTemplateService;
_validator = validator;
}
@@ -108,11 +114,24 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
return DomainErrors.Library.CoverFileMustBeAnImage;
}
LibraryType libraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// A library always carries a path template: the one provided by the user, or the ideal structure of the library type as its default.
Result<IReadOnlyList<LibraryPathPart>> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts();
if (pathTemplatePartsResult.IsFailure)
return pathTemplatePartsResult.Errors;
LibraryPathTemplate pathTemplate = command.PathTemplateParts is null
? _pathTemplateService.GetDefaultTemplate(libraryType)
: LibraryPathTemplate.Create(pathTemplatePartsResult.Value);
Result<Success> validatePathTemplateResult = _pathTemplateService.Validate(libraryType, pathTemplate);
if (validatePathTemplateResult.IsFailure)
return validatePathTemplateResult.Errors;
// Create a domain library object.
Result<Library> createLibraryResult = Library.Create(
UserId.Create(userId),
command.Title!,
Enum.Parse<LibraryType>(command.LibraryType!),
libraryType,
command.ContentLocations!,
Optional<string>.FromNullable(command.CoverImage),
command.IsEnabled,
@@ -120,6 +139,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
command.CanDownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
pathTemplate,
[]
);
@@ -134,7 +154,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
if (insertLibraryResult.IsFailure)
return insertLibraryResult.Errors;
Result<Success> ensureProviderConfigurationsResult = await _providerConfigurationStore.EnsureProviderConfigurationsAsync(
createLibraryResult.Value.Id.Value, Enum.Parse<LibraryType>(command.LibraryType!), cancellationToken).ConfigureAwait(false);
createLibraryResult.Value.Id.Value, libraryType, cancellationToken).ConfigureAwait(false);
if (ensureProviderConfigurationsResult.IsFailure)
return ensureProviderConfigurationsResult.Errors;
@@ -41,5 +41,17 @@ public class AddLibraryCommandValidator : AbstractValidator<AddLibraryCommand>
.WithError(Errors.Library.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Library.TitleMustBeMaximum255CharactersLong);
RuleForEach(command => command.PathTemplateParts)
.ChildRules(part =>
{
part.RuleFor(pathPart => pathPart.Kind)
.NotEmpty()
.WithError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
part.RuleFor(pathPart => pathPart.Representation)
.NotEmpty()
.When(pathPart => !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase))
.WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
});
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using System;
using System.Diagnostics;
#endregion
@@ -20,6 +21,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary
/// <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="PathTemplateParts">The ordered parts of the template describing the structure of the media library on disk.</param>
[DebuggerDisplay("Title: {Title}")]
public record UpdateLibraryCommand(
Guid Id,
@@ -32,5 +34,6 @@ public record UpdateLibraryCommand(
bool IsLocked,
bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
bool ShouldSkipUnchangedDirectoriesDuringScan,
LibraryPathTemplatePartDto[]? PathTemplateParts
) : ICommand;
@@ -12,6 +12,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
@@ -43,6 +44,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore;
private readonly ILibraryPathTemplateService _pathTemplateService;
private readonly IValidator<UpdateLibraryCommand> _validator;
/// <summary>
@@ -53,6 +55,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="providerConfigurationStore">Injected store of the provider configurations of the media libraries.</param>
/// <param name="pathTemplateService">Injected service for validating and resolving the path templates of the media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateLibraryCommandHandler(
@@ -61,6 +64,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IMediaLibraryProviderConfigurationStore providerConfigurationStore,
ILibraryPathTemplateService pathTemplateService,
IUnitOfWork unitOfWork,
IValidator<UpdateLibraryCommand> validator)
{
@@ -70,6 +74,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_providerConfigurationStore = providerConfigurationStore;
_pathTemplateService = pathTemplateService;
_validator = validator;
}
@@ -124,6 +129,18 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
// Create a domain library object.
LibraryType newLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// A library always carries a path template: the one provided by the user, or the ideal structure of the library type as its default.
Result<IReadOnlyList<LibraryPathPart>> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts();
if (pathTemplatePartsResult.IsFailure)
return pathTemplatePartsResult.Errors;
LibraryPathTemplate pathTemplate = command.PathTemplateParts is null
? _pathTemplateService.GetDefaultTemplate(newLibraryType)
: LibraryPathTemplate.Create(pathTemplatePartsResult.Value);
Result<Success> validatePathTemplateResult = _pathTemplateService.Validate(newLibraryType, pathTemplate);
if (validatePathTemplateResult.IsFailure)
return validatePathTemplateResult.Errors;
Result<Library> createLibraryResult = Library.Create(
LibraryId.Create(command.Id),
UserId.Create(command.OwnerId),
@@ -136,6 +153,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
command.CanDownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
pathTemplate,
[.. getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
);
if (createLibraryResult.IsFailure)
@@ -53,5 +53,17 @@ public class UpdateLibraryCommandValidator : AbstractValidator<UpdateLibraryComm
.WithError(Errors.Library.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Library.TitleMustBeMaximum255CharactersLong);
RuleForEach(command => command.PathTemplateParts)
.ChildRules(part =>
{
part.RuleFor(pathPart => pathPart.Kind)
.NotEmpty()
.WithError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
part.RuleFor(pathPart => pathPart.Representation)
.NotEmpty()
.When(pathPart => !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase))
.WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
});
}
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
/// <summary>
/// Query for getting the path parts available for a media library type.
/// </summary>
/// <param name="LibraryType">The media library type whose available path parts are retrieved.</param>
[DebuggerDisplay("LibraryType: {LibraryType}")]
public record GetLibraryPathTemplatePartsQuery(
string? LibraryType
) : IQuery;
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
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;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
/// <summary>
/// Handler for the query to get the path template catalog available for a media library type.
/// </summary>
public class GetLibraryPathTemplatePartsQueryHandler : IQueryHandler<GetLibraryPathTemplatePartsQuery, Result<LibraryPathTemplateCatalogResponse>>
{
private readonly IReadOnlyList<ILibraryPathPartCatalog> _catalogs;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsQueryHandler"/> class.
/// </summary>
/// <param name="catalogs">Injected path part catalogs of the supported media library types.</param>
public GetLibraryPathTemplatePartsQueryHandler(IEnumerable<ILibraryPathPartCatalog> catalogs)
{
_catalogs = [.. catalogs];
}
/// <summary>
/// Handles the query to get the path template catalog available for a media library type.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the path template catalog, or an error message.
/// </returns>
public Task<Result<LibraryPathTemplateCatalogResponse>> HandleAsync(GetLibraryPathTemplatePartsQuery query, CancellationToken cancellationToken)
{
// the library type travels as a string taken from the route, and is matched against the enum the same way the create and update
// library commands do, so that a malformed type is reported as an unknown library type instead of silently returning an empty catalog.
if (!Enum.TryParse(query.LibraryType, ignoreCase: true, out LibraryType libraryType))
return Task.FromResult<Result<LibraryPathTemplateCatalogResponse>>(DomainErrors.Library.UnknownLibraryType);
// only the catalog registered for the requested library type applies, so the parts and the default structure offered to the user are
// type aware (music libraries get artist and release parts, book libraries get author and title parts, and so on).
ILibraryPathPartCatalog? catalog = _catalogs.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
if (catalog is null)
// a library type without a catalog has no structure to describe, so an empty catalog is returned, which the client uses to hide the editor.
return Task.FromResult(Result<LibraryPathTemplateCatalogResponse>.Success(new LibraryPathTemplateCatalogResponse([], [])));
// the selectable parts describe what the user can drop into the template, together with the value type and the default on-disk representation of each part.
List<LibraryPathPartDefinitionResponse> parts =
[
.. catalog.GetPartDefinitions().Select(definition => new LibraryPathPartDefinitionResponse(
definition.Kind.ToString(),
definition.ValueType.ToString(),
definition.DefaultRepresentation,
definition.IsOptionalByDefault))
];
// the default template parts describe the ideal structure the application expects, pre-filled in the editor so the user only edits what deviates.
List<LibraryPathTemplatePartResponse> defaultTemplateParts =
[
.. catalog.GetDefaultTemplate().Parts.Select(part => new LibraryPathTemplatePartResponse(part.Kind.ToString(), part.Representation, part.IsOptional))
];
return Task.FromResult(Result<LibraryPathTemplateCatalogResponse>.Success(new LibraryPathTemplateCatalogResponse(parts, defaultTemplateParts)));
}
}