Rewords additional code comments as complete sentences

This commit is contained in:
BinaryAlley committed 2026-09-13 20:40:46 +03:00
1 parent 36e43b7999
commit 871644b3c9
23 files changed
+171 -140

No files matched your search

@@ -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
};
}
}
@@ -77,6 +77,36 @@ public static class ScheduledJobEntityMapping
);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to a copy that carries the provided status and execution timestamps.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="status">The status to assign to the converted entity.</param>
/// <param name="lastStartedOnUtc">The last start time to assign to the converted entity.</param>
/// <param name="lastCompletedOnUtc">The last completion time to assign to the converted entity.</param>
/// <returns>The converted repository entity.</returns>
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
};
}
/// <summary>
/// Creates the schedule of <paramref name="repositoryEntity"/> from its flattened schedule properties.
/// </summary>
@@ -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
);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to a copy that carries the provided completion time.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="completedOnUtc">The completion time to assign to the converted entity.</param>
/// <returns>The converted repository entity.</returns>
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
};
}
}
@@ -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<GetPermissionsQuery, Res
/// </returns>
public async Task<Result<IEnumerable<PermissionResponse>>> 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<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
Result<PaginatedResultDto<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
return getPermissionsResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors);
}
}
@@ -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<GetRolePermissionsQu
if (validationResult.Count > 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<RoleEntity?> getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
// Get the role from the repository and return its role permissions.
Result<RoleEntity?> getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsFailure)
return getRoleResult.Errors;
else if (getRoleResult.Value is null)
@@ -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<GetRolesQuery, Result<IEnumera
/// </returns>
public async Task<Result<IEnumerable<RoleResponse>>> 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<IEnumerable<RoleEntity>> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors);
Result<PaginatedResultDto<RoleEntity>> getRolesResult = await _roleRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
return getRolesResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors);
}
}
@@ -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<CheckInitialization
/// </returns>
public async Task<InitializationResponse> HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken)
{
// if the repository reports an error, or there are no users, the application has not been initialized
Result<IEnumerable<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken);
// If the repository reports an error, or there are no users, the application has not been initialized.
Result<PaginatedResultDto<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken);
if (!selectUsersResult.IsFailure)
return new InitializationResponse(selectUsersResult.Value.Any());
return new InitializationResponse(selectUsersResult.Value.Data.Any());
return new InitializationResponse(false);
}
}
@@ -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<GetLibrariesQuery, Result<
/// </returns>
public async Task<Result<LibraryResponse[]>> 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<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
// Get the libraries from the repository.
Result<PaginatedResultDto<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync<BaseFilterDto>(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())];
@@ -53,14 +53,14 @@ public class GetPluginSettingsQueryHandler : IQueryHandler<GetPluginSettingsQuer
if (validationResult.Count > 0)
return validationResult;
Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
Result<PluginEntity?> 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<PluginSettingDescriptorResponse> schema = loadedPlugin is not null
? loadedPlugin.GetSettingsSchema().Select(setting => setting.ToResponse()).ToList()
@@ -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<GetThemesQuery, Result<IReadO
/// </returns>
public async Task<Result<IReadOnlyList<ThemeResponse>>> HandleAsync(GetThemesQuery query, CancellationToken cancellationToken)
{
Result<IEnumerable<ThemeEntity>> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<PaginatedResultDto<ThemeEntity>> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync<BaseFilterDto>(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<IReadOnlyList<ThemeResponse>>([.. getThemesResult.Value
// Deleted bundled themes are returned as well, so the administration page can offer to restore them.
return Result.From<IReadOnlyList<ThemeResponse>>([.. 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())]);
@@ -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<GetUsersQuery, Result<IEnumera
/// </returns>
public async Task<Result<IEnumerable<UserResponse>>> 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<IEnumerable<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors);
Result<PaginatedResultDto<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
return getRolesResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using System;
#endregion
@@ -21,9 +22,9 @@ public abstract class Entity<TId> : IEquatable<Entity<TId>> where TId : notnull
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets the date and time when the entity was last updated.
/// Gets the date and time when the entity was last updated, if applicable.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
public Optional<DateTime> UpdatedOnUtc { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Entity{TId}"/> class.
@@ -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
/// <param name="languageCode">The ISO 639-1 two-letter language code.</param>
/// <param name="languageName">The full name of the language in English.</param>
/// <param name="nativeName">The optional native name of the language.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="LanguageInfo"/>, or an error message.
/// </returns>
public static Result<LanguageInfo> Create(string? languageCode, string? languageName, Optional<string> nativeName)
/// <returns>The created <see cref="LanguageInfo"/>.</returns>
public static LanguageInfo Create(string languageCode, string languageName, Optional<string> 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);
}
@@ -185,7 +185,7 @@ public sealed class Book : AggregateRoot<BookId>
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<BookId>
IEnumerable<BookMediaContributor> contributors,
List<BookRating> ratings)
{
// TODO: enforce invariants
// TODO: enforce invariants.
return new Book(
BookId.CreateUnique(),
libraryId,
@@ -256,7 +256,7 @@ public sealed class Book : AggregateRoot<BookId>
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<BookId>
IEnumerable<BookMediaContributor> contributors,
List<BookRating> ratings)
{
// TODO: enforce invariants
// TODO: enforce invariants.
return new Book(
id,
libraryId,
@@ -350,7 +350,7 @@ public sealed class Book : AggregateRoot<BookId>
/// <param name="contributors">The media contributors of the book.</param>
public void UpdateContributors(IReadOnlyCollection<BookMediaContributor> 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<BookId>
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();
@@ -40,15 +40,15 @@ public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy
if (context is not LibraryOwnershipPolicyContext libraryContext)
return false;
// admins can access any media library
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
// Admins can access any media library.
Result<UserEntity?> 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<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken).ConfigureAwait(false);
// Regular users can only access the media libraries they own.
Result<LibraryEntity?> 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;
@@ -41,11 +41,11 @@ public class Over18Policy : IOver18Policy
/// <returns><see langword="true"/> if the policy evaluation succeeds, <see langword="false"/> otherwise.</returns>
public async Task<bool> EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken)
{
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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;
@@ -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
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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<IDomainEventPublisher>()!;
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<string>.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.
}
}
}
@@ -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
/// <returns>The bare file name, or <see langword="null"/> when the path contains no usable file name.</returns>
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;
}
@@ -224,18 +224,21 @@ public class ApiHttpClient : IApiHttpClient
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="fileStream">The stream of the file to upload.</param>
/// <param name="fileName">The name of the file to upload.</param>
/// <param name="fileStream">The stream of the file to upload, or <see langword="null"/> to send a multipart form without any file.</param>
/// <param name="fileName">The name of the file to upload, or <see langword="null"/> when no file is sent.</param>
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
public async Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default)
public async Task<TResponse> PutMultipartAsync<TResponse>(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)
{
@@ -62,12 +62,12 @@ public interface IApiHttpClient
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="fileStream">The stream of the file to upload.</param>
/// <param name="fileName">The name of the file to upload.</param>
/// <param name="fileStream">The stream of the file to upload, or <see langword="null"/> to send a multipart form without any file.</param>
/// <param name="fileName">The name of the file to upload, or <see langword="null"/> when no file is sent.</param>
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default);
Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
@@ -31,20 +31,20 @@ public class ThemeCachePreferenceService
/// Gets whether the theme cache is enabled for the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The unique identifier of the user whose preference is read.</param>
/// <param name="defaultValue">The value used when the user did not express a preference yet.</param>
/// <param name="isCachingEnabledByDefault">The value used when the user did not express a preference yet.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> when the theme cache is enabled for the user, <see langword="false"/> otherwise.</returns>
public async Task<bool> GetAsync(Guid userId, bool defaultValue, CancellationToken cancellationToken = default)
public async Task<bool> GetAsync(Guid userId, bool isCachingEnabledByDefault, CancellationToken cancellationToken = default)
{
bool? preference = await _hybridCache.GetOrCreateAsync(
BuildKey(userId),
(cancellationToken) => new ValueTask<bool?>(defaultValue),
(cancellationToken) => new ValueTask<bool?>(isCachingEnabledByDefault),
new HybridCacheEntryOptions()
{
Expiration = s_preferenceLifetime
},
cancellationToken: cancellationToken).ConfigureAwait(false);
return preference ?? defaultValue;
return preference ?? isCachingEnabledByDefault;
}
/// <summary>
@@ -56,7 +56,7 @@ public class ThemeCachePreferenceService
/// <returns>An awaitable task representing the asynchronous operation.</returns>
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
@@ -20,7 +20,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
private readonly List<Error> _instanceAwarePredicateErrors = [];
private Error currentError = Error.Validation();
private Func<TRequest, bool>? condition;
private bool lastAddedPredicateIsInstanceAware;
private bool isLastAddedPredicateInstanceAware;
private AbstractValidator<TItem>? _childValidator;
/// <summary>
@@ -41,7 +41,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
{
_predicates.Add(predicate);
_predicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = false;
isLastAddedPredicateInstanceAware = false;
return this;
}
@@ -54,7 +54,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
{
_instanceAwarePredicates.Add(predicate);
_instanceAwarePredicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = true;
isLastAddedPredicateInstanceAware = true;
return this;
}
@@ -76,12 +76,12 @@ 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)
{
// 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<TRequest, TItem> : IValidationRule<T
/// <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.
// Evaluate the condition first, if it returns false, skip validation entirely..
if (condition is not null && !condition(instance))
yield break;
@@ -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<LanguageInfo> result = LanguageInfo.Create("EN", "English", Optional<string>.Some("English"));
LanguageInfo result = LanguageInfo.Create("EN", "English", Optional<string>.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<LanguageInfo> result = LanguageInfo.Create(languageCode, "English", Optional<string>.None());
LanguageInfo result = LanguageInfo.Create("en", "English", Optional<string>.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<LanguageInfo> result = LanguageInfo.Create("en", languageName, Optional<string>.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<LanguageInfo> result = LanguageInfo.Create(languageCode, "English", Optional<string>.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]