diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
index 90f36343..be721acb 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
@@ -26,7 +26,7 @@ public static class LibraryMapping
LibraryType = domainEntity.LibraryType,
UserId = domainEntity.UserId.Value,
ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })],
- CoverImage = domainEntity.CoverImage,
+ CoverImage = domainEntity.CoverImage.HasValue ? domainEntity.CoverImage.Value : null,
IsEnabled = domainEntity.IsEnabled,
IsLocked = domainEntity.IsLocked,
CanDownloadMetadataFromWeb = domainEntity.CanDownloadMetadataFromWeb,
@@ -46,8 +46,9 @@ public static class LibraryMapping
})],
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
- UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
- UpdatedBy = Guid.Empty
+ // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
+ UpdatedOnUtc = null,
+ UpdatedBy = null
};
}
}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs
index 23734cb6..a2dd9855 100644
--- a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs
@@ -77,6 +77,36 @@ public static class ScheduledJobEntityMapping
);
}
+ ///
+ /// Converts to a copy that carries the provided status and execution timestamps.
+ ///
+ /// The repository entity to be converted.
+ /// The status to assign to the converted entity.
+ /// The last start time to assign to the converted entity.
+ /// The last completion time to assign to the converted entity.
+ /// The converted repository entity.
+ public static ScheduledJobEntity ToUpdatedRepositoryEntity(this ScheduledJobEntity repositoryEntity, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
+ {
+ return new ScheduledJobEntity
+ {
+ Id = repositoryEntity.Id,
+ Name = repositoryEntity.Name,
+ TaskType = repositoryEntity.TaskType,
+ ScheduleType = repositoryEntity.ScheduleType,
+ IntervalMinutes = repositoryEntity.IntervalMinutes,
+ Hour = repositoryEntity.Hour,
+ Minute = repositoryEntity.Minute,
+ Status = status,
+ OwnerUserId = repositoryEntity.OwnerUserId,
+ LastStartedOnUtc = lastStartedOnUtc,
+ LastCompletedOnUtc = lastCompletedOnUtc,
+ CreatedOnUtc = repositoryEntity.CreatedOnUtc,
+ CreatedBy = repositoryEntity.CreatedBy,
+ UpdatedOnUtc = repositoryEntity.UpdatedOnUtc,
+ UpdatedBy = repositoryEntity.UpdatedBy
+ };
+ }
+
///
/// Creates the schedule of from its flattened schedule properties.
///
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs
index 2ac77c66..5883d056 100644
--- a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
+using System;
#endregion
namespace Lumina.Application.Common.Mapping.Scheduling;
@@ -26,4 +27,28 @@ public static class ScheduledJobExecutionEntityMapping
repositoryEntity.CompletedOnUtc
);
}
+
+ ///
+ /// Converts to a copy that carries the provided completion time.
+ ///
+ /// The repository entity to be converted.
+ /// The completion time to assign to the converted entity.
+ /// The converted repository entity.
+ public static ScheduledJobExecutionEntity ToUpdatedRepositoryEntity(this ScheduledJobExecutionEntity repositoryEntity, DateTime? completedOnUtc)
+ {
+ return new ScheduledJobExecutionEntity
+ {
+ Id = repositoryEntity.Id,
+ ScheduledJobId = repositoryEntity.ScheduledJobId,
+ TaskType = repositoryEntity.TaskType,
+ IsCycleRun = repositoryEntity.IsCycleRun,
+ WasCycleActive = repositoryEntity.WasCycleActive,
+ StartedOnUtc = repositoryEntity.StartedOnUtc,
+ CompletedOnUtc = completedOnUtc,
+ CreatedOnUtc = repositoryEntity.CreatedOnUtc,
+ CreatedBy = repositoryEntity.CreatedBy,
+ UpdatedOnUtc = repositoryEntity.UpdatedOnUtc,
+ UpdatedBy = repositoryEntity.UpdatedBy
+ };
+ }
}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs
index 977992b9..3ea703dc 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs
@@ -1,14 +1,15 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
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.DTO.Filtering;
+using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
+using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -49,17 +50,17 @@ public class GetPermissionsQueryHandler : IQueryHandler
public async Task>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken)
{
- // an authenticated request must always carry a user identity
+ // An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
- // only admins can see the list of authorization permissions
+ // Only admins can see the list of authorization permissions.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
- Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
- return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
+ Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
+ return getPermissionsResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors);
}
}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
index 59920ec7..c428ffd5 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
@@ -10,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
+using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -57,18 +57,19 @@ public class GetRolePermissionsQueryHandler : IQueryHandler 0)
return validationResult;
- // an authenticated request must always carry a user identity
+ // An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
- // only admins can see the list of authorization roles
+ // Only admins can see the list of authorization roles.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
- // get the role from the repository and return its role permissions
- Result getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
+
+ // Get the role from the repository and return its role permissions.
+ Result getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsFailure)
return getRoleResult.Errors;
else if (getRoleResult.Value is null)
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs
index db595254..1cd48b58 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
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.DTO.Filtering;
+using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
+using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -49,17 +51,18 @@ public class GetRolesQueryHandler : IQueryHandler
public async Task>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken)
{
- // an authenticated request must always carry a user identity
+ // An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
- // only admins can see the list of authorization roles
+ // Only admins can see the list of authorization roles.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
- Result> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
- return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors);
+
+ Result> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
+ return getRolesResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors);
}
}
diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs
index 8f2dba4c..3d647435 100644
--- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs
+++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs
@@ -1,11 +1,11 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
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.Application.Common.DTO.Filtering;
+using Lumina.Application.Common.DTO.Pagination;
using Lumina.Contracts.Responses.UsersManagement;
-using System.Collections.Generic;
+using Lumina.Domain.Common.Primitives;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -38,10 +38,10 @@ public class CheckInitializationQueryHandler : IQueryHandler
public async Task HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken)
{
- // if the repository reports an error, or there are no users, the application has not been initialized
- Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken);
+ // If the repository reports an error, or there are no users, the application has not been initialized.
+ Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken);
if (!selectUsersResult.IsFailure)
- return new InitializationResponse(selectUsersResult.Value.Any());
+ return new InitializationResponse(selectUsersResult.Value.Data.Any());
return new InitializationResponse(false);
}
}
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs
index 620aa06b..56b7ac87 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs
@@ -4,6 +4,8 @@ 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.DTO.Filtering;
+using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
@@ -53,24 +55,24 @@ public class GetLibrariesQueryHandler : IQueryHandler
public async Task> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
{
- // an authenticated request must always carry a user identity
+ // An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
- // get the libraries from the repository
- Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ // Get the libraries from the repository.
+ Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
return getLibrariesResult.Errors;
- // admins can see all libraries
+ // Admins can see all libraries.
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
- return Result.From(getLibrariesResult.Value.Select(library => library.ToResponse()).ToArray());
+ return Result.From(getLibrariesResult.Value.Data.Select(library => library.ToResponse()).ToArray());
else
{
- // for regular users, only take the libraries that belong to them
- LibraryResponse[] userLibraries = [.. getLibrariesResult.Value
+ // For regular users, only take the libraries that belong to them.
+ LibraryResponse[] userLibraries = [.. getLibrariesResult.Value.Data
.Where(library => library.UserId == userId)
.Select(library => library.ToResponse())];
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
index 28a8eae3..f69e02fa 100644
--- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
@@ -53,14 +53,14 @@ public class GetPluginSettingsQueryHandler : IQueryHandler 0)
return validationResult;
- Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
+ Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsFailure)
return getPluginResult.Errors;
PluginEntity? pluginEntity = getPluginResult.Value;
if (pluginEntity is null)
return Errors.Plugins.PluginNotFound;
- // the schema comes from the loaded plugin, the current values from the storage medium
+ // The schema comes from the loaded plugin, the current values from the storage medium.
IPlugin? loadedPlugin = _pluginManager.GetPlugin(query.PluginId);
IReadOnlyList schema = loadedPlugin is not null
? loadedPlugin.GetSettingsSchema().Select(setting => setting.ToResponse()).ToList()
diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs
index 03eb9b5a..b4f64978 100644
--- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs
+++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs
@@ -2,6 +2,8 @@
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DTO.Filtering;
+using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
@@ -41,14 +43,14 @@ public class GetThemesQueryHandler : IQueryHandler
public async Task>> HandleAsync(GetThemesQuery query, CancellationToken cancellationToken)
{
- Result> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ Result> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure)
return getThemesResult.Errors;
- // deleted bundled themes are returned as well, so the administration page can offer to restore them
- return Result.From>([.. getThemesResult.Value
+ // Deleted bundled themes are returned as well, so the administration page can offer to restore them.
+ return Result.From>([.. getThemesResult.Value.Data
.OrderBy(theme => theme.IsDeleted)
- // the shipped bundled themes are listed before the user themes, so the defaults stay the most visible
+ // The shipped bundled themes are listed before the user themes, so the defaults stay the most visible.
.ThenByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled)
.ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)
.Select(theme => theme.ToResponse())]);
diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs
index f6381a4c..1797831b 100644
--- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs
+++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs
@@ -4,6 +4,8 @@ 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.Application.Common.DTO.Filtering;
+using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
@@ -50,17 +52,17 @@ public class GetUsersQueryHandler : IQueryHandler
public async Task>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken)
{
- // an authenticated request must always carry a user identity
+ // An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
- // only admins can see the list of users
+ // Only admins can see the list of users.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
- Result> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
- return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors);
+ Result> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
+ return getRolesResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors);
}
}
diff --git a/src/Lumina.Domain/Common/Models/Core/Entity.cs b/src/Lumina.Domain/Common/Models/Core/Entity.cs
index e100c991..e381af5f 100644
--- a/src/Lumina.Domain/Common/Models/Core/Entity.cs
+++ b/src/Lumina.Domain/Common/Models/Core/Entity.cs
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Common.Primitives;
using System;
#endregion
@@ -21,9 +22,9 @@ public abstract class Entity : IEquatable> where TId : notnull
public DateTime CreatedOnUtc { get; set; }
///
- /// Gets the date and time when the entity was last updated.
+ /// Gets the date and time when the entity was last updated, if applicable.
///
- public DateTime? UpdatedOnUtc { get; set; }
+ public Optional UpdatedOnUtc { get; set; }
///
/// Initializes a new instance of the class.
diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs
index c0231804..7420583b 100644
--- a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs
+++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs
@@ -2,7 +2,6 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.Models.Core;
-using Lumina.Domain.Common.Errors;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
@@ -49,17 +48,9 @@ public class LanguageInfo : ValueObject
/// The ISO 639-1 two-letter language code.
/// The full name of the language in English.
/// The optional native name of the language.
- ///
- /// An containing either a successfully created , or an error message.
- ///
- public static Result Create(string? languageCode, string? languageName, Optional nativeName)
+ /// The created .
+ public static LanguageInfo Create(string languageCode, string languageName, Optional nativeName)
{
- if (string.IsNullOrWhiteSpace(languageCode))
- return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty;
- if (string.IsNullOrWhiteSpace(languageName))
- return Errors.Errors.Metadata.LanguageNameCannotBeEmpty;
- if (languageCode.Length != 2)
- return Errors.Errors.Metadata.InvalidIsoCode;
return new LanguageInfo(languageCode, languageName, nativeName);
}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs
index 8fab9f39..9f4ccca6 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs
@@ -185,7 +185,7 @@ public sealed class Book : AggregateRoot
BarnesAndNobleId = barnesAndNobleId;
AppleBooksId = appleBooksId;
CreatedOnUtc = createdOnUtc;
- UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null;
+ UpdatedOnUtc = updatedOnUtc;
_isbns = isbns;
_contributors = [.. contributors];
_ratings = ratings;
@@ -237,7 +237,7 @@ public sealed class Book : AggregateRoot
IEnumerable contributors,
List ratings)
{
- // TODO: enforce invariants
+ // TODO: enforce invariants.
return new Book(
BookId.CreateUnique(),
libraryId,
@@ -256,7 +256,7 @@ public sealed class Book : AggregateRoot
googleBooksId,
barnesAndNobleId,
appleBooksId,
- DateTime.UtcNow, // TODO: should be IDateTimeProvider
+ DateTime.UtcNow, // TODO: should be IDateTimeProvider.
default,
isbns,
contributors,
@@ -316,7 +316,7 @@ public sealed class Book : AggregateRoot
IEnumerable contributors,
List ratings)
{
- // TODO: enforce invariants
+ // TODO: enforce invariants.
return new Book(
id,
libraryId,
@@ -350,7 +350,7 @@ public sealed class Book : AggregateRoot
/// The media contributors of the book.
public void UpdateContributors(IReadOnlyCollection contributors)
{
- // replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate
+ // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate.
_contributors.Clear();
_contributors.UnionWith(contributors);
}
@@ -406,7 +406,7 @@ public sealed class Book : AggregateRoot
GoogleBooksId = googleBooksId;
BarnesAndNobleId = barnesAndNobleId;
AppleBooksId = appleBooksId;
- // replace the contents of the collections in place, preserving the readonly reference invariants of the aggregate
+ // Replace the contents of the collections in place, preserving the readonly reference invariants of the aggregate.
_isbns.Clear();
_isbns.AddRange(isbns);
_ratings.Clear();
diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs
index 07f903a3..c3269050 100644
--- a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs
+++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs
@@ -40,15 +40,15 @@ public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy
if (context is not LibraryOwnershipPolicyContext libraryContext)
return false;
- // admins can access any media library
- Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
+ // Admins can access any media library.
+ Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure || getUserResult.Value is null)
return false;
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin")
return true;
- // regular users can only access the media libraries they own
- Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken).ConfigureAwait(false);
+ // Regular users can only access the media libraries they own.
+ Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
return false;
return getLibraryResult.Value.UserId == userId;
diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs
index 474db2aa..719818c9 100644
--- a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs
+++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs
@@ -41,11 +41,11 @@ public class Over18Policy : IOver18Policy
/// if the policy evaluation succeeds, otherwise.
public async Task EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken)
{
- Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
+ Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure || getUserResult.Value is null)
return false;
- // TODO: uncomment when Date of Birth is implemented for users registration
+ // TODO: uncomment when Date of Birth is implemented for users registration.
//if (!getUserResult.Value.DateOfBirth.HasValue)
// return false;
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs
index cade5637..42f35c39 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
@@ -26,16 +27,16 @@ internal static class ScanFailurePublisher
/// Cancellation token that can be used to stop the execution.
public static async Task PublishAsync(IServiceScopeFactory serviceScopeFactory, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, Exception exception, CancellationToken cancellationToken)
{
- // failure reporting is best-effort, a failure to report the failure must not crash the job processing
+ // Failure reporting is best-effort, a failure to report the failure must not crash the job processing.
try
{
await using AsyncServiceScope asyncServiceScope = serviceScopeFactory.CreateAsyncScope();
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!;
- await domainEventPublisher.PublishAsync(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false);
+ await domainEventPublisher.PublishAsync(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, Optional.FromNullable(exception.Message)), cancellationToken).ConfigureAwait(false);
}
catch
{
- // the failure reporting is best-effort, as the exception cannot be reported if the reporting itself fails
+ // The failure reporting is best-effort, as the exception cannot be reported if the reporting itself fails.
}
}
}
diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs
index eb897343..7e02ce87 100644
--- a/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs
+++ b/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs
@@ -108,21 +108,21 @@ internal sealed class PluginInstaller : IPluginInstaller
{
using ZipArchive zipArchive = new(archive);
Directory.CreateDirectory(_pluginsDirectory);
- bool foundAssembly = false;
+ bool isAssemblyFound = false;
foreach (ZipArchiveEntry entry in zipArchive.Entries)
{
cancellationToken.ThrowIfCancellationRequested();
string? safeFileName = GetSafeFileName(entry.FullName);
if (safeFileName is null || !string.Equals(Path.GetExtension(safeFileName), ".dll", StringComparison.OrdinalIgnoreCase))
continue;
- foundAssembly = true;
+ isAssemblyFound = true;
string destinationPath = Path.Combine(_pluginsDirectory, safeFileName);
await using Stream entryStream = entry.Open();
await using FileStream outputStream = new(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None);
await entryStream.CopyToAsync(outputStream, cancellationToken).ConfigureAwait(false);
}
- if (!foundAssembly)
+ if (!isAssemblyFound)
return Errors.Plugins.PluginArchiveContainsNoAssemblies;
return Result.Success;
}
@@ -135,8 +135,8 @@ internal sealed class PluginInstaller : IPluginInstaller
/// The bare file name, or when the path contains no usable file name.
private static string? GetSafeFileName(string path)
{
- // a backslash is not a directory separator on non-Windows platforms, so it is normalized to '/' first,
- // after which Path.GetFileName can strip any directory component on every platform
+ // A backslash is not a directory separator on non-Windows platforms, so it is normalized to '/' first,
+ // after which Path.GetFileName can strip any directory component on every platform.
string fileName = Path.GetFileName(path.Replace('\\', '/'));
return fileName is "" or "." or ".." ? null : fileName;
}
diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
index a0c9bd2d..bb13b274 100644
--- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
+++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
@@ -224,18 +224,21 @@ public class ApiHttpClient : IApiHttpClient
///
/// The expected type of the response content.
/// The API endpoint where the request is being sent.
- /// The stream of the file to upload.
- /// The name of the file to upload.
+ /// The stream of the file to upload, or to send a multipart form without any file.
+ /// The name of the file to upload, or when no file is sent.
/// The name of the form field carrying the file.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the PUT request.
- public async Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default)
+ public async Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default)
{
- // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
using MultipartFormDataContent form = [];
- using StreamContent fileContent = new(fileStream);
- fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
- form.Add(fileContent, fieldName, fileName);
+ if (fileStream is not null)
+ {
+ // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
+ StreamContent fileContent = new(fileStream);
+ fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
+ form.Add(fileContent, fieldName, fileName ?? string.Empty);
+ }
using HttpRequestMessage request = new(HttpMethod.Put, endpoint)
{
diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs
index ae7d9d45..77bae8cd 100644
--- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs
+++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs
@@ -62,12 +62,12 @@ public interface IApiHttpClient
///
/// The expected type of the response content.
/// The API endpoint where the request is being sent.
- /// The stream of the file to upload.
- /// The name of the file to upload.
+ /// The stream of the file to upload, or to send a multipart form without any file.
+ /// The name of the file to upload, or when no file is sent.
/// The name of the form field carrying the file.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the PUT request.
- Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default);
+ Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default);
///
/// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result.
diff --git a/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs
index d6990cdb..d9bd7653 100644
--- a/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs
+++ b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs
@@ -31,20 +31,20 @@ public class ThemeCachePreferenceService
/// Gets whether the theme cache is enabled for the user identified by .
///
/// The unique identifier of the user whose preference is read.
- /// The value used when the user did not express a preference yet.
+ /// The value used when the user did not express a preference yet.
/// Cancellation token that can be used to stop the execution.
/// when the theme cache is enabled for the user, otherwise.
- public async Task GetAsync(Guid userId, bool defaultValue, CancellationToken cancellationToken = default)
+ public async Task GetAsync(Guid userId, bool isCachingEnabledByDefault, CancellationToken cancellationToken = default)
{
bool? preference = await _hybridCache.GetOrCreateAsync(
BuildKey(userId),
- (cancellationToken) => new ValueTask(defaultValue),
+ (cancellationToken) => new ValueTask(isCachingEnabledByDefault),
new HybridCacheEntryOptions()
{
Expiration = s_preferenceLifetime
},
cancellationToken: cancellationToken).ConfigureAwait(false);
- return preference ?? defaultValue;
+ return preference ?? isCachingEnabledByDefault;
}
///
@@ -56,7 +56,7 @@ public class ThemeCachePreferenceService
/// An awaitable task representing the asynchronous operation.
public async Task SetAsync(Guid userId, bool isEnabled, CancellationToken cancellationToken = default)
{
- // the value is stored as a nullable bool, matching the read type, since HybridCache keys entries by their stored type
+ // The value is stored as a nullable bool, matching the read type, since HybridCache keys entries by their stored type.
await _hybridCache.SetAsync(BuildKey(userId), (bool?)isEnabled, new HybridCacheEntryOptions()
{
Expiration = s_preferenceLifetime
diff --git a/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs b/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs
index 22822f7c..58b4d427 100644
--- a/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs
+++ b/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs
@@ -20,7 +20,7 @@ internal sealed class ValidationRuleForEach : IValidationRule _instanceAwarePredicateErrors = [];
private Error currentError = Error.Validation();
private Func? condition;
- private bool lastAddedPredicateIsInstanceAware;
+ private bool isLastAddedPredicateInstanceAware;
private AbstractValidator? _childValidator;
///
@@ -41,7 +41,7 @@ internal sealed class ValidationRuleForEach : IValidationRule : IValidationRule : IValidationRuleThe current instance for method chaining.
public IRuleBuilder WithError(Error error)
{
- // validation rules always produce validation errors, regardless of the error type of the source 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)
+ if (isLastAddedPredicateInstanceAware && _instanceAwarePredicateErrors.Count > 0)
_instanceAwarePredicateErrors[^1] = validationError;
- else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
+ else if (!isLastAddedPredicateInstanceAware && _predicateErrors.Count > 0)
_predicateErrors[^1] = validationError;
return this;
}
@@ -106,7 +106,7 @@ internal sealed class ValidationRuleForEach : IValidationRuleOne per failing predicate, per item; empty if every item passes.
public IEnumerable Validate(TRequest instance)
{
- // evaluate the condition first, if it returns false, skip validation entirely.
+ // Evaluate the condition first, if it returns false, skip validation entirely..
if (condition is not null && !condition(instance))
yield break;
diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs
index 12cd4adb..38e8b312 100644
--- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs
+++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
-using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
@@ -20,56 +19,25 @@ public class LanguageInfoTests
public void Create_WhenCalledWithValidValues_ShouldCreateLanguageInfoWithLowercaseCode()
{
// Act
- Result result = LanguageInfo.Create("EN", "English", Optional.Some("English"));
+ LanguageInfo result = LanguageInfo.Create("EN", "English", Optional.Some("English"));
// Assert
- Assert.False(result.IsFailure);
- Assert.Equal("en", result.Value.LanguageCode);
- Assert.Equal("English", result.Value.LanguageName);
- Assert.True(result.Value.NativeName.HasValue);
- Assert.Equal("English", result.Value.NativeName.Value);
+ Assert.Equal("en", result.LanguageCode);
+ Assert.Equal("English", result.LanguageName);
+ Assert.True(result.NativeName.HasValue);
+ Assert.Equal("English", result.NativeName.Value);
}
- [Theory]
- [InlineData(null)] // null language code
- [InlineData("")] // empty language code
- [InlineData(" ")] // whitespace language code
- public void Create_WhenLanguageCodeIsNullOrWhitespace_ShouldReturnError(string? languageCode)
+ [Fact]
+ public void Create_WhenNativeNameIsMissing_ShouldCreateLanguageInfoWithoutNativeName()
{
// Act
- Result result = LanguageInfo.Create(languageCode, "English", Optional.None());
+ LanguageInfo result = LanguageInfo.Create("en", "English", Optional.None());
// Assert
- Assert.True(result.IsFailure);
- Assert.Equal(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, result.FirstError);
- }
-
- [Theory]
- [InlineData(null)] // null language name
- [InlineData("")] // empty language name
- [InlineData(" ")] // whitespace language name
- public void Create_WhenLanguageNameIsNullOrWhitespace_ShouldReturnError(string? languageName)
- {
- // Act
- Result result = LanguageInfo.Create("en", languageName, Optional.None());
-
- // Assert
- Assert.True(result.IsFailure);
- Assert.Equal(DomainErrors.Metadata.LanguageNameCannotBeEmpty, result.FirstError);
- }
-
- [Theory]
- [InlineData("e")] // single character code
- [InlineData("eng")] // three character code
- [InlineData("english")] // long code
- public void Create_WhenLanguageCodeIsNotTwoCharactersLong_ShouldReturnError(string languageCode)
- {
- // Act
- Result result = LanguageInfo.Create(languageCode, "English", Optional.None());
-
- // Assert
- Assert.True(result.IsFailure);
- Assert.Equal(DomainErrors.Metadata.InvalidIsoCode, result.FirstError);
+ Assert.Equal("en", result.LanguageCode);
+ Assert.Equal("English", result.LanguageName);
+ Assert.False(result.NativeName.HasValue);
}
[Fact]