Replaces FluentValidation and Mediator command/queries handling with custom implementations.

This commit is contained in:
BinaryAlley committed 2026-08-13 08:53:06 -07:00
1 parent 9a5c7473f9
commit 2d1c6b1ab8
297 files changed
+3619 -3045

No files matched your search

@@ -1,53 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentValidation;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Behaviors;
/// <summary>
/// Represents a validation behavior in the Mediator pipeline for handling requests and responses.
/// </summary>
/// <typeparam name="TRequest">The type representing a request. It should implement <see cref="IRequest{TResponse}"/>.</typeparam>
/// <typeparam name="TResponse">The type representing a response. It should implement <see cref="IErrorOr"/> interface.</typeparam>
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
where TResponse : IErrorOr
{
private readonly IValidator<TRequest>? _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidationBehavior{TRequest, TResponse}"/> class.
/// </summary>
/// <param name="validator">The validator used in this behavior pipeline for the Mediator commands and queries.</param>
public ValidationBehavior(IValidator<TRequest>? validator = null)
{
_validator = validator;
}
/// <summary>
/// Pipeline handler. Perform any additional behavior and await the <paramref name="next"/> delegate as necessary.
/// </summary>
/// <param name="request">Incoming request.</param>
/// <param name="next">Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask<TResponse> Handle(TRequest request, MessageHandlerDelegate<TRequest, TResponse> next, CancellationToken cancellationToken)
{
// if there is no validator, just invoke the handler
if (_validator is null)
return await next(request, cancellationToken).ConfigureAwait(false);
// before the handler of the command is executed
FluentValidation.Results.ValidationResult validationResult = await _validator.ValidateAsync(request, cancellationToken).ConfigureAwait(false);
// if there are no validation errors, invoke the command handler
if (validationResult.IsValid)
return await next(request, cancellationToken).ConfigureAwait(false);
// after the command handler is executed
List<Error> errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage));
// the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic
// this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!)
return (dynamic)errors;
}
}
@@ -1,7 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Behaviors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -25,44 +22,39 @@ public static class ApplicationLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
{
// register Mediator
// register the Mediator publisher used for publishing domain events
services.AddMediator(options =>
{
options.ServiceLifetime = ServiceLifetime.Scoped;
});
// register the validation behavior
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
// register fluent validators
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
Type[] handlers =
Type[] handlerContractTypes =
[
typeof(CQRS.ICommandHandler<,>),
typeof(CQRS.IQueryHandler<,>),
typeof(Infrastructure.Validation.IValidator<>),
];
IEnumerable<Type> types = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => !type.IsInterface && !type.IsAbstract);
IEnumerable<Type> concreteTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition);
var registrations = types
.SelectMany(type => type.GetInterfaces(),
(implementation, service) => new { Service = service, Implmentation = implementation })
.Where(type => type.Service.IsGenericType && handlers.Contains(type.Service.GetGenericTypeDefinition()));
var handlerRegistrations = concreteTypes
.SelectMany(implementation => implementation.GetInterfaces(),
(implementation, contract) => new { Contract = contract, Implementation = implementation })
.Where(registration => registration.Contract.IsGenericType && handlerContractTypes.Contains(registration.Contract.GetGenericTypeDefinition()));
foreach (var registration in registrations)
foreach (var registration in handlerRegistrations)
{
if (!services.Any(service => service.ServiceType == registration.Service))
{
if (registration.Service.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
services.AddSingleton(registration.Service, registration.Implmentation);
else
services.AddScoped(registration.Service, registration.Implmentation);
}
if (services.Any(service => service.ServiceType == registration.Contract))
continue;
if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
services.AddSingleton(registration.Contract, registration.Implementation);
else
services.AddScoped(registration.Contract, registration.Implementation);
}
return services;
}
}
@@ -20,7 +20,7 @@ public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="propertySelector">A function that selects the property to validate from the request instance.</param>
/// <returns>An <see cref="IRuleBuilder{TRequest, TProperty}"/> instance to configure the rule fluently.</returns>
protected IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(Func<TRequest, TProperty> propertySelector)
public IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(Func<TRequest, TProperty> propertySelector)
{
ValidationRule<TRequest, TProperty> rule = new(propertySelector);
_rules.Add(rule);
@@ -33,7 +33,7 @@ public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
/// <typeparam name="TItem">The type of the items in the collection being validated.</typeparam>
/// <param name="collectionSelector">A function that selects the collection to validate from the request instance.</param>
/// <returns>An <see cref="IRuleBuilder{TRequest, TItem}"/> instance to configure the per-item rule fluently.</returns>
protected IRuleBuilder<TRequest, TItem> RuleForEach<TItem>(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
public IRuleBuilder<TRequest, TItem> RuleForEach<TItem>(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
{
ValidationRuleForEach<TRequest, TItem> rule = new(collectionSelector);
_rules.Add(rule);
@@ -19,6 +19,13 @@ public interface IRuleBuilder<TRequest, TProperty>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate);
/// <summary>
/// Specifies a condition that both the request instance and the property value must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the request instance together with the property value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> Must(Func<TRequest, TProperty, bool> predicate);
/// <summary>
/// Specifies a condition that must be met for the validation rule to be executed.
/// </summary>
@@ -32,4 +39,11 @@ public interface IRuleBuilder<TRequest, TProperty>
/// <param name="error">The specific error to return upon failure.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> WithError(Error error);
/// <summary>
/// Defines nested validation rules for the complex property being validated.
/// </summary>
/// <param name="configure">An action used to configure the inline validator for the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> ChildRules(Action<AbstractValidator<TProperty>> configure);
}
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
#endregion
namespace Lumina.Application.Common.Infrastructure.Validation;
/// <summary>
/// Concrete <see cref="AbstractValidator{TRequest}"/> used to declare validation rules inline for nested complex properties.
/// </summary>
/// <typeparam name="TRequest">The type of the request (command or query) to be validated.</typeparam>
public class InlineValidator<TRequest> : AbstractValidator<TRequest>
{
}
@@ -14,10 +14,28 @@ namespace Lumina.Application.Common.Infrastructure.Validation;
internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TRequest>, IRuleBuilder<TRequest, TProperty>
{
private readonly Func<TRequest, TProperty> _propertySelector;
// Predicates and their errors are kept in two parallel lists (rather than a single list of tuples)
// so that Must() can append cheaply and WithError() can patch the *last* entry by index, without
// having to rebuild a composite struct each time.
private readonly List<Func<TProperty, bool>> _predicates = [];
private Error error = Error.Validation();
private readonly List<Error> _predicateErrors = [];
// instance-aware predicates get their own separate pair of lists instead of being merged into the
// lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty).
// Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape.
private readonly List<Func<TRequest, TProperty, bool>> _instanceAwarePredicates = [];
private readonly List<Error> _instanceAwarePredicateErrors = [];
private Error currentError = Error.Validation();
private Func<TRequest, bool>? condition;
// Tracks which list WithError() should patch, since it doesn't know on its own whether the
// most recent Must() call went to the plain-predicate list or the instance-aware list.
private bool lastAddedPredicateIsInstanceAware;
private AbstractValidator<TProperty>? _childValidator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidationRule{TRequest, TProperty}"/> class.
/// </summary>
@@ -35,6 +53,25 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
public IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate)
{
_predicates.Add(predicate);
// Every predicate is paired with whatever error is "current" at the time it's added, so that a
// subsequent WithError() call has something concrete to overwrite via index lookup.
_predicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = false;
return this;
}
/// <summary>
/// Adds a condition that the request instance together with the property must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the request instance together with the property value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> Must(Func<TRequest, TProperty, bool> predicate)
{
// This overload exists for cross-field rules (e.g. "EndDate must be after StartDate") where
// the check can't be expressed from the property value alone and needs the whole request.
_instanceAwarePredicates.Add(predicate);
_instanceAwarePredicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = true;
return this;
}
@@ -56,7 +93,35 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> WithError(Error error)
{
this.error = error;
// Callers might pass in an error created with the wrong factory (e.g. Error.NotFound()) by mistake.
// Rebuilding it as Error.Validation() here guarantees every error surfaced by this class is
// consistently typed as a validation error, regardless of what the caller supplied.
Error validationError = Error.Validation(description: error.Description);
currentError = validationError;
// WithError() is meant to apply to the predicate that was *just* added via Must(), not to all
// predicates registered so far. Since Must() can target either parallel-list pair, we use the
// flag set by the last Must() call to figure out which list's last slot to overwrite.
if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
_instanceAwarePredicateErrors[^1] = validationError;
else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
_predicateErrors[^1] = validationError;
return this;
}
/// <summary>
/// Defines nested validation rules for the complex property being validated.
/// </summary>
/// <param name="configure">An action used to configure the inline validator for the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> ChildRules(Action<AbstractValidator<TProperty>> configure)
{
// Lets a rule delegate to a fully separate validator for a complex nested object (e.g. validating
// an Address property's own fields) instead of forcing every nested check to be flattened into
// Must() predicates on this rule.
InlineValidator<TProperty> childValidator = new();
configure(childValidator);
_childValidator = childValidator;
return this;
}
@@ -64,7 +129,7 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
/// Evaluates all configured predicates against the specified request instance.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>The <see cref="Error"/> if any predicate fails; empty if the rule passes.</returns>
/// <returns>The <see cref="Error"/> of every predicate that fails; empty if the rule passes.</returns>
public IEnumerable<Error> Validate(TRequest instance)
{
// evaluate the condition first, if it returns false, skip validation entirely.
@@ -73,13 +138,19 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
TProperty value = _propertySelector(instance);
foreach (Func<TProperty, bool> predicate in _predicates)
{
if (!predicate(value))
{
yield return error;
yield break;
}
}
// Deliberately does NOT stop at the first failure: every failing predicate contributes its own error,
// so a caller sees the full set of problems for // this property in one pass instead of having to fix
// and resubmit one error at a time.
for (int index = 0; index < _predicates.Count; index++)
if (!_predicates[index](value))
yield return _predicateErrors[index];
for (int index = 0; index < _instanceAwarePredicates.Count; index++)
if (!_instanceAwarePredicates[index](instance, value))
yield return _instanceAwarePredicateErrors[index];
if (_childValidator is not null && value is not null)
foreach (Error childError in _childValidator.Validate(value))
yield return childError;
}
}
@@ -15,8 +15,13 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
{
private readonly Func<TRequest, IEnumerable<TItem>?> _collectionSelector;
private readonly List<Func<TItem, bool>> _predicates = [];
private Error error = Error.Validation();
private readonly List<Error> _predicateErrors = [];
private readonly List<Func<TRequest, TItem, bool>> _instanceAwarePredicates = [];
private readonly List<Error> _instanceAwarePredicateErrors = [];
private Error currentError = Error.Validation();
private Func<TRequest, bool>? condition;
private bool lastAddedPredicateIsInstanceAware;
private AbstractValidator<TItem>? _childValidator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidationRuleForEach{TRequest, TItem}"/> class.
@@ -35,6 +40,21 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
public IRuleBuilder<TRequest, TItem> Must(Func<TItem, bool> predicate)
{
_predicates.Add(predicate);
_predicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = false;
return this;
}
/// <summary>
/// Adds a condition that the request instance together with each item must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the request instance together with each item value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> Must(Func<TRequest, TItem, bool> predicate)
{
_instanceAwarePredicates.Add(predicate);
_instanceAwarePredicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = true;
return this;
}
@@ -56,7 +76,26 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> WithError(Error error)
{
this.error = error;
// validation rules always produce validation errors, regardless of the error type of the source error
Error validationError = Error.Validation(description: error.Description);
currentError = validationError;
if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
_instanceAwarePredicateErrors[^1] = validationError;
else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
_predicateErrors[^1] = validationError;
return this;
}
/// <summary>
/// Defines nested validation rules for each item of the collection being validated.
/// </summary>
/// <param name="configure">An action used to configure the inline validator for each item.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> ChildRules(Action<AbstractValidator<TItem>> configure)
{
InlineValidator<TItem> childValidator = new();
configure(childValidator);
_childValidator = childValidator;
return this;
}
@@ -64,7 +103,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
/// Evaluates all configured predicates against each item in the collection.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>One <see cref="Error"/> per item that fails a predicate; empty if every item passes.</returns>
/// <returns>One <see cref="Error"/> per failing predicate, per item; empty if every item passes.</returns>
public IEnumerable<Error> Validate(TRequest instance)
{
// evaluate the condition first, if it returns false, skip validation entirely.
@@ -77,14 +116,17 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
foreach (TItem item in collection)
{
foreach (Func<TItem, bool> predicate in _predicates)
{
if (!predicate(item))
{
yield return error;
break;
}
}
for (int index = 0; index < _predicates.Count; index++)
if (!_predicates[index](item))
yield return _predicateErrors[index];
for (int index = 0; index < _instanceAwarePredicates.Count; index++)
if (!_instanceAwarePredicates[index](instance, item))
yield return _instanceAwarePredicateErrors[index];
if (_childValidator is not null && item is not null)
foreach (Error childError in _childValidator.Validate(item))
yield return childError;
}
}
}
@@ -1,7 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Application.Common.Utilities;
@@ -38,6 +39,33 @@ public static class ValidatorUtilities
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the decimal property is greater than the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, decimal> GreaterThan<TRequest>(this IRuleBuilder<TRequest, decimal> ruleBuilder, decimal valueToCompare)
{
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable decimal property is greater than the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, decimal?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, decimal?> ruleBuilder, decimal valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the time span property is greater than the specified value.
/// </summary>
@@ -50,13 +78,54 @@ public static class ValidatorUtilities
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the integer property is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int valueToCompare)
{
return ruleBuilder.Must(value => value >= valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable integer property is greater than or equal to the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int?> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable decimal property is greater than or equal to the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, decimal?> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, decimal?> ruleBuilder, decimal valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the property is not <see langword="null"/>.
/// </summary>
/// <remarks>
/// This rule checks reference/nullable-value nullness only. Combine with
/// <see cref="NotEmpty{TRequest}(IRuleBuilder{TRequest, string})"/> or
/// <see cref="NotEmpty{TRequest, TItem}(IRuleBuilder{TRequest, List{TItem}})"/> to also reject empty values.
/// <see cref="NotEmpty{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to also reject empty values.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
@@ -68,43 +137,27 @@ public static class ValidatorUtilities
}
/// <summary>
/// Defines a validation rule that ensures the string property is not empty or consisting only of white-space characters.
/// Defines a validation rule that ensures the property is not empty.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// This rule is type-aware: a <see cref="string"/> is checked for white-space only content, a <see cref="Guid"/>
/// is checked against <see cref="Guid.Empty"/>, and any <see cref="IEnumerable"/> is checked for having at least
/// one item. If the property is <see langword="null"/>, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, string> NotEmpty<TRequest>(this IRuleBuilder<TRequest, string> ruleBuilder)
public static IRuleBuilder<TRequest, TProperty> NotEmpty<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder)
{
return ruleBuilder.Must(value => value is null || value.Trim().Length > 0);
}
/// <summary>
/// Defines a validation rule that ensures the List property is not empty.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TItem">The type of the items in the list being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, List<TItem>> NotEmpty<TRequest, TItem>(this IRuleBuilder<TRequest, List<TItem>> ruleBuilder)
{
return ruleBuilder.Must(value => value is null || value.Count > 0);
}
/// <summary>
/// Defines a validation rule that ensures the <see cref="Guid"/> property is not <see cref="Guid.Empty"/>.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, Guid> NotEmpty<TRequest>(this IRuleBuilder<TRequest, Guid> ruleBuilder)
{
return ruleBuilder.Must(value => value != Guid.Empty);
return ruleBuilder.Must(value => value switch
{
null => false,
string stringValue => stringValue.Trim().Length > 0,
Guid guidValue => guidValue != Guid.Empty,
IEnumerable enumerable => enumerable.GetEnumerator().MoveNext(),
_ => true
});
}
/// <summary>
@@ -130,4 +183,144 @@ public static class ValidatorUtilities
{
return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value));
}
/// <summary>
/// Defines a validation rule that ensures the string property does not exceed the specified maximum length.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule passes.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="maximumLength">The maximum allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> MaximumLength<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int maximumLength)
{
return ruleBuilder.Must(value => value is not string stringValue || stringValue.Length <= maximumLength);
}
/// <summary>
/// Defines a validation rule that ensures the string property is at least the specified minimum length.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumLength">The minimum allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> MinimumLength<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int minimumLength)
{
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength);
}
/// <summary>
/// Defines a validation rule that ensures the string property has exactly the specified length.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="length">The exact allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Length<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int length)
{
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length == length);
}
/// <summary>
/// Defines a validation rule that ensures the string property length is within the specified inclusive range.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumLength">The minimum allowed length of the property.</param>
/// <param name="maximumLength">The maximum allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Length<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int minimumLength, int maximumLength)
{
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength && stringValue.Length <= maximumLength);
}
/// <summary>
/// Defines a validation rule that ensures the string property matches the specified regular expression pattern.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails (use
/// <see cref="When{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty}, Func{TRequest, bool})"/> to skip optional properties).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="regexPattern">The regular expression pattern the property must match.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Matches<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, string regexPattern)
{
return ruleBuilder.Must(value => value is string stringValue && Regex.IsMatch(stringValue, regexPattern));
}
/// <summary>
/// Defines a validation rule that ensures the string property matches the regular expression pattern selected from the request instance.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="regexPatternSelector">A function that selects the regular expression pattern to match against from the request instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Matches<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, Func<TRequest, string> regexPatternSelector)
{
return ruleBuilder.Must((instance, value) => value is string stringValue && Regex.IsMatch(stringValue, regexPatternSelector(instance)));
}
/// <summary>
/// Defines a validation rule that ensures the integer property is within the specified inclusive range.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumValue">The minimum allowed value of the property.</param>
/// <param name="maximumValue">The maximum allowed value of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int minimumValue, int maximumValue)
{
return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue);
}
/// <summary>
/// Defines a validation rule that ensures the nullable integer property is within the specified inclusive range.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumValue">The minimum allowed value of the property.</param>
/// <param name="maximumValue">The maximum allowed value of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int?> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int minimumValue, int maximumValue)
{
return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue));
}
/// <summary>
/// Defines a validation rule that ensures the property is equal to another property of the request.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="comparisonSelector">A function that selects the property the validated property must equal.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Equal<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, Func<TRequest, TProperty> comparisonSelector)
{
return ruleBuilder.Must((instance, value) => Equals(value, comparisonSelector(instance)));
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer
/// <summary>
/// Query for retrieving the list of authorization permissions.
/// </summary>
public record GetPermissionsQuery : IRequest<ErrorOr<IEnumerable<PermissionResponse>>>;
public record GetPermissionsQuery : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
@@ -8,7 +9,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer
/// <summary>
/// Handler for the query to retrieve the list of authorization permissions.
/// </summary>
public class GetPermissionsQueryHandler : IRequestHandler<GetPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
@@ -41,12 +41,12 @@ public class GetPermissionsQueryHandler : IRequestHandler<GetPermissionsQuery, E
/// <summary>
/// Handles the query to retrieve the list of authorization permissions.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PermissionResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<PermissionResponse>>> Handle(GetPermissionsQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<PermissionResponse>>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken)
{
// only admins can see the list of authorization permissions
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -14,4 +13,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
[DebuggerDisplay("RoleId: {RoleId}")]
public record DeleteRoleCommand(
Guid RoleId
) : IRequest<ErrorOr<Deleted>>;
) : ICommand;
@@ -1,12 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -21,11 +22,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
/// <summary>
/// Handler for the command to delete an authorization role.
/// </summary>
public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, ErrorOr<Deleted>>
public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, ErrorOr<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteRoleCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteRoleCommandHandler"/> class.
@@ -33,21 +35,27 @@ public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, Error
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<DeleteRoleCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete an authorization role.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Deleted>> HandleAsync(DeleteRoleCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// only admins can delete authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
@@ -55,7 +63,7 @@ public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, Error
// check if a role with the requested Id exists
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
ErrorOr<RoleEntity?> getExistingRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
ErrorOr<RoleEntity?> getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (getExistingRoleResult.IsError)
return getExistingRoleResult.Errors;
else if (getExistingRoleResult.Value is null)
@@ -63,7 +71,7 @@ public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, Error
else if (getExistingRoleResult.Value.RoleName == "Admin")
return Errors.Authorization.AdminRoleCannotBeDeleted;
// delete the role and its permissions
ErrorOr<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
ErrorOr<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (deleteRoleResult.IsError)
return deleteRoleResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -16,8 +17,8 @@ public class DeleteRoleCommandValidator : AbstractValidator<DeleteRoleCommand>
/// </summary>
public DeleteRoleCommandValidator()
{
RuleFor(x => x.RoleId)
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
RuleFor(command => command.RoleId)
.NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty)
.Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -20,4 +18,4 @@ public record UpdateRoleCommand(
Guid RoleId,
string RoleName,
List<Guid> Permissions
) : IRequest<ErrorOr<RolePermissionsResponse>>;
) : ICommand;
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -19,11 +21,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
/// <summary>
/// Handler for the command to update an authorization role.
/// </summary>
public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ErrorOr<RolePermissionsResponse>>
public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, ErrorOr<RolePermissionsResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateRoleCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateRoleCommandHandler"/> class.
@@ -31,23 +34,29 @@ public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, Error
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<UpdateRoleCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update an authorization role.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<RolePermissionsResponse>> HandleAsync(UpdateRoleCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// only admins can update authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
@@ -58,9 +67,9 @@ public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, Error
// update the role and its permissions
RoleEntity newRole = new()
{
Id = request.RoleId,
RoleName = request.RoleName,
RolePermissions = request.Permissions.Select(permissionId => new RolePermissionEntity()
Id = command.RoleId,
RoleName = command.RoleName,
RolePermissions = command.Permissions.Select(permissionId => new RolePermissionEntity()
{
PermissionId = permissionId,
Permission = null!,
@@ -74,7 +83,7 @@ public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, Error
return updateRoleResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// retrieve the updated authorization role from the persistence medium and return it
ErrorOr<RoleEntity?> getRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
ErrorOr<RoleEntity?> getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsError)
return getRoleResult.Errors;
if (getRoleResult.Value is null)
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -16,19 +17,20 @@ public class UpdateRoleCommandValidator : AbstractValidator<UpdateRoleCommand>
/// </summary>
public UpdateRoleCommandValidator()
{
RuleFor(x => x.RoleId)
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
RuleFor(command => command.RoleId)
.NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty)
.Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty);
RuleFor(x => x.RoleName)
.NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
RuleFor(command => command.RoleName)
.NotNull().WithError(Errors.Authorization.RoleNameCannotBeNull)
.NotEmpty().WithError(Errors.Authorization.RoleNameCannotBeEmpty);
RuleFor(x => x.Permissions)
.NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
RuleForEach(x => x.Permissions)
.NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
RuleFor(command => command.Permissions)
.NotNull().WithError(Errors.Authorization.PermissionsListCannotBeNull)
.NotEmpty().WithError(Errors.Authorization.PermissionsListCannotBeEmpty);
RuleForEach(command => command.Permissions)
.NotEmpty().WithError(Errors.Authorization.PermissionIdCannotBeEmpty)
.Must(id => id != Guid.Empty).WithError(Errors.Authorization.PermissionIdCannotBeEmpty);
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
/// <summary>
/// Query for retrieving the list of authorization roles.
/// </summary>
public record GetRolesQuery() : IRequest<ErrorOr<IEnumerable<RoleResponse>>>;
public record GetRolesQuery() : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
@@ -8,7 +9,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
/// <summary>
/// Handler for the query to retrieve the list of authorization roles.
/// </summary>
public class GetRolesQueryHandler : IRequestHandler<GetRolesQuery, ErrorOr<IEnumerable<RoleResponse>>>
public class GetRolesQueryHandler : IQueryHandler<GetRolesQuery, ErrorOr<IEnumerable<RoleResponse>>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
@@ -41,12 +41,12 @@ public class GetRolesQueryHandler : IRequestHandler<GetRolesQuery, ErrorOr<IEnum
/// <summary>
/// Handles the query to retrieve the list of authorization roles.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<RoleResponse>>> Handle(GetRolesQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<RoleResponse>>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken)
{
// only admins can see the list of authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -17,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi
public record GetDirectoriesQuery(
string? Path,
bool IncludeHiddenElements
) : IRequest<ErrorOr<IEnumerable<DirectoryResponse>>>;
) : IQuery;
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi
/// <summary>
/// Handler for the query to get all directories.
/// </summary>
public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, ErrorOr<IEnumerable<DirectoryResponse>>>
public class GetDirectoriesQueryHandler : IQueryHandler<GetDirectoriesQuery, ErrorOr<IEnumerable<DirectoryResponse>>>
{
private readonly IDirectoryService _directoryService;
private readonly IValidator<GetDirectoriesQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandler"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
public GetDirectoriesQueryHandler(IDirectoryService directoryService)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetDirectoriesQueryHandler(IDirectoryService directoryService, IValidator<GetDirectoriesQuery> validator)
{
_directoryService = directoryService;
_validator = validator;
}
/// <summary>
/// Gets the list of directories at the specified path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="query">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="DirectoryResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
public Task<ErrorOr<IEnumerable<DirectoryResponse>>> HandleAsync(GetDirectoriesQuery query, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<IEnumerable<DirectoryResponse>>>(validationResult);
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements);
return Task.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class GetDirectoriesQueryValidator : AbstractValidator<GetDirectoriesQuer
/// </summary>
public GetDirectoriesQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
/// <summary>
/// Query for retrieving the list of drives.
/// </summary>
public record GetDrivesQuery() : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
public record GetDrivesQuery() : IQuery;
@@ -1,10 +1,10 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -15,7 +15,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
/// <summary>
/// Handler for the query to get all drives.
/// </summary>
public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
public class GetDrivesQueryHandler : IQueryHandler<GetDrivesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
{
private readonly IDriveService _driveService;
@@ -31,14 +31,14 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
/// <summary>
/// Gets the list of file system drives.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="query">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken)
public Task<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> HandleAsync(GetDrivesQuery query, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemItem>> getDrivesResult = _driveService.GetDrives();
return ValueTask.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors));
return Task.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors));
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
@@ -8,4 +7,4 @@ namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFil
/// <summary>
/// Query for retrieving the file system type.
/// </summary>
public record GetFileSystemQuery() : IRequest<FileSystemTypeResponse>;
public record GetFileSystemQuery() : IQuery;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -11,7 +11,7 @@ namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFil
/// <summary>
/// Handler for the query to get the file system type.
/// </summary>
public class GetFileSystemQueryHandler : IRequestHandler<GetFileSystemQuery, FileSystemTypeResponse>
public class GetFileSystemQueryHandler : IQueryHandler<GetFileSystemQuery, FileSystemTypeResponse>
{
private readonly IPlatformContext _platformContext;
@@ -27,11 +27,11 @@ public class GetFileSystemQueryHandler : IRequestHandler<GetFileSystemQuery, Fil
/// <summary>
/// Gets the type of the file system.
/// </summary>
/// <param name="request">The query to be handled.</param>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The type of the file system.</returns>
public ValueTask<FileSystemTypeResponse> Handle(GetFileSystemQuery request, CancellationToken cancellationToken)
public Task<FileSystemTypeResponse> HandleAsync(GetFileSystemQuery query, CancellationToken cancellationToken)
{
return ValueTask.FromResult(new FileSystemTypeResponse(_platformContext.Platform));
return Task.FromResult(new FileSystemTypeResponse(_platformContext.Platform));
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -17,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
public record GetFilesQuery(
string? Path,
bool IncludeHiddenElements
) : IRequest<ErrorOr<IEnumerable<FileResponse>>>;
) : IQuery;
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
/// <summary>
/// Handler for the query to get all files.
/// </summary>
public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnumerable<FileResponse>>>
public class GetFilesQueryHandler : IQueryHandler<GetFilesQuery, ErrorOr<IEnumerable<FileResponse>>>
{
private readonly IFileService _fileService;
private readonly IValidator<GetFilesQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryHandler"/> class.
/// </summary>
/// <param name="fileService">Injected service for handling files.</param>
public GetFilesQueryHandler(IFileService fileService)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetFilesQueryHandler(IFileService fileService, IValidator<GetFilesQuery> validator)
{
_fileService = fileService;
_validator = validator;
}
/// <summary>
/// Gets the list of files at the specified path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="query">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
public Task<ErrorOr<IEnumerable<FileResponse>>> HandleAsync(GetFilesQuery query, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<IEnumerable<FileResponse>>>(validationResult);
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements);
return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class GetFilesQueryValidator : AbstractValidator<GetFilesQuery>
/// </summary>
public GetFilesQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -17,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFile
public record GetTreeFilesQuery(
string? Path,
bool IncludeHiddenElements
) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
) : IQuery;
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFile
/// <summary>
/// Handler for the query to get all files.
/// </summary>
public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
public class GetTreeFilesQueryHandler : IQueryHandler<GetTreeFilesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
{
private readonly IFileService _fileService;
private readonly IValidator<GetTreeFilesQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesQueryHandler"/> class.
/// </summary>
/// <param name="fileService">Injected service for handling files.</param>
public GetTreeFilesQueryHandler(IFileService fileService)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetTreeFilesQueryHandler(IFileService fileService, IValidator<GetTreeFilesQuery> validator)
{
_fileService = fileService;
_validator = validator;
}
/// <summary>
/// Gets the list of files at the specified path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="query">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken)
public Task<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> HandleAsync(GetTreeFilesQuery query, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(validationResult);
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements);
return Task.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class GetTreeFilesQueryValidator : AbstractValidator<GetTreeFilesQuery>
/// </summary>
public GetTreeFilesQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Mediator;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -16,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePat
public record CombinePathCommand(
string? OriginalPath,
string? NewPath
) : IRequest<ErrorOr<PathSegmentResponse>>;
) : ICommand;
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -13,30 +15,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePat
/// <summary>
/// Handler for the command to split a file system path.
/// </summary>
public class CombinePathCommandHandler : IRequestHandler<CombinePathCommand, ErrorOr<PathSegmentResponse>>
public class CombinePathCommandHandler : ICommandHandler<CombinePathCommand, ErrorOr<PathSegmentResponse>>
{
private readonly IPathService _pathService;
private readonly IValidator<CombinePathCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for handling file system paths.</param>
public CombinePathCommandHandler(IPathService pathService)
/// <param name="validator">Injected validator for application validation rules.</param>
public CombinePathCommandHandler(IPathService pathService, IValidator<CombinePathCommand> validator)
{
_pathService = pathService;
_validator = validator;
}
/// <summary>
/// Combines two file system paths.
/// </summary>
/// <param name="request">The command containing the requested paths.</param>
/// <param name="command">The command containing the requested paths.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="PathSegmentResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(CombinePathCommand request, CancellationToken cancellationToken)
public Task<ErrorOr<PathSegmentResponse>> HandleAsync(CombinePathCommand command, CancellationToken cancellationToken)
{
ErrorOr<string> combinePathResult = _pathService.CombinePath(request.OriginalPath!, request.NewPath!);
return ValueTask.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors));
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<PathSegmentResponse>>(validationResult);
ErrorOr<string> combinePathResult = _pathService.CombinePath(command.OriginalPath!, command.NewPath!);
return Task.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,7 +16,12 @@ public class CombinePathCommandValidator : AbstractValidator<CombinePathCommand>
/// </summary>
public CombinePathCommandValidator()
{
RuleFor(x => x.OriginalPath).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(x => x.NewPath).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(command => command.OriginalPath)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
RuleFor(command => command.NewPath)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -15,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
[DebuggerDisplay("Path: {Path}")]
public record SplitPathCommand(
string? Path
) : IRequest<ErrorOr<IEnumerable<PathSegmentResponse>>>;
) : ICommand;
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
/// <summary>
/// Handler for the command to split a file system path.
/// </summary>
public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr<IEnumerable<PathSegmentResponse>>>
public class SplitPathCommandHandler : ICommandHandler<SplitPathCommand, ErrorOr<IEnumerable<PathSegmentResponse>>>
{
private readonly IPathService _pathService;
private readonly IValidator<SplitPathCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for handling file system paths.</param>
public SplitPathCommandHandler(IPathService pathService)
/// <param name="validator">Injected validator for application validation rules.</param>
public SplitPathCommandHandler(IPathService pathService, IValidator<SplitPathCommand> validator)
{
_pathService = pathService;
_validator = validator;
}
/// <summary>
/// Gets the path components of the specified path.
/// </summary>
/// <param name="request">The command containing the requested path.</param>
/// <param name="command">The command containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PathSegmentResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken)
public Task<ErrorOr<IEnumerable<PathSegmentResponse>>> HandleAsync(SplitPathCommand command, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegment>> parsePathResult = _pathService.ParsePath(request.Path!);
return ValueTask.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<IEnumerable<PathSegmentResponse>>>(validationResult);
ErrorOr<IEnumerable<PathSegment>> parsePathResult = _pathService.ParsePath(command.Path!);
return Task.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class SplitPathCommandValidator : AbstractValidator<SplitPathCommand>
/// </summary>
public SplitPathCommandValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(command => command.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Mediator;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -16,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx
public record CheckPathExistsQuery(
string? Path,
bool IncludeHiddenElements
) : IRequest<ErrorOr<PathExistsResponse>>;
) : IQuery;
@@ -1,8 +1,10 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -12,29 +14,36 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx
/// <summary>
/// Handler for the query to check the existence a file system path.
/// </summary>
public class CheckPathExistsQueryHandler : IRequestHandler<CheckPathExistsQuery, ErrorOr<PathExistsResponse>>
public class CheckPathExistsQueryHandler : IQueryHandler<CheckPathExistsQuery, ErrorOr<PathExistsResponse>>
{
private readonly IPathService _pathService;
private readonly IValidator<CheckPathExistsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsQueryHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for managing file system paths.</param>
public CheckPathExistsQueryHandler(IPathService pathService)
/// <param name="validator">Injected validator for application validation rules.</param>
public CheckPathExistsQueryHandler(IPathService pathService, IValidator<CheckPathExistsQuery> validator)
{
_pathService = pathService;
_validator = validator;
}
/// <summary>
/// Checks the existence of the specified file system path.
/// </summary>
/// <param name="request">The query containing the request.</param>
/// <param name="query">The query containing the request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either <see langword="true"/> if the specified path exists, <see langword="false"/> if it doesn't, or an error message.
/// </returns>
public ValueTask<ErrorOr<PathExistsResponse>> Handle(CheckPathExistsQuery request, CancellationToken cancellationToken)
public Task<ErrorOr<PathExistsResponse>> HandleAsync(CheckPathExistsQuery query, CancellationToken cancellationToken)
{
return ValueTask.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(request.Path!, request.IncludeHiddenElements))));
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<PathExistsResponse>>(validationResult);
return Task.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(query.Path!, query.IncludeHiddenElements))));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class CheckPathExistsQueryValidator : AbstractValidator<CheckPathExistsQu
/// </summary>
public CheckPathExistsQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -15,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathPare
[DebuggerDisplay("Path: {Path}")]
public record GetPathParentQuery(
string? Path
) : IRequest<ErrorOr<IEnumerable<PathSegmentResponse>>>;
) : IQuery;
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathPare
/// <summary>
/// Handler for the query to get the parent of a file system path.
/// </summary>
public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, ErrorOr<IEnumerable<PathSegmentResponse>>>
public class GetPathParentQueryHandler : IQueryHandler<GetPathParentQuery, ErrorOr<IEnumerable<PathSegmentResponse>>>
{
private readonly IPathService _pathService;
private readonly IValidator<GetPathParentQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentQueryHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for managing file system paths.</param>
public GetPathParentQueryHandler(IPathService pathService)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetPathParentQueryHandler(IPathService pathService, IValidator<GetPathParentQuery> validator)
{
_pathService = pathService;
_validator = validator;
}
/// <summary>
/// Gets the parent of the specified file system path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="query">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PathSegmentResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(GetPathParentQuery request, CancellationToken cancellationToken)
public Task<ErrorOr<IEnumerable<PathSegmentResponse>>> HandleAsync(GetPathParentQuery query, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegment>> goUpOneLevelResult = _pathService.GoUpOneLevel(request.Path!);
return ValueTask.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<IEnumerable<PathSegmentResponse>>>(validationResult);
ErrorOr<IEnumerable<PathSegment>> goUpOneLevelResult = _pathService.GoUpOneLevel(query.Path!);
return Task.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class GetPathParentQueryValidator : AbstractValidator<GetPathParentQuery>
/// </summary>
public GetPathParentQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Mediator;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -14,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot
[DebuggerDisplay("Path: {Path}")]
public record GetPathRootQuery(
string? Path
) : IRequest<ErrorOr<PathSegmentResponse>>;
) : IQuery;
@@ -1,10 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -14,28 +16,35 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot
/// <summary>
/// Handler for the query to get the root of a file system path.
/// </summary>
public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr<PathSegmentResponse>>
public class GetPathRootQueryHandler : IQueryHandler<GetPathRootQuery, ErrorOr<PathSegmentResponse>>
{
private readonly IPathService _pathService;
private readonly IValidator<GetPathRootQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for managing file system paths.</param>
public GetPathRootQueryHandler(IPathService pathService)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetPathRootQueryHandler(IPathService pathService, IValidator<GetPathRootQuery> validator)
{
_pathService = pathService;
_validator = validator;
}
/// <summary>
/// Gets the root of the specified file system path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="query">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the root of the specified path, or an error.</returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken)
public Task<ErrorOr<PathSegmentResponse>> HandleAsync(GetPathRootQuery query, CancellationToken cancellationToken)
{
ErrorOr<PathSegment> getPathRootResult = _pathService.GetPathRoot(request.Path!);
return ValueTask.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return Task.FromResult<ErrorOr<PathSegmentResponse>>(validationResult);
ErrorOr<PathSegment> getPathRootResult = _pathService.GetPathRoot(query.Path!);
return Task.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class GetPathRootQueryValidator : AbstractValidator<GetPathRootQuery>
/// </summary>
public GetPathRootQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator;
@@ -8,4 +7,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSepa
/// <summary>
/// Query for retrieving the file system path separator.
/// </summary>
public record GetPathSeparatorQuery() : IRequest<PathSeparatorResponse>;
public record GetPathSeparatorQuery() : IQuery;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -11,7 +11,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSepa
/// <summary>
/// Handler for the query to get the path separator character of a file system path.
/// </summary>
public class GetPathSeparatorQueryHandler : IRequestHandler<GetPathSeparatorQuery, PathSeparatorResponse>
public class GetPathSeparatorQueryHandler : IQueryHandler<GetPathSeparatorQuery, PathSeparatorResponse>
{
private readonly IPathService _pathService;
@@ -27,11 +27,11 @@ public class GetPathSeparatorQueryHandler : IRequestHandler<GetPathSeparatorQuer
/// <summary>
/// Gets the path separator character of a file system path.
/// </summary>
/// <param name="request">The query containing the request.</param>
/// <param name="query">The query containing the request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The file system path separator character.</returns>
public ValueTask<PathSeparatorResponse> Handle(GetPathSeparatorQuery request, CancellationToken cancellationToken)
public Task<PathSeparatorResponse> HandleAsync(GetPathSeparatorQuery query, CancellationToken cancellationToken)
{
return ValueTask.FromResult(new PathSeparatorResponse(_pathService.PathSeparator.ToString()));
return Task.FromResult(new PathSeparatorResponse(_pathService.PathSeparator.ToString()));
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Mediator;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -13,4 +12,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePat
[DebuggerDisplay("Path: {Path}")]
public record ValidatePathQuery(
string? Path
) : IRequest<PathValidResponse>;
) : IQuery;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -11,7 +11,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePat
/// <summary>
/// Handler for the query to validate a file system path.
/// </summary>
public class ValidatePathQueryHandler : IRequestHandler<ValidatePathQuery, PathValidResponse>
public class ValidatePathQueryHandler : IQueryHandler<ValidatePathQuery, PathValidResponse>
{
private readonly IPathService _pathService;
@@ -27,13 +27,13 @@ public class ValidatePathQueryHandler : IRequestHandler<ValidatePathQuery, PathV
/// <summary>
/// Validates the specified file system path.
/// </summary>
/// <param name="request">The query containing the request.</param>
/// <param name="query">The query containing the request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// <see langword="true"/> if the specified path is valid, <see langword="false"/> otherwise.
/// </returns>
public ValueTask<PathValidResponse> Handle(ValidatePathQuery request, CancellationToken cancellationToken)
public Task<PathValidResponse> HandleAsync(ValidatePathQuery query, CancellationToken cancellationToken)
{
return ValueTask.FromResult(new PathValidResponse(_pathService.IsValidPath(request.Path!)));
return Task.FromResult(new PathValidResponse(_pathService.IsValidPath(query.Path!)));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class ValidatePathQueryValidator : AbstractValidator<ValidatePathQuery>
/// </summary>
public ValidatePathQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using Mediator;
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -16,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThu
public record GetThumbnailQuery(
string? Path,
int Quality
) : IRequest<ErrorOr<ThumbnailResponse>>;
) : IQuery;
@@ -1,10 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -14,28 +16,35 @@ namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThu
/// <summary>
/// Handler for the query to get the file thumbnail.
/// </summary>
public class GetThumbnailQueryHandler : IRequestHandler<GetThumbnailQuery, ErrorOr<ThumbnailResponse>>
public class GetThumbnailQueryHandler : IQueryHandler<GetThumbnailQuery, ErrorOr<ThumbnailResponse>>
{
private readonly IThumbnailService _thumbnailsService;
private readonly IValidator<GetThumbnailQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailQueryHandler"/> class.
/// </summary>
/// <param name="thumbnailsService">Injected service for handling thumbnails.</param>
public GetThumbnailQueryHandler(IThumbnailService thumbnailsService)
/// <param name="validator">Injected validator for application validation rules.</param>
public GetThumbnailQueryHandler(IThumbnailService thumbnailsService, IValidator<GetThumbnailQuery> validator)
{
_thumbnailsService = thumbnailsService;
_validator = validator;
}
/// <summary>
/// Gets the thumbnail for a file located at the specified path, with the specified quality.
/// </summary>
/// <param name="request">The query to be handled.</param>
/// <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="ErrorOr{T}"/> containing either a thumbnail, or an error.</returns>
public async ValueTask<ErrorOr<ThumbnailResponse>> Handle(GetThumbnailQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<ThumbnailResponse>> HandleAsync(GetThumbnailQuery query, CancellationToken cancellationToken)
{
ErrorOr<Thumbnail> getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken);
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
ErrorOr<Thumbnail> getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(query.Path!, query.Quality, cancellationToken);
return await ValueTask.FromResult(getThumbnailResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,7 +16,12 @@ public class GetThumbnailQueryValidator : AbstractValidator<GetThumbnailQuery>
/// </summary>
public GetThumbnailQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
RuleFor(x => x.Quality).InclusiveBetween(0, 100).WithMessage(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred.Description);
RuleFor(query => query.Path)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
RuleFor(query => query.Quality)
.InclusiveBetween(0, 100)
.WithError(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
@@ -18,4 +16,4 @@ public record SetupApplicationCommand(
string? Password,
string? PasswordConfirm,
bool Use2fa
) : IRequest<ErrorOr<RegistrationResponse>>;
) : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.Seed;
@@ -8,8 +9,8 @@ using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -22,7 +23,7 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApp
/// <summary>
/// Handler for the command to perform the initial application setup.
/// </summary>
public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCommand, ErrorOr<RegistrationResponse>>
public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCommand, ErrorOr<RegistrationResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPasswordHashService _hashService;
@@ -31,6 +32,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IDataSeedService _dataSeedService;
private readonly IValidator<SetupApplicationCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationCommandHandler"/> class.
@@ -42,6 +44,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="dataSeedService">Injected service for the initial persistence medium data seed.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
IPasswordHashService hashService,
@@ -49,7 +52,8 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider,
IDataSeedService dataSeedService)
IDataSeedService dataSeedService,
IValidator<SetupApplicationCommand> validator)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
@@ -58,18 +62,23 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
_qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
_dataSeedService = dataSeedService;
_validator = validator;
}
/// <summary>
/// Handles the command to perform the initial application setup.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RegistrationResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(SetupApplicationCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<RegistrationResponse>> HandleAsync(SetupApplicationCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
@@ -83,8 +92,8 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
UserEntity user = new()
{
Id = id,
Username = request.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
Username = command.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(command.Password!)),
CreatedOnUtc = _dateTimeProvider.UtcNow,
Libraries = [],
UserPermissions = [],
@@ -93,12 +102,12 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
LibraryScans = [],
};
// if the user enabled two factor auth, include a QR with the totp secret
if (request.Use2fa)
if (command.Use2fa)
{
// generate a TOTP secret
byte[] secret = _totpTokenGenerator.GenerateSecret();
// convert the secret into a QR code for the user to scan
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(request.Username!, secret);
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(command.Username!, secret);
// store the TOTP secret in the repository, encrypted
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
#endregion
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
@@ -15,10 +16,22 @@ public class SetupApplicationCommandValidator : AbstractValidator<SetupApplicati
/// </summary>
public SetupApplicationCommandValidator()
{
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description);
RuleFor(x => x.PasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
RuleFor(x => x.Password).Equal(x => x.PasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description);
RuleFor(command => command.Username)
.NotEmpty()
.WithError(Errors.Authentication.UsernameCannotBeEmpty);
RuleFor(command => command.Password)
.NotEmpty()
.WithError(Errors.Authentication.PasswordCannotBeEmpty)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$")
.WithError(Errors.Authentication.InvalidPassword);
RuleFor(command => command.PasswordConfirm)
.NotEmpty()
.WithError(Errors.Authentication.PasswordConfirmCannotBeEmpty);
RuleFor(command => command.Password)
.Equal(command => command.PasswordConfirm)
.WithError(Errors.Authentication.PasswordsNotMatch);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.UsersManagement;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization;
@@ -8,4 +7,4 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInit
/// <summary>
/// Query for checking the initialization of the application.
/// </summary>
public record CheckInitializationQuery() : IRequest<InitializationResponse>;
public record CheckInitializationQuery() : IQuery;
@@ -1,10 +1,10 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Contracts.Responses.UsersManagement;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -16,7 +16,7 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInit
/// <summary>
/// Handler for the query to check the initialization of the application.
/// </summary>
public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializationQuery, InitializationResponse>
public class CheckInitializationQueryHandler : IQueryHandler<CheckInitializationQuery, InitializationResponse>
{
private readonly IUnitOfWork _unitOfWork;
@@ -31,12 +31,12 @@ public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializati
/// <summary>
/// Checks the initialization status of the application.
/// </summary>
/// <param name="request">The query containing the request.</param>
/// <param name="query">The query containing the request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// <see langword="true"/> if the application is initialized (the admin account is created), <see langword="false"/> otherwise.
/// </returns>
public async ValueTask<InitializationResponse> Handle(CheckInitializationQuery request, CancellationToken cancellationToken)
public async Task<InitializationResponse> HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken)
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
// if the repository reports an error, or there are no users, the application has not been initialized
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -31,4 +29,4 @@ public record AddLibraryCommand(
bool DownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
) : IRequest<ErrorOr<LibraryResponse>>;
) : ICommand;
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -16,8 +18,8 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -29,13 +31,14 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
/// <summary>
/// Handler for the command to add a media library.
/// </summary>
public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, ErrorOr<LibraryResponse>>
public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<AddLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryCommandHandler"/> class.
@@ -45,30 +48,36 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
/// <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="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(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<AddLibraryCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to add a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse>> HandleAsync(AddLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// if the user that made the request is not an Admin or they don't have the permission to manage media libraries, they do not have the right to create it
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
@@ -76,9 +85,9 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
return ApplicationErrors.Authorization.NotAuthorized;
// make sure the file is an actual supported image
if (request.CoverImage is not null)
if (command.CoverImage is not null)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
@@ -92,15 +101,15 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
UserId.Create(_currentUserService.UserId!.Value),
request.Title!,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!,
request.CoverImage,
request.IsEnabled,
request.IsLocked,
request.DownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan,
command.Title!,
Enum.Parse<LibraryType>(command.LibraryType!),
command.ContentLocations!,
command.CoverImage,
command.IsEnabled,
command.IsLocked,
command.DownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
[]
);
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
@@ -17,21 +18,28 @@ public class AddLibraryCommandValidator : AbstractValidator<AddLibraryCommand>
/// </summary>
public AddLibraryCommandValidator()
{
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(command => command.LibraryType)
.NotNull()
.WithError(Errors.Library.LibraryTypeCannotBeNull)
.Must(libraryType => Enum.TryParse<LibraryType>(libraryType, out _))
.WithError(Errors.Library.UnknownLibraryType);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description);
RuleFor(command => command.ContentLocations)
.NotNull()
.WithError(Errors.Library.PathsListCannotBeNull)
.NotEmpty()
.WithError(Errors.Library.PathsListCannotBeEmpty);
RuleForEach(x => x.ContentLocations)
.NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description)
.MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description);
RuleForEach(command => command.ContentLocations)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty)
.MaximumLength(260)
.WithError(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong);
RuleFor(x => x.Title)
.NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description);
RuleFor(command => command.Title)
.NotEmpty()
.WithError(Errors.Library.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan;
@@ -8,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrari
/// <summary>
/// Command for canceling the previously started scan of all media libraries.
/// </summary>
public record CancelLibrariesScanCommand : IRequest<ErrorOr<Success>>;
public record CancelLibrariesScanCommand : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -10,7 +11,6 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrari
/// <summary>
/// Handler for the command for canceling the scan of all media libraries.
/// </summary>
public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
@@ -51,10 +51,10 @@ public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibraries
/// <summary>
/// Handles the command for canceling the scan of all media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(CancelLibrariesScanCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -16,4 +15,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrary
public record CancelLibraryScanCommand(
Guid LibraryId,
Guid ScanId
) : IRequest<ErrorOr<Success>>;
) : ICommand;
@@ -1,15 +1,17 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -21,12 +23,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrary
/// <summary>
/// Handler for the command for canceling the scan of a media library.
/// </summary>
public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScanCommand, ErrorOr<Success>>
public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScanCommand, ErrorOr<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<CancelLibraryScanCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibraryScanCommandHandler"/> class.
@@ -35,30 +38,37 @@ public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScan
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</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 CancelLibraryScanCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<CancelLibraryScanCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command for canceling the scan of a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(CancelLibraryScanCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Success>> HandleAsync(CancelLibraryScanCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the library scan from the repository
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(request.ScanId, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
if (getLibraryScansResult.IsError)
return getLibraryScansResult.Errors;
if (getLibraryScansResult.Value is null)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,11 +17,16 @@ public class CancelLibraryScanCommandValidator : AbstractValidator<CancelLibrary
/// </summary>
public CancelLibraryScanCommandValidator()
{
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.ScanId)
.NotEmpty().WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description);
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.ScanId)
.NotEmpty()
.WithError(Errors.LibraryScanning.ScanIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.LibraryScanning.ScanIdCannotBeEmpty);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -14,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary
[DebuggerDisplay("Id: {Id}")]
public record DeleteLibraryCommand(
Guid Id
) : IRequest<ErrorOr<Deleted>>;
) : ICommand;
@@ -1,15 +1,17 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -21,12 +23,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary
/// <summary>
/// Handler for the command to delete a library by its Id.
/// </summary>
public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand, ErrorOr<Deleted>>
public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand, ErrorOr<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<DeleteLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLibraryCommandHandler"/> class.
@@ -35,29 +38,36 @@ public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand,
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</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 DeleteLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<DeleteLibraryCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to delete a library by its Id.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Deleted>> HandleAsync(DeleteLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -83,7 +93,7 @@ public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand,
_domainEventsQueue.Enqueue(domainEvent);
// perform the deletion
ErrorOr<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (deletePersistenceLibraryResult.IsError)
return deletePersistenceLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class DeleteLibraryCommandValidator : AbstractValidator<DeleteLibraryComm
/// </summary>
public DeleteLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(command => command.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries
/// <summary>
/// Command for initiating the scan of all media libraries.
/// </summary>
public record ScanLibrariesCommand() : IRequest<ErrorOr<IEnumerable<MediaLibraryScanResponse>>>;
public record ScanLibrariesCommand() : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -13,7 +14,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -25,7 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries
/// <summary>
/// Handler for the command for initiating the scan of all media libraries.
/// </summary>
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<MediaLibraryScanResponse>>>
public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<MediaLibraryScanResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -54,10 +54,10 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
/// <summary>
/// Handles the command for initiating the scan of all media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<IEnumerable<MediaLibraryScanResponse>>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
#endregion
@@ -13,4 +11,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
/// <param name="Id">The unique identifier of the library to scan.</param>
public record ScanLibraryCommand(
Guid Id
) : IRequest<ErrorOr<MediaLibraryScanResponse>>;
) : ICommand;
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
@@ -14,7 +16,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -28,12 +29,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
/// <summary>
/// Handler for the command for initiating the scan of a media library.
/// </summary>
public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, ErrorOr<MediaLibraryScanResponse>>
public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, ErrorOr<MediaLibraryScanResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<ScanLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibraryCommandHandler"/> class.
@@ -42,31 +44,38 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</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 ScanLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<ScanLibraryCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command for initiating the scan of a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<MediaLibraryScanResponse>> Handle(ScanLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<MediaLibraryScanResponse>> HandleAsync(ScanLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the media library from the persistence medium
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
@@ -91,7 +100,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
return domainLibraryResult.Errors;
// get the past month's scans for this library
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (pastLibraryScansResult.IsError)
return pastLibraryScansResult.Errors;
@@ -103,7 +112,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
// queue the media library scan
ErrorOr<LibraryScan> libraryScanResult = LibraryScan.Create(
LibraryId.Create(request.Id),
LibraryId.Create(command.Id),
UserId.Create(_currentUserService.UserId!.Value),
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
);
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class ScanLibraryCommandValidator : AbstractValidator<ScanLibraryCommand>
/// </summary>
public ScanLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(command => command.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -35,4 +33,4 @@ public record UpdateLibraryCommand(
bool DownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
) : IRequest<ErrorOr<LibraryResponse>>;
) : ICommand;
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -18,8 +20,8 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -32,13 +34,14 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary
/// <summary>
/// Handler for the command to update a media library.
/// </summary>
public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IValidator<UpdateLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryCommandHandler"/> class.
@@ -48,34 +51,41 @@ public class UpdateLibraryCommandHandler : IRequestHandler<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="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(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<UpdateLibraryCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_validator = validator;
}
/// <summary>
/// Handles the command to update a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse>> HandleAsync(UpdateLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// make sure the file is an actual supported image
if (request.CoverImage is not null)
if (command.CoverImage is not null)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
@@ -88,7 +98,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
// get a library repository and retrieve the library to update
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -102,17 +112,17 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
LibraryId.Create(request.Id),
UserId.Create(request.OwnerId),
request.Title!,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!,
request.CoverImage,
request.IsEnabled,
request.IsLocked,
request.DownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan,
LibraryId.Create(command.Id),
UserId.Create(command.OwnerId),
command.Title!,
Enum.Parse<LibraryType>(command.LibraryType!),
command.ContentLocations!,
command.CoverImage,
command.IsEnabled,
command.IsLocked,
command.DownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
);
if (createLibraryResult.IsError)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
@@ -17,29 +18,40 @@ public class UpdateLibraryCommandValidator : AbstractValidator<UpdateLibraryComm
/// </summary>
public UpdateLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.OwnerId)
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
RuleFor(command => command.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(command => command.OwnerId)
.NotEmpty()
.WithError(Errors.Users.UserIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Users.UserIdCannotBeEmpty);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description);
RuleFor(command => command.LibraryType)
.NotNull()
.WithError(Errors.Library.LibraryTypeCannotBeNull)
.Must(libraryType => Enum.TryParse<LibraryType>(libraryType, out _))
.WithError(Errors.Library.UnknownLibraryType);
RuleForEach(x => x.ContentLocations)
.NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description)
.MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description);
RuleFor(command => command.ContentLocations)
.NotNull()
.WithError(Errors.Library.PathsListCannotBeNull)
.NotEmpty()
.WithError(Errors.Library.PathsListCannotBeEmpty);
RuleFor(x => x.Title)
.NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description);
RuleForEach(command => command.ContentLocations)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty)
.MaximumLength(260)
.WithError(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong);
RuleFor(command => command.Title)
.NotEmpty()
.WithError(Errors.Library.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries;
@@ -9,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibr
/// <summary>
/// Query for getting the list of enabled media libraries.
/// </summary>
public record GetEnabledLibrariesQuery : IRequest<ErrorOr<LibraryResponse[]>>;
public record GetEnabledLibrariesQuery : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -7,7 +8,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibr
/// <summary>
/// Handler for the query to get the enabled media libraries.
/// </summary>
public class GetEnabledLibrariesQueryHandler : IRequestHandler<GetEnabledLibrariesQuery, ErrorOr<LibraryResponse[]>>
public class GetEnabledLibrariesQueryHandler : IQueryHandler<GetEnabledLibrariesQuery, ErrorOr<LibraryResponse[]>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -44,12 +44,12 @@ public class GetEnabledLibrariesQueryHandler : IRequestHandler<GetEnabledLibrari
/// <summary>
/// Handles the query to get the enabled media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <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="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse[]>> Handle(GetEnabledLibrariesQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
{
// get the enabled libraries from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
@@ -9,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
/// <summary>
/// Query for getting the list of media libraries.
/// </summary>
public record GetLibrariesQuery : IRequest<ErrorOr<LibraryResponse[]>>;
public record GetLibrariesQuery : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -7,7 +8,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
/// <summary>
/// Handler for the query to get the media libraries.
/// </summary>
public class GetLibrariesQueryHandler : IRequestHandler<GetLibrariesQuery, ErrorOr<LibraryResponse[]>>
public class GetLibrariesQueryHandler : IQueryHandler<GetLibrariesQuery, ErrorOr<LibraryResponse[]>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -44,12 +44,12 @@ public class GetLibrariesQueryHandler : IRequestHandler<GetLibrariesQuery, Error
/// <summary>
/// Handles the query to get the media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <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="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse[]>> Handle(GetLibrariesQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse[]>> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
{
// get the libraries from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
[DebuggerDisplay("Id: {Id}")]
public record GetLibraryQuery(
Guid Id
) : IRequest<ErrorOr<LibraryResponse>>;
) : IQuery;
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -20,11 +22,12 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
/// <summary>
/// Handler for the query to get a library by its Id.
/// </summary>
public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<LibraryResponse>>
public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetLibraryQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryQueryHandler"/> class.
@@ -32,29 +35,36 @@ public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<L
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</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 GetLibraryQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<GetLibraryQuery> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the query to get a library by its Id.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <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="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(GetLibraryQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse>> HandleAsync(GetLibraryQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class GetLibraryQueryValidator : AbstractValidator<GetLibraryQuery>
/// </summary>
public GetLibraryQueryValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(query => query.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScan
public record GetLibraryScanProgressQuery(
Guid LibraryId,
Guid ScanId
) : IRequest<ErrorOr<MediaLibraryScanProgressResponse>>;
) : IQuery;
@@ -1,17 +1,19 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -23,12 +25,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScan
/// <summary>
/// Handler for the query to get the progress of a library scan.
/// </summary>
public class GetLibraryScanProgressQueryHandler : IRequestHandler<GetLibraryScanProgressQuery, ErrorOr<MediaLibraryScanProgressResponse>>
public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanProgressQuery, ErrorOr<MediaLibraryScanProgressResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetLibraryScanProgressQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryScanProgressQueryHandler"/> class.
@@ -37,31 +40,38 @@ public class GetLibraryScanProgressQueryHandler : IRequestHandler<GetLibraryScan
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</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 GetLibraryScanProgressQueryHandler(
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<GetLibraryScanProgressQuery> validator)
{
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the query to get the progress of a library scan.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <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="ErrorOr{TValue}"/> containing either a <see cref="MediaLibraryScanProgressResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<MediaLibraryScanProgressResponse>> Handle(GetLibraryScanProgressQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<MediaLibraryScanProgressResponse>> HandleAsync(GetLibraryScanProgressQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -73,7 +83,7 @@ public class GetLibraryScanProgressQueryHandler : IRequestHandler<GetLibraryScan
return ApplicationErrors.Authorization.NotAuthorized;
ErrorOr<MediaLibraryScanProgress> getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
MediaLibraryScanCompositeId.Create(ScanId.Create(request.ScanId), UserId.Create(_currentUserService.UserId!.Value)));
MediaLibraryScanCompositeId.Create(ScanId.Create(query.ScanId), UserId.Create(_currentUserService.UserId!.Value)));
if (getProgressResult.IsError)
return getProgressResult.Errors;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,11 +17,16 @@ public class GetLibraryScanProgressQueryValidator : AbstractValidator<GetLibrary
/// </summary>
public GetLibraryScanProgressQueryValidator()
{
RuleFor(x => x.ScanId)
.NotEmpty().WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description);
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(query => query.ScanId)
.NotEmpty()
.WithError(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibr
/// <summary>
/// Query for getting the list of ongoing media library scans.
/// </summary>
public record GetRunningLibraryScansQuery : IRequest<ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>>;
public record GetRunningLibraryScansQuery : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -10,7 +11,6 @@ using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibr
/// <summary>
/// Handler for the query to get the ongoing media library scans.
/// </summary>
public class GetRunningLibraryScansQueryHandler : IRequestHandler<GetRunningLibraryScansQuery, ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>>
public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibraryScansQuery, ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -51,12 +51,12 @@ public class GetRunningLibraryScansQueryHandler : IRequestHandler<GetRunningLibr
/// <summary>
/// Handles the query to get the ongoing media library scans.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <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="ErrorOr{TValue}"/> containing either a successfully created <see cref="MediaLibraryScanProgress"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>> Handle(GetRunningLibraryScansQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
{
// get the ongoing library scans from the repository
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -56,4 +54,4 @@ public record AddBookCommand(
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<BookRatingDto>? Ratings
) : IRequest<ErrorOr<BookResponse>>;
) : ICommand;
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
@@ -13,7 +15,6 @@ using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Boo
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -27,42 +28,49 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Handler for the command to add a book.
/// </summary>
public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<BookResponse>>
public class AddBookCommandHandler : ICommandHandler<AddBookCommand, ErrorOr<BookResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IValidator<AddBookCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public AddBookCommandHandler(IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public AddBookCommandHandler(IUnitOfWork unitOfWork, IValidator<AddBookCommand> validator)
{
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to add a book.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<BookResponse>> Handle(AddBookCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<BookResponse>> HandleAsync(AddBookCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// TODO: update Api.Book.md documentation when the functionality is fully implemented
List<MediaContributorId> contributorIds = [];
foreach (MediaContributorDto mediaContributor in request.Contributors!)
foreach (MediaContributorDto mediaContributor in command.Contributors!)
{
// TODO: add logic to search the media contributors repository for existing contributors, based on the provided names
}
BookSeries? bookSeries = null;
if (request.Series != null)
if (command.Series != null)
{
// TODO: add logic to search the book series repository for existing book series, based on the provided title
// TODO: uncomment integration and unit tests about series
}
List<ErrorOr<BookRating>> domainRatingsResult = request.Ratings!.ConvertAll(rating => BookRating.Create(
List<ErrorOr<BookRating>> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create(
rating.Value ?? default,
rating.MaxValue ?? default,
Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null),
@@ -74,88 +82,88 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
List<BookRating> domainRatings = [.. domainRatingsResult.Select(rating => rating.Value)];
List<ErrorOr<Genre>> domainGenresResult = request.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!));
List<ErrorOr<Genre>> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!));
errors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)];
if (errors.Count != 0)
return errors;
List<Genre> domainGenres = [.. domainGenresResult.Select(genre => genre.Value)];
List<ErrorOr<Tag>> domainTagsResult = request.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!));
List<ErrorOr<Tag>> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!));
errors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)];
if (errors.Count != 0)
return errors;
List<Tag> domainTags = [.. domainTagsResult.Select(tag => tag.Value)];
List<ErrorOr<Isbn>> domainIsbnsResult = request.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
List<ErrorOr<Isbn>> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)];
if (errors.Count != 0)
return errors;
List<Isbn> domainIsbns = [.. domainIsbnsResult.Select(isbn => isbn.Value)];
ErrorOr<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo!.OriginalReleaseDate),
Optional<int>.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseYear),
Optional<string>.FromNullable(request.Metadata.ReleaseInfo.ReleaseCountry),
Optional<string>.FromNullable(request.Metadata.ReleaseInfo.ReleaseVersion)
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo!.OriginalReleaseDate),
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseYear),
Optional<string>.FromNullable(command.Metadata.ReleaseInfo.ReleaseCountry),
Optional<string>.FromNullable(command.Metadata.ReleaseInfo.ReleaseVersion)
);
if (releaseInfoResult.IsError)
return releaseInfoResult.Errors;
ReleaseInfo releaseInfo = releaseInfoResult.Value;
LanguageInfo? languageInfo = null;
if (request.Metadata.Language is not null)
if (command.Metadata.Language is not null)
{
ErrorOr<LanguageInfo> languageInfoResult = LanguageInfo.Create(
request.Metadata.Language.LanguageCode!,
request.Metadata.Language.LanguageName!,
Optional<string>.FromNullable(request.Metadata.Language.NativeName));
command.Metadata.Language.LanguageCode!,
command.Metadata.Language.LanguageName!,
Optional<string>.FromNullable(command.Metadata.Language.NativeName));
if (languageInfoResult.IsError)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
LanguageInfo? originalLanguageInfo = null;
if (request.Metadata.OriginalLanguage is not null)
if (command.Metadata.OriginalLanguage is not null)
{
ErrorOr<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
request.Metadata.OriginalLanguage.LanguageCode!,
request.Metadata.OriginalLanguage.LanguageName!,
Optional<string>.FromNullable(request.Metadata.OriginalLanguage.NativeName));
command.Metadata.OriginalLanguage.LanguageCode!,
command.Metadata.OriginalLanguage.LanguageName!,
Optional<string>.FromNullable(command.Metadata.OriginalLanguage.NativeName));
if (originalLanguageInfoResult.IsError)
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
ErrorOr<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
request.Metadata.Title!,
Optional<string>.FromNullable(request.Metadata.OriginalTitle),
Optional<string>.FromNullable(request.Metadata.Description),
command.Metadata.Title!,
Optional<string>.FromNullable(command.Metadata.OriginalTitle),
Optional<string>.FromNullable(command.Metadata.Description),
releaseInfo,
domainGenres,
domainTags,
Optional<LanguageInfo>.FromNullable(languageInfo),
Optional<LanguageInfo>.FromNullable(originalLanguageInfo),
Optional<string>.FromNullable(request.Metadata.Publisher),
Optional<int>.FromNullable(request.Metadata.PageCount)
Optional<string>.FromNullable(command.Metadata.Publisher),
Optional<int>.FromNullable(command.Metadata.PageCount)
);
if (metadataResult.IsError)
return metadataResult.Errors;
ErrorOr<Book> createBookResult = Book.Create(
LibraryId.Create(request.LibraryId),
request.Path,
LibraryId.Create(command.LibraryId),
command.Path,
metadataResult.Value,
Optional<BookFormat>.FromNullable(request.Format),
Optional<string>.FromNullable(request.Edition),
request.VolumeNumber ?? default,
Optional<BookFormat>.FromNullable(command.Format),
Optional<string>.FromNullable(command.Edition),
command.VolumeNumber ?? default,
Optional<BookSeries>.FromNullable(bookSeries),
Optional<string>.FromNullable(request.ASIN),
Optional<string>.FromNullable(request.GoodreadsId),
Optional<string>.FromNullable(request.LCCN),
Optional<string>.FromNullable(request.OCLCNumber),
Optional<string>.FromNullable(request.OpenLibraryId),
Optional<string>.FromNullable(request.LibraryThingId),
Optional<string>.FromNullable(request.GoogleBooksId),
Optional<string>.FromNullable(request.BarnesAndNobleId),
Optional<string>.FromNullable(request.AppleBooksId),
Optional<string>.FromNullable(command.ASIN),
Optional<string>.FromNullable(command.GoodreadsId),
Optional<string>.FromNullable(command.LCCN),
Optional<string>.FromNullable(command.OCLCNumber),
Optional<string>.FromNullable(command.OpenLibraryId),
Optional<string>.FromNullable(command.LibraryThingId),
Optional<string>.FromNullable(command.GoogleBooksId),
Optional<string>.FromNullable(command.BarnesAndNobleId),
Optional<string>.FromNullable(command.AppleBooksId),
domainIsbns,
contributorIds,
ratings: domainRatings
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -16,235 +17,339 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
/// </summary>
public AddBookCommandValidator()
{
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.WrittenContent.BookLibraryCannotBeNull.Description);
RuleFor(x => x.Path)
.NotEmpty().WithMessage(Errors.WrittenContent.BookPathCannotBeEmpty.Description);
RuleFor(x => x.Metadata)
.NotNull().WithMessage(Errors.Metadata.MetadataCannotBeNull.Description)
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull);
RuleFor(command => command.Path)
.NotEmpty()
.WithError(Errors.WrittenContent.BookPathCannotBeEmpty);
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description);
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255).When(m => m!.OriginalTitle is not null)
.WithMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description);
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.Description)
.MaximumLength(2000).When(m => m!.Description is not null)
.WithMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description);
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
metadata.RuleFor(m => m!.ReleaseInfo)
.NotNull().WithMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Description)
.ChildRules(ri =>
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
ri.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999).When(r => r!.OriginalReleaseYear.HasValue)
.WithMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999).When(r => r!.ReReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description);
ri.RuleFor(r => r!.ReleaseCountry)
.Matches("^[A-Za-z]{2}$").When(r => r!.ReleaseCountry is not null)
.WithMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Description);
ri.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50).When(r => r!.ReleaseVersion is not null)
.WithMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description);
ri.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfo, originalReleaseYear) =>
!releaseInfo!.OriginalReleaseDate.HasValue ||
!releaseInfo.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfo.OriginalReleaseDate.Value.Year)
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseCountry)
.Matches("^[A-Za-z]{2}$")
.When(r => r!.ReleaseCountry is not null)
.WithError(Errors.Metadata.CountryCodeMustBe2CharactersLong);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithMessage(Errors.Metadata.OriginalReleaseDateAndYearMustMatch.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfo, reReleaseYear) =>
!releaseInfo!.ReReleaseDate.HasValue ||
!releaseInfo.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfo.ReReleaseDate.Value.Year)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfo, reReleaseYear) =>
!releaseInfo!.ReReleaseYear.HasValue ||
!releaseInfo.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfo.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description);
ri.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfo, reReleaseDate) =>
!releaseInfo!.ReReleaseDate.HasValue ||
!releaseInfo.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfo.OriginalReleaseDate)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfo, reReleaseYear) =>
!releaseInfo!.ReReleaseDate.HasValue ||
!releaseInfo.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfo.ReReleaseDate.Value.Year)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description);
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
});
metadata.RuleFor(m => m!.Genres)
.NotNull().WithMessage(Errors.Metadata.GenresListCannotBeNull.Description);
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
metadata.RuleForEach(m => m!.Genres)
.ChildRules(g =>
g.RuleFor(genre => genre.Name)
.NotEmpty().WithMessage(Errors.Metadata.GenreNameCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description));
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Tags)
.NotNull().WithMessage(Errors.Metadata.TagsListCannotBeNull.Description);
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
metadata.RuleForEach(m => m!.Tags)
.ChildRules(t =>
t.RuleFor(tag => tag.Name)
.NotEmpty().WithMessage(Errors.Metadata.TagNameCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description));
metadata.RuleFor(m => m!.Language)
.Custom((language, context) =>
{
if (language is null)
return;
if (string.IsNullOrEmpty(language.LanguageCode))
context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
else if (language.LanguageCode.Length > 2)
context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description);
if (string.IsNullOrEmpty(language.LanguageName))
context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description);
else if (language.LanguageName.Length > 50)
context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description);
if (language.NativeName != null && language.NativeName.Length > 50)
context.AddFailure("Language.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description);
});
metadata.RuleFor(m => m!.OriginalLanguage)
.Custom((language, context) =>
{
if (language is null)
return;
if (string.IsNullOrEmpty(language.LanguageCode))
context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
else if (language.LanguageCode.Length > 2)
context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description);
if (string.IsNullOrEmpty(language.LanguageName))
context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description);
else if (language.LanguageName.Length > 50)
context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description);
if (language.NativeName != null && language.NativeName.Length > 50)
context.AddFailure("OriginalLanguage.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description);
});
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty().WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.Publisher)
.MaximumLength(100).When(m => m!.Publisher is not null)
.WithMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description);
.MaximumLength(100)
.When(m => m!.Publisher is not null)
.WithError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong);
metadata.RuleFor(m => m!.PageCount)
.GreaterThan(0).When(m => m!.PageCount.HasValue)
.WithMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description);
.GreaterThan(0)
.When(m => m!.PageCount.HasValue)
.WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero);
});
RuleFor(x => x.Format)
.IsInEnum().When(f => f.Format is not null).WithMessage(Errors.WrittenContent.UnknownBookFormat.Description);
RuleFor(x => x.Edition)
.MaximumLength(50).When(x => x.Edition is not null)
.WithMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description);
RuleFor(x => x.VolumeNumber)
.GreaterThan(0).When(x => x.VolumeNumber.HasValue)
.WithMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description);
RuleFor(x => x.Series)
.ChildRules(s =>
s.RuleFor(series => series!.Title)
.NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description)
.MaximumLength(255)).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description)
.When(x => x.Series is not null);
RuleFor(x => x.ASIN)
.Length(10).When(x => x.ASIN is not null)
.WithMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Description);
RuleFor(x => x.GoodreadsId)
.Matches(@"^\d+$").When(x => x.GoodreadsId is not null)
.WithMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description);
RuleFor(x => x.LCCN)
.Matches(@"^[a-z]{0,3}\d{8,10}$").WithMessage(Errors.WrittenContent.InvalidLccnFormat.Description)
.When(x => x.LCCN is not null);
RuleFor(x => x.OCLCNumber)
.Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$").When(x => x.OCLCNumber is not null)
.WithMessage(Errors.WrittenContent.InvalidOclcFormat.Description);
RuleFor(x => x.OpenLibraryId)
.Matches(@"^OL[1-9]\d*[AMW]$").When(x => x.OpenLibraryId is not null)
.WithMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description);
RuleFor(x => x.LibraryThingId)
.MaximumLength(50).When(x => x.LibraryThingId is not null)
.WithMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description);
RuleFor(x => x.GoogleBooksId)
.Length(12).WithMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description)
.Matches(@"^[A-Za-z0-9_-]{12}$").WithMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description)
.When(x => x.GoogleBooksId is not null);
RuleFor(x => x.BarnesAndNobleId)
.Length(10).WithMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description)
.Matches(@"^\d{10}$").WithMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description)
.When(x => x.BarnesAndNobleId is not null);
RuleFor(x => x.AppleBooksId)
.Matches(@"^id\d+$").When(x => x.AppleBooksId is not null)
.WithMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Description);
RuleFor(x => x.ISBNs)
.NotNull().WithMessage(Errors.WrittenContent.IsbnListCannotBeNull.Description);
RuleForEach(x => x.ISBNs)
RuleFor(command => command.Format)
.IsInEnum()
.When(command => command.Format is not null)
.WithError(Errors.WrittenContent.UnknownBookFormat);
RuleFor(command => command.Edition)
.MaximumLength(50)
.When(command => command.Edition is not null)
.WithError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong);
RuleFor(command => command.VolumeNumber)
.GreaterThan(0)
.When(command => command.VolumeNumber.HasValue)
.WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
RuleFor(command => command.Series)
.ChildRules(series =>
series.RuleFor(s => s!.Title)
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong))
.When(command => command.Series is not null);
RuleFor(command => command.ASIN)
.Length(10)
.When(command => command.ASIN is not null)
.WithError(Errors.WrittenContent.AsinMustBe10CharactersLong);
RuleFor(command => command.GoodreadsId)
.Matches(@"^\d+$")
.When(command => command.GoodreadsId is not null)
.WithError(Errors.WrittenContent.GoodreadsIdMustBeNumeric);
RuleFor(command => command.LCCN)
.Matches(@"^[a-z]{0,3}\d{8,10}$")
.When(command => command.LCCN is not null)
.WithError(Errors.WrittenContent.InvalidLccnFormat);
RuleFor(command => command.OCLCNumber)
.Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$").When(command => command.OCLCNumber is not null)
.WithError(Errors.WrittenContent.InvalidOclcFormat);
RuleFor(command => command.OpenLibraryId)
.Matches(@"^OL[1-9]\d*[AMW]$")
.When(command => command.OpenLibraryId is not null)
.WithError(Errors.WrittenContent.InvalidOpenLibraryId);
RuleFor(command => command.LibraryThingId)
.MaximumLength(50)
.When(command => command.LibraryThingId is not null)
.WithError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong);
RuleFor(command => command.GoogleBooksId)
.Length(12)
.When(command => command.GoogleBooksId is not null)
.WithError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong)
.Matches(@"^[A-Za-z0-9_-]{12}$")
.When(command => command.GoogleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat);
RuleFor(command => command.BarnesAndNobleId)
.Length(10)
.When(command => command.BarnesAndNobleId is not null)
.WithError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong)
.Matches(@"^\d{10}$")
.When(command => command.BarnesAndNobleId is not null)
.WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat);
RuleFor(command => command.AppleBooksId)
.Matches(@"^id\d+$")
.When(command => command.AppleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
RuleFor(command => command.ISBNs)
.NotNull()
.WithError(Errors.WrittenContent.IsbnListCannotBeNull);
RuleForEach(command => command.ISBNs)
.ChildRules(isbn =>
{
isbn.RuleFor(i => i.Value)
.NotEmpty().WithMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Description)
.Matches(i => i.Format == IsbnFormat.Isbn13
? @"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$"
: @"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$")
.WithMessage(i => i.Format == IsbnFormat.Isbn13
? Errors.WrittenContent.InvalidIsbn13Format.Description
: Errors.WrittenContent.InvalidIsbn10Format.Description);
.NotEmpty()
.WithError(Errors.WrittenContent.IsbnValueCannotBeEmpty);
isbn.RuleFor(i => i.Value)
.Matches(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$")
.When(i => i.Format == IsbnFormat.Isbn13)
.WithError(Errors.WrittenContent.InvalidIsbn13Format);
isbn.RuleFor(i => i.Value)
.Matches(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$")
.When(i => i.Format == IsbnFormat.Isbn10)
.WithError(Errors.WrittenContent.InvalidIsbn10Format);
isbn.RuleFor(i => i.Format)
.IsInEnum().WithMessage(Errors.WrittenContent.UnknownIsbnFormat.Description);
.IsInEnum()
.WithError(Errors.WrittenContent.UnknownIsbnFormat);
});
RuleFor(x => x.Contributors)
.NotNull().WithMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Description);
RuleForEach(x => x.Contributors)
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.Name)
.NotNull().WithMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Description)
.NotNull()
.WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty)
.ChildRules(name =>
{
name.RuleFor(n => n!.DisplayName)
.NotNull().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description)
.NotEmpty().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description)
.MaximumLength(100).WithMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description);
.NotNull()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.NotEmpty()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.MaximumLength(100)
.WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
name.RuleFor(n => n!.LegalName)
.MaximumLength(100).When(n => n!.LegalName is not null)
.WithMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description);
.MaximumLength(100)
.When(n => n!.LegalName is not null)
.WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
});
contributor.RuleFor(c => c.Role)
.NotNull().WithMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Description)
.NotNull()
.WithError(Errors.MediaContributor.ContributorRoleCannotBeNull)
.ChildRules(role =>
{
role.RuleFor(r => r!.Name)
.NotEmpty().WithMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description);
.NotEmpty()
.WithError(Errors.MediaContributor.RoleNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
role.RuleFor(r => r!.Category)
.NotEmpty().WithMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description);
.NotEmpty()
.WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong);
});
});
RuleFor(x => x.Ratings)
.NotNull().WithMessage(Errors.Metadata.RatingsListCannotBeNull.Description);
RuleForEach(x => x.Ratings)
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
RuleForEach(command => command.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0).WithMessage(Errors.Metadata.RatingValueMustBePositive.Description)
.Must((r, value) => value <= r.MaxValue).WithMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description);
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0).WithMessage(Errors.Metadata.RatingMaxValueMustBePositive.Description);
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0).When(r => r.VoteCount.HasValue)
.WithMessage(Errors.Metadata.RatingVoteCountMustBePositive.Description);
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
}
}
@@ -1,9 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
@@ -14,4 +11,4 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <param name="LibraryId">The Id of the media library whose books are retrieved.</param>
public record GetBooksQuery(
Guid LibraryId
) : IRequest<ErrorOr<IEnumerable<BookResponse>>>;
) : IQuery;
@@ -1,11 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -16,7 +16,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Handler for the query to get all books.
/// </summary>
public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnumerable<BookResponse>>>
public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, ErrorOr<IEnumerable<BookResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
@@ -32,17 +32,17 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
/// <summary>
/// Handles the query to get all books.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <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="ErrorOr{TValue}"/> containing either a collection of <see cref="BookResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<BookResponse>>> Handle(GetBooksQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<BookResponse>>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken)
{
// get a books repository
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
// get all books of the media library from the book repository
ErrorOr<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
ErrorOr<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(result => ErrorOrFactory.From(getBooksResult.Value.ToResponses()), errors => errors);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
#endregion
@@ -15,4 +14,4 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide
public record ReorderLibraryMetadataProvidersCommand(
Guid LibraryId,
IReadOnlyList<Guid> PluginIds
) : IRequest<ErrorOr<Success>>;
) : ICommand;
@@ -1,9 +1,10 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Mediator;
using Lumina.Application.Common.Infrastructure.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -16,38 +17,45 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide
/// <summary>
/// Handler for the command to reorder the metadata providers of a media library.
/// </summary>
public class ReorderLibraryMetadataProvidersCommandHandler : IRequestHandler<ReorderLibraryMetadataProvidersCommand, ErrorOr<Success>>
public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<ReorderLibraryMetadataProvidersCommand, ErrorOr<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IValidator<ReorderLibraryMetadataProvidersCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork, IValidator<ReorderLibraryMetadataProvidersCommand> validator)
{
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to reorder the metadata providers of a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async ValueTask<ErrorOr<Success>> Handle(ReorderLibraryMetadataProvidersCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Success>> HandleAsync(ReorderLibraryMetadataProvidersCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsError)
return getConfigurationsResult.Errors;
Dictionary<Guid, LibraryMetadataProviderConfigurationEntity> configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId);
for (int rank = 0; rank < request.PluginIds.Count; rank++)
for (int rank = 0; rank < command.PluginIds.Count; rank++)
{
Guid pluginId = request.PluginIds[rank];
Guid pluginId = command.PluginIds[rank];
if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration))
{
configuration.Rank = rank + 1;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,10 +16,14 @@ public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator
/// </summary>
public ReorderLibraryMetadataProvidersCommandValidator()
{
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.Plugins.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.PluginIds)
.NotNull().WithMessage(Errors.Plugins.PluginIdsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Plugins.PluginIdsListCannotBeEmpty.Description);
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
RuleFor(command => command.PluginIds)
.NotNull()
.WithError(Errors.Plugins.PluginIdsListCannotBeNull)
.NotEmpty()
.WithError(Errors.Plugins.PluginIdsListCannotBeEmpty);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
#endregion
@@ -16,4 +15,4 @@ public record SetLibraryMetadataProviderEnabledCommand(
Guid LibraryId,
Guid PluginId,
bool IsEnabled
) : IRequest<ErrorOr<Success>>;
) : ICommand;
@@ -1,9 +1,10 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Mediator;
using Lumina.Application.Common.Infrastructure.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -16,31 +17,38 @@ namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEna
/// <summary>
/// Handler for the command to enable or disable a metadata provider for a media library.
/// </summary>
public class SetLibraryMetadataProviderEnabledCommandHandler : IRequestHandler<SetLibraryMetadataProviderEnabledCommand, ErrorOr<Success>>
public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<SetLibraryMetadataProviderEnabledCommand, ErrorOr<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IValidator<SetLibraryMetadataProviderEnabledCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork, IValidator<SetLibraryMetadataProviderEnabledCommand> validator)
{
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to enable or disable a metadata provider for a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async ValueTask<ErrorOr<Success>> Handle(SetLibraryMetadataProviderEnabledCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Success>> HandleAsync(SetLibraryMetadataProviderEnabledCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
ErrorOr<LibraryMetadataProviderConfigurationEntity?> getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(request.LibraryId, request.PluginId, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryMetadataProviderConfigurationEntity?> getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
if (getConfigurationResult.IsError)
return getConfigurationResult.Errors;
@@ -48,21 +56,21 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : IRequestHandler<S
if (getConfigurationResult.Value is not null)
{
configuration = getConfigurationResult.Value;
configuration.IsEnabled = request.IsEnabled;
configuration.IsEnabled = command.IsEnabled;
}
else
{
// compute the rank to assign to the new configuration, appending it after the existing ones
ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsError)
return getConfigurationsResult.Errors;
int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
configuration = new LibraryMetadataProviderConfigurationEntity
{
Id = Guid.NewGuid(),
LibraryId = request.LibraryId,
PluginId = request.PluginId,
IsEnabled = request.IsEnabled,
LibraryId = command.LibraryId,
PluginId = command.PluginId,
IsEnabled = command.IsEnabled,
Rank = nextRank,
CreatedOnUtc = default,
CreatedBy = default,
Loaded 100 of 297 files, more files were not shown because too many files have changed in this diff. Show more