diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs index 64e841e5..c87a10b2 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -56,25 +56,24 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan from the repository - Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + // Get the library scan from the repository. + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // cancel the media library scan + // Cancel the media library scan. Result cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value); if (cancelScanResult.IsFailure) throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors); - // release the scan processing resources - + // Release the scan processing resources. MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId)); _mediaLibrariesScanCancellationTracker.RemoveScan(compositeId); _mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index d77ae07f..6895eaee 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -46,25 +46,25 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan that was queued, from the repository - Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + // Get the library scan that was queued, from the repository. + Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScanResult.IsFailure) throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); if (getLibraryScanResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository entity to a domain entity + // Convert the repository entity to a domain entity. Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // start the media library scan + // Start the media library scan. Result startScanResult = await _mediaLibraryScanningService.StartScanAsync( libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false); if (startScanResult.IsFailure) throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors); - // queue any domain events + // Queue any domain events. foreach (IDomainEvent queuedDomainEvent in libraryScanDomainResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(queuedDomainEvent); } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs index d9a35d7a..d1f0ec67 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs @@ -64,20 +64,20 @@ public class GetLibraryQueryHandler : 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 ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library with the specified id from the repository - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); + // Get the library with the specified id from the repository. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can see all libraries; for everyone else, only the libraries they own + // Admins can see all libraries; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.Id), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs index 0ea12e65..3de2d660 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs @@ -71,20 +71,20 @@ public class GetLibraryScanProgressQueryHandler : 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 ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library with the specified id from the repository - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + // Get the library with the specified id from the repository. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can view the progress of any library scan; for everyone else, only the ones of the libraries they own + // Admins can view the progress of any library scan; for everyone else, only the ones of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs index e5f518db..25658eb6 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -58,28 +60,30 @@ public class GetLibraryArtworkProvidersQueryHandler : 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 ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can read the artwork providers of any library; for everyone else, only their own libraries + // Admins can read the artwork providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the artwork provider configurations registered for the library, so that only the providers it actually has are returned. Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; - // build a plugin name lookup from the detected plugins - Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + // Build a plugin name lookup from the detected plugins, so that each configuration can be returned with its provider's display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) return getPluginsResult.Errors; - Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + // Return the configurations ordered by their rank, so the client sees the providers in the order they are applied. return getConfigurationsResult.Value .OrderBy(configuration => configuration.Rank) .Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty)) diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index 0143c65c..aab473ae 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -62,28 +64,30 @@ public class GetLibraryMetadataProvidersQueryHandler : 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 ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can read the metadata providers of any library; for everyone else, only their own libraries + // Admins can read the metadata providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the metadata provider configurations registered for the library, so that only the providers it actually has are returned. Result> getConfigurationsResult = await _providerConfigurationStore.GetConfigurationsAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; - // build a plugin name lookup from the detected plugins - Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + // Build a plugin name lookup from the detected plugins, so that each configuration can be returned with its provider's display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) return getPluginsResult.Errors; - Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + // Return the configurations ordered by their rank, so the client sees the providers in the order they are applied. return getConfigurationsResult.Value .OrderBy(configuration => configuration.Rank) .Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty)) diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs index 54acf7b6..ae8e36e1 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs @@ -58,22 +58,25 @@ public class GetUserPermissionsQueryHandler : 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 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; - // get the user from the repository and return its permissions - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + + // Get the user from the repository, so that a missing user is reported before its permissions are mapped. + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; + + // Return the permissions of the user, mapped to their response representations. return Result.From(getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission).ToResponses()); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs index 5b876904..fea42fc4 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs @@ -57,22 +57,25 @@ public class GetUserRoleQueryHandler : 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 authorization role + // Only admins can see the authorization role. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // get the user from the repository and return its roles - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + + // Get the user from the repository, so that a missing user is reported before its role is mapped. + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; + + // Return the role of the user, or null when the user has no role assigned. return Result.From(getUserResult.Value.UserRole?.Role.ToResponse()); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs index 668094c2..8120b5a2 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; @@ -14,7 +15,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext. /// /// Service for file system permissions. /// -internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: refactor towards abstractions that could allow testing +internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: Refactor towards abstractions that would allow testing. { private readonly IPlatformContextManager _platformContextManager; @@ -61,10 +62,10 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T switch (accessMode) { case FileAccessMode.ReadProperties: - // for properties, we only need to check if the path exists + // For properties, we only need to check if the path exists. return File.Exists(path) || Directory.Exists(path); case FileAccessMode.ReadContents: - // attempt to open the file for reading to verify read access + // Attempt to open the file for reading, to verify read access. if (File.Exists(path)) { FileStream fileStream = File.OpenRead(path); @@ -73,7 +74,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T } return false; case FileAccessMode.Write: - // attempt to open the file for writing or verify directory exists + // Attempt to open the file for writing, or verify that the directory exists. if (File.Exists(path)) { FileStream fileStream = File.OpenWrite(path); @@ -82,11 +83,11 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T } return Directory.Exists(path); case FileAccessMode.Execute: - // check Unix execute permission bit + // Check the Unix execute permission bit. FileInfo fileInfo = new(path); return (fileInfo.UnixFileMode & UnixFileMode.UserExecute) != 0; case FileAccessMode.ListDirectory: - // attempt to list directory contents to verify access + // Attempt to list the directory contents, to verify access. if (Directory.Exists(path)) { string[] _ = Directory.GetFiles(path); @@ -96,11 +97,11 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T case FileAccessMode.Delete: if (File.Exists(path)) { - // for files, check if parent directory is writable - string? directoryPath = Path.GetDirectoryName(path); - return directoryPath != null && HasWriteAccessToDirectory(directoryPath); + // For files, check if the parent directory is writable. + Optional directoryPath = Optional.FromNullable(Path.GetDirectoryName(path)); + return directoryPath.HasValue && HasWriteAccessToDirectory(directoryPath.Value); } - // for directories, check if the directory itself is writable + // For directories, check if the directory itself is writable. return Directory.Exists(path) && HasWriteAccessToDirectory(path); default: throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode"); @@ -108,11 +109,11 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T } catch (UnauthorizedAccessException) { - return false; // access denied by the operating system + return false; // Access denied by the operating system. } catch (IOException) { - return false; // IO operation failed, indicating no access + return false; // IO operation failed, indicating no access. } } @@ -125,9 +126,9 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T { try { - // create a unique temporary filename + // Create a unique temporary filename. string temporaryFilePath = Path.Combine(path, string.Format(".test_{0}", Guid.NewGuid())); - // attempt to create and immediately delete a temporary file + // Attempt to create and immediately delete a temporary file. FileStream testStream = File.Create(temporaryFilePath); testStream.Dispose(); File.Delete(temporaryFilePath); @@ -154,7 +155,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T [SupportedOSPlatform("windows")] private static bool CanAccessPathWindows(string path, FileAccessMode accessMode, bool isFile = true) { - // translate to filesystem access modes (multiple can match per case) + // Translate to filesystem access modes (multiple can match per case). FileSystemRights rights = accessMode switch { FileAccessMode.ReadProperties => FileSystemRights.ReadAttributes, @@ -167,12 +168,12 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T }; if (rights == FileSystemRights.Delete) { - // when checking for delete permissions, we need to check the directory the file or directory resides in - string? parentDirectory = Directory.GetParent(path)?.FullName; - if (string.IsNullOrEmpty(parentDirectory)) - return false; // the path is either a root directory or has no parent, which we cannot delete - // checking for modify permission on the parent directory since delete requires modifying the parent contents - return HasAccess(FileSystemRights.Modify, parentDirectory, false); + // When checking for delete permissions, we need to check the directory the file or directory resides in. + Optional parentDirectory = Optional.FromNullable(Directory.GetParent(path)?.FullName); + if (!parentDirectory.HasValue || string.IsNullOrEmpty(parentDirectory.Value)) + return false; // The path is either a root directory or has no parent, which we cannot delete. + // Checking for the modify permission on the parent directory, since delete requires modifying the parent contents. + return HasAccess(FileSystemRights.Modify, parentDirectory.Value, false); } else if (HasAccess(rights, path, isFile)) @@ -181,9 +182,9 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T switch (accessMode) { case FileAccessMode.ReadProperties: - // just accessing file info for properties, without opening it + // Just access file info for properties, without opening it. FileSystemInfo fileSystemInfo = isFile ? new FileInfo(path) : new DirectoryInfo(path); - _ = fileSystemInfo.CreationTime; // trigger potential access denial + _ = fileSystemInfo.CreationTime; // Trigger a potential access denial. break; case FileAccessMode.ReadContents: using (FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) @@ -209,14 +210,14 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T [SupportedOSPlatform("windows")] private static bool HasAccess(FileSystemRights rights, string path, bool isFile = true) { - bool allowAccess = false; + bool doesAllowAccess = false; AuthorizationRuleCollection acl; WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new(identity); - // get the collection of authorization rules that apply to the specified directory + // Get the collection of authorization rules that apply to the specified directory. try { - // some paths (ex: C:\Windows\System32\config) throw "unauthorized" exceptions even when trying to check if one is authorized to access them - how dumb is that??... + // Some paths, such as C:\Windows\System32\config, throw unauthorized exceptions even when only checking whether access is allowed. if (isFile) { FileInfo fileInfo = new(path); @@ -228,18 +229,18 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T acl = directoryInfo.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); } foreach (FileSystemAccessRule accessRule in acl) - // Check if the current rule applies to the current user or the groups they belong to + // Check if the current rule applies to the current user or the groups they belong to. if (identity?.User?.Equals(accessRule.IdentityReference) == true || principal.IsInRole((SecurityIdentifier)accessRule.IdentityReference)) if (accessRule.AccessControlType.Equals(AccessControlType.Deny) && (accessRule.FileSystemRights & rights) == rights) - return false; // if there's a deny rule that matches the specified rights, return false immediately + return false; // If there is a deny rule that matches the specified rights, deny access immediately. else if (accessRule.AccessControlType.Equals(AccessControlType.Allow) && (accessRule.FileSystemRights & rights) == rights) - allowAccess = true; + doesAllowAccess = true; } catch { return false; } - return allowAccess; + return doesAllowAccess; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs index 08b46525..52897771 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs @@ -56,24 +56,24 @@ public class ThumbnailService : IThumbnailService /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. public async Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken) { - // first, get the type of the image file + // First, get the type of the image file. Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path, cancellationToken); if (imageTypeResult.IsFailure) return imageTypeResult.Errors; if (imageTypeResult.Value != ImageType.None) { - // then, get its bytes + // Then, get its bytes. Result resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); if (resultFileContents.IsFailure) return resultFileContents.Errors; byte[] fileContents = resultFileContents.Value; - // finally, resize or adjust quality based on image type - byte[]? adjustedImage = null; + // Finally, resize or adjust the quality based on the image type. + Optional adjustedImage = Optional.None(); if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000 or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA) - adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality, cancellationToken); - return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents); + adjustedImage = Optional.Some(await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality, cancellationToken)); + return new Thumbnail(imageTypeResult.Value, adjustedImage.HasValue ? adjustedImage.Value : fileContents); } else return Errors.Thumbnails.NoThumbnail; @@ -105,7 +105,7 @@ public class ThumbnailService : IThumbnailService case ImageType.PNG: { using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); - // PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression + // PNG is lossless, so quality adjustments do not apply in the same way; instead, the compression level is adjusted. int compressionLevel = MapRange(quality, 1, 100, 1, 9); PngEncoder encoder = new() { CompressionLevel = (PngCompressionLevel)compressionLevel }; @@ -115,11 +115,11 @@ public class ThumbnailService : IThumbnailService case ImageType.BMP: { using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); - await image.SaveAsync(outputMemoryStream, new PngEncoder(), cancellationToken); // convert BMP to PNG for compression + await image.SaveAsync(outputMemoryStream, new PngEncoder(), cancellationToken); // Convert BMP to PNG for compression. break; } default: - return imageBytes; // for unsupported formats, just return the original bytes + return imageBytes; // For unsupported formats, just return the original bytes. } return outputMemoryStream.ToArray(); } @@ -140,7 +140,7 @@ public class ThumbnailService : IThumbnailService double ratio = quality / 100.0; int newWidth = (int)(image.Width * ratio); int newHeight = (int)(image.Height * ratio); - // ensure new dimensions are not zero + // Ensure the new dimensions are not zero. newWidth = Math.Max(1, newWidth); newHeight = Math.Max(1, newHeight); ResizeOptions options = new() @@ -148,9 +148,9 @@ public class ThumbnailService : IThumbnailService Size = new Size(newWidth, newHeight), Mode = ResizeMode.Max }; - // resize the image to the specified size + // Resize the image to the specified size. image.Mutate(ctx => ctx.Resize(options)); - // save the resized image and return its bytes + // Save the resized image and return its bytes. switch (imageType) { case ImageType.BMP: @@ -166,7 +166,7 @@ public class ThumbnailService : IThumbnailService await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!, cancellationToken); break; default: - return imageBytes; // for unsupported formats, just return the original bytes + return imageBytes; // For unsupported formats, just return the original bytes. } return outputMemoryStream.ToArray(); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs index 34f5b47a..b72a8b1e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Runtime.InteropServices; @@ -11,7 +12,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext. /// public class PlatformContextManager : IPlatformContextManager { - private IPlatformContext? _currentPlatformContext; + private Optional _currentPlatformContext; private readonly IPlatformContextFactory _platformContextFactory; private readonly IOperatingSystemInfo _operatingSystemInfo; @@ -32,13 +33,13 @@ public class PlatformContextManager : IPlatformContextManager /// The current platform context. public IPlatformContext GetCurrentContext() { - // set a default context if none is set - if (_currentPlatformContext is null) + // Set a default context if none is set. + if (!_currentPlatformContext.HasValue) if (_operatingSystemInfo.IsOSPlatform(OSPlatform.Linux) || _operatingSystemInfo.IsOSPlatform(OSPlatform.OSX)) SetCurrentPlatform(PlatformType.Unix); else SetCurrentPlatform(PlatformType.Windows); - return _currentPlatformContext!; + return _currentPlatformContext.Value; } /// @@ -48,12 +49,12 @@ public class PlatformContextManager : IPlatformContextManager /// Thrown when an unsupported platform type is provided. public void SetCurrentPlatform(PlatformType platformType) { - // determine the correct context based on platformType - _currentPlatformContext = platformType switch + // Determine the correct context based on the platform type. + _currentPlatformContext = Optional.Some(platformType switch { PlatformType.Unix => _platformContextFactory.CreateStrategy(), PlatformType.Windows => _platformContextFactory.CreateStrategy(), _ => throw new ArgumentException($"Unsupported platform type: {platformType}"), - }; + }); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index c49151d9..91d8ee8f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -43,12 +43,12 @@ public class Library : AggregateRoot /// /// Gets the path of the image file used as the cover for the library. /// - public string? CoverImage { get; private set; } + public Optional CoverImage { get; private set; } /// /// Gets the path of the image file chosen by the user to be used as the cover for the library. /// - public string? CoverImageSourcePath { get; private set; } + public Optional CoverImageSourcePath { get; private set; } /// /// Gets whether this media library is enabled or not. A disabled media library is never shown or changed. @@ -107,7 +107,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, List contentLocations, - string? coverImage, + Optional coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, @@ -150,7 +150,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, IEnumerable contentLocations, - string? coverImageSourcePath, + Optional coverImageSourcePath, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, @@ -159,7 +159,7 @@ public class Library : AggregateRoot List scanIds) { List tempContentLocations = []; - // go through all the file system paths that make up the media library and create domain objects from them + // Go through all the file system paths that make up the media library and create domain objects from them. foreach (string contentLocation in contentLocations) { Result contentLocationResult = FileSystemPathId.Create(contentLocation); @@ -207,7 +207,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, IEnumerable contentLocations, - string? coverImageSourcePath, + Optional coverImageSourcePath, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, @@ -216,7 +216,7 @@ public class Library : AggregateRoot List scanIds) { List tempContentLocations = []; - // go through all the file system paths that make up the media library and create domain objects from them + // Go through all the file system paths that make up the media library and create domain objects from them. foreach (string contentLocation in contentLocations) { Result contentLocationResult = FileSystemPathId.Create(contentLocation); @@ -254,7 +254,7 @@ public class Library : AggregateRoot /// The internal libray path location of the cover image file. public void SetInternalLibraryCoverImagePath(string path) { - CoverImage = path; + CoverImage = Optional.Some(path); } /// @@ -263,14 +263,14 @@ public class Library : AggregateRoot /// An representing either a successful operation, or an error. public Result Delete() { - // clear all existing events since they become irrelevant when the entity is deleted, and they dont need to be processed + // Clear all existing events, since they become irrelevant when the entity is deleted and do not need to be processed. _domainEvents.Clear(); - // only add the delete event if it hasn't been added already + // Only add the delete event if it has not been added already. if (!_domainEvents.Any(domainEvent => domainEvent is LibraryDeletedDomainEvent)) _domainEvents.Add(new LibraryDeletedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow)); - // TODO: perhaps trigger events for removing contents related to the removed library (media metadata, etc)? + // TODO: Perhaps trigger events for removing content related to the removed library (media metadata, etc.). return Result.Deleted; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs index 6a841213..ea8e3ded 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs @@ -46,12 +46,12 @@ public sealed class Isbn : ValueObject /// The value representing this object. /// The format of the ISBN representing this object. /// The created instance. - public static Result Create(string? value, IsbnFormat format) + public static Result Create(string value, IsbnFormat format) { - // enforce invariants + // Enforce invariants. if (string.IsNullOrWhiteSpace(value)) return Errors.WrittenContent.IsbnValueCannotBeEmpty; - // remove hyphens and spaces, for validation + // Remove hyphens and spaces, for validation. string cleanedValue = Regex.Replace(value, @"[-\s]", string.Empty); switch (format) { @@ -78,7 +78,7 @@ public sealed class Isbn : ValueObject { if (!s_isbn10Regex.IsMatch(isbn)) return false; - // remove any hyphens or spaces + // Remove any hyphens or spaces. isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper(); int sum = 0; for (int i = 0; i < 9; i++) @@ -100,7 +100,7 @@ public sealed class Isbn : ValueObject { if (!s_isbn13Regex.IsMatch(isbn)) return false; - // remove any hyphens or spaces + // Remove any hyphens or spaces. isbn = isbn.Replace("-", "").Replace(" ", ""); int sum = 0; for (int i = 0; i < 12; i++) diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index 2dfccb20..d635095b 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -45,15 +45,15 @@ public class AuthorizationService : IAuthorizationService /// if the user has the specified permission, otherwise. public async Task HasPermissionAsync(Guid userId, AuthorizationPermission permission, 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; - // check if the user has the permission directly + // Check if the user has the permission directly. if (getUserResult.Value.UserPermissions.Any(userPermission => userPermission.Permission.PermissionName == permission)) return true; - // check if any of the user's roles grant the permission + // Check if any of the user's roles grant the permission. return getUserResult.Value.UserRole?.Role.RolePermissions .Any(rolePermission => rolePermission.Permission.PermissionName == permission) == true; } @@ -67,7 +67,7 @@ public class AuthorizationService : IAuthorizationService /// if the user is in the specified role, otherwise. public async Task IsInRoleAsync(Guid userId, string role, 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; return getUserResult.Value.UserRole?.Role.RoleName == role; @@ -83,7 +83,7 @@ public class AuthorizationService : IAuthorizationService /// if the user satisfies the policy, otherwise. public async Task EvaluatePolicyAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy { - // resolve the authorization policy dynamically using the factory + // Resolve the authorization policy dynamically using the factory. IAuthorizationPolicy policy = _authorizationPolicyFactory.CreatePolicy(); return await policy.EvaluateAsync(userId, context, cancellationToken).ConfigureAwait(false); } @@ -96,7 +96,7 @@ public class AuthorizationService : IAuthorizationService /// An containing either a , or an error. public async Task> GetUserAuthorizationAsync(Guid userId, 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) return getUserResult.Errors; @@ -104,18 +104,18 @@ public class AuthorizationService : IAuthorizationService if (getUserResult.Value is null) return Errors.Users.UserDoesNotExist; - // get all roles + // Get all roles. string? role = getUserResult.Value.UserRole?.Role.RoleName; - // get direct user permissions + // Get direct user permissions. HashSet directPermissions = [.. getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission.PermissionName)]; - // get permissions from roles + // Get permissions from roles. HashSet? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions .Select(rolePermission => rolePermission.Permission.PermissionName) .ToHashSet(); - // combine all permissions + // Combine all permissions. HashSet allPermissions = rolePermissions is not null ? [.. directPermissions.Union(rolePermissions)] : directPermissions; return new UserAuthorizationEntity diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs index 4ec993a2..f34d78df 100644 --- a/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs @@ -21,9 +21,9 @@ public class CachedThemeHandler : DelegatingHandler { private const string THEMES_SEGMENT = "/api/v1/themes"; private const string THEME_CACHE_TAG = "themes"; - // responses above this size are never kept in the cache, so large binary assets do not bloat the memory + // Responses above this size are never kept in the cache, so large binary assets do not bloat the memory. private const int MAX_CACHEABLE_BYTES = 512 * 1024; - // themes only change when the user switches, reinstalls or deletes them, so the cached responses stay valid for a long time + // Themes only change when the user switches, reinstalls or deletes them, so the cached responses stay valid for a long time. private static readonly TimeSpan s_cacheExpiration = TimeSpan.FromMinutes(30); private readonly HybridCache _hybridCache; @@ -56,7 +56,7 @@ public class CachedThemeHandler : DelegatingHandler if (!requestPath.StartsWith(THEMES_SEGMENT, StringComparison.OrdinalIgnoreCase)) return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); - // a theme mutation replaces the theme files or the active selection, so every cached theme response becomes stale + // A theme mutation replaces the theme files or the active selection, so every cached theme response becomes stale. if (!request.Method.Equals(HttpMethod.Get)) { HttpResponseMessage mutationResponse = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); @@ -65,16 +65,16 @@ public class CachedThemeHandler : DelegatingHandler return mutationResponse; } - // the current user can switch off the theme cache from the settings page, so their requests always receive the freshly edited theme files + // The current user can switch off the theme cache from the settings page, so their requests always receive the freshly edited theme files. Guid? userId = GetCurrentUserId(); if (userId is not null) { - bool isCachingEnabledForUser = await _themeCachePreferenceService.GetAsync(userId.Value, defaultValue: true, cancellationToken).ConfigureAwait(false); + bool isCachingEnabledForUser = await _themeCachePreferenceService.GetAsync(userId.Value, isCachingEnabledByDefault: true, cancellationToken).ConfigureAwait(false); if (!isCachingEnabledForUser) return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } - // key the cached responses by the full request path and query, since each theme endpoint identifies a distinct resource + // Key the cached responses by the full request path and query, since each theme endpoint identifies a distinct resource. string cacheKey = $"themes:{request.RequestUri.PathAndQuery}"; CachedResponse cached = await _hybridCache.GetOrCreateAsync( cacheKey, @@ -96,7 +96,7 @@ public class CachedThemeHandler : DelegatingHandler [THEME_CACHE_TAG], cancellationToken); - // failed responses are only served from the call that produced them, so a temporary failure can never be served from a stale entry + // Failed responses are only served from the call that produced them, so a temporary failure can never be served from a stale entry. if (!IsSuccessful(cached.StatusCode) || cached.Bytes.Length > MAX_CACHEABLE_BYTES) await _hybridCache.RemoveAsync(cacheKey, cancellationToken).ConfigureAwait(false);