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,13 @@
namespace Lumina.Application.Common.DTO.MediaLibrary.Management;
/// <summary>
/// Data transfer object for one part of the path template of a media library, carried by the commands that create or update a media library.
/// </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>
public record LibraryPathTemplatePartDto(
string? Kind,
string? Representation,
bool IsOptional
);
@@ -45,6 +45,11 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
/// </summary>
public required ICollection<LibraryContentLocationEntity> ContentLocations { get; init; } = [];
/// <summary>
/// Gets the ordered parts of the template describing the structure of the media library on disk.
/// </summary>
public ICollection<LibraryPathTemplatePartEntity> PathTemplateParts { get; init; } = [];
/// <summary>
/// Gets the list of scans of the media library.
/// </summary>
@@ -87,6 +92,12 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? ArtworkProvidersConfigurationFingerprint { get; set; }
/// <summary>
/// Gets or sets the fingerprint of the path template of the media library, used to detect whether the template
/// changed since the last scan, and thus whether the metadata needs to be derived from the paths again.
/// </summary>
public string? PathTemplateFingerprint { get; set; }
/// <summary>
/// Gets the user that owns the media library.
/// </summary>
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
/// <summary>
/// Repository entity for one part of the path template of a media library.
/// </summary>
[DebuggerDisplay("Kind: {Kind}; Position: {Position}")]
public class LibraryPathTemplatePartEntity
{
/// <summary>
/// Gets or sets the zero based position of the part in the path template.
/// </summary>
public required int Position { get; set; }
/// <summary>
/// Gets or sets the kind of the path part.
/// </summary>
public required LibraryPathPartKind Kind { get; set; }
/// <summary>
/// Gets or sets the literal text or the value mask of the path part.
/// </summary>
public required string Representation { get; set; }
/// <summary>
/// Gets or sets whether the path part can be absent from the path.
/// </summary>
public required bool IsOptional { get; set; }
}
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
@@ -26,7 +28,8 @@ public static class AddMediaLibraryRequestMapping
request.IsLocked,
request.CanDownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan
request.ShouldSkipUnchangedDirectoriesDuringScan,
request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray()
);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Contracts.Requests.MediaLibrary.Management;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Extension methods for converting <see cref="GetLibraryPathTemplatePartsRequest"/>.
/// </summary>
public static class GetLibraryPathTemplatePartsRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetLibraryPathTemplatePartsQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetLibraryPathTemplatePartsQuery ToQuery(this GetLibraryPathTemplatePartsRequest request)
{
return new GetLibraryPathTemplatePartsQuery(
request.LibraryType
);
}
}
@@ -36,6 +36,9 @@ public static class LibraryEntityMapping
repositoryEntity.CanDownloadMetadataFromWeb,
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
[.. repositoryEntity.PathTemplateParts
.OrderBy(part => part.Position)
.Select(part => new LibraryPathTemplatePartResponse(part.Kind.ToString(), part.Representation, part.IsOptional))],
repositoryEntity.CreatedOnUtc,
repositoryEntity.UpdatedOnUtc
);
@@ -50,6 +53,10 @@ public static class LibraryEntityMapping
/// </returns>
public static Result<Library> ToDomainEntity(this LibraryEntity repositoryEntity)
{
Result<LibraryPathTemplate> pathTemplateResult = BuildPathTemplate(repositoryEntity.PathTemplateParts);
if (pathTemplateResult.IsFailure)
return pathTemplateResult.Errors;
return Library.Create(
LibraryId.Create(repositoryEntity.Id),
UserId.Create(repositoryEntity.UserId),
@@ -62,10 +69,31 @@ public static class LibraryEntityMapping
repositoryEntity.CanDownloadMetadataFromWeb,
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
pathTemplateResult.Value,
[.. repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
);
}
/// <summary>
/// Builds the path template of a media library from its ordered stored parts.
/// </summary>
/// <param name="parts">The stored parts of the path template.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the built <see cref="LibraryPathTemplate"/>, or an error message.
/// </returns>
private static Result<LibraryPathTemplate> BuildPathTemplate(IEnumerable<LibraryPathTemplatePartEntity> parts)
{
List<LibraryPathPart> orderedParts = [];
foreach (LibraryPathTemplatePartEntity part in parts.OrderBy(part => part.Position))
{
Result<LibraryPathPart> partResult = LibraryPathPart.Create(part.Kind, part.Representation, part.IsOptional);
if (partResult.IsFailure)
return partResult.Errors;
orderedParts.Add(partResult.Value);
}
return LibraryPathTemplate.Create(orderedParts);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="Library"/>.
/// </summary>
@@ -26,6 +26,13 @@ public static class LibraryMapping
LibraryType = domainEntity.LibraryType,
UserId = domainEntity.UserId.Value,
ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })],
PathTemplateParts = [.. domainEntity.PathTemplate.Parts.Select((part, index) => new LibraryPathTemplatePartEntity
{
Kind = part.Kind,
Representation = part.Representation,
IsOptional = part.IsOptional,
Position = index
})],
CoverImage = domainEntity.CoverImage.HasValue ? domainEntity.CoverImage.Value : null,
IsEnabled = domainEntity.IsEnabled,
IsLocked = domainEntity.IsLocked,
@@ -0,0 +1,44 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Extension methods for converting <see cref="LibraryPathTemplatePartDto"/>.
/// </summary>
public static class LibraryPathTemplatePartDtoMapping
{
/// <summary>
/// Converts the provided path template parts to their domain path parts.
/// </summary>
/// <param name="parts">The path template parts to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the converted domain path parts, or an error message.
/// </returns>
public static Result<IReadOnlyList<LibraryPathPart>> ToDomainParts(this IEnumerable<LibraryPathTemplatePartDto>? parts)
{
List<LibraryPathPart> domainParts = [];
if (parts is null)
return domainParts;
foreach (LibraryPathTemplatePartDto part in parts)
{
if (!Enum.TryParse(part.Kind, ignoreCase: true, out LibraryPathPartKind kind))
return DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType;
Result<LibraryPathPart> partResult = LibraryPathPart.Create(kind, part.Representation, part.IsOptional);
if (partResult.IsFailure)
return partResult.Errors;
domainParts.Add(partResult.Value);
}
return domainParts;
}
}
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
@@ -28,7 +30,8 @@ public static class UpdateLibraryRequestMapping
request.IsLocked,
request.CanDownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan
request.ShouldSkipUnchangedDirectoriesDuringScan,
request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray()
);
}
}
@@ -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)));
}
}