Rewords the code comments as complete sentences

This commit is contained in:
BinaryAlley committed 2026-09-12 06:51:28 +03:00
1 parent 39f4a04459
commit 36e43b7999
15 files changed
+135 -120

No files matched your search

@@ -56,25 +56,24 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
{
// get the library scan from the repository
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
// Get the library scan from the repository.
Result<LibraryScanEntity?> 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<LibraryScan> 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<Success> 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);
@@ -46,25 +46,25 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibrarySc
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// get the library scan that was queued, from the repository
Result<LibraryScanEntity?> getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
// Get the library scan that was queued, from the repository.
Result<LibraryScanEntity?> 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<LibraryScan> 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<Success> 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);
}
@@ -64,20 +64,20 @@ public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, Result<Libr
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 ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the library with the specified id from the repository
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
// Get the library with the specified id from the repository.
Result<LibraryEntity?> 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<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.Id), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
@@ -71,20 +71,20 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanPr
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 ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the library with the specified id from the repository
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
// Get the library with the specified id from the repository.
Result<LibraryEntity?> 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<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
@@ -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<GetLibraryAr
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 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<ILibraryOwnershipPolicy>(
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<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> 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<IEnumerable<PluginEntity>> 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<PaginatedResultDto<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
return getPluginsResult.Errors;
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
Dictionary<Guid, string> 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))
@@ -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<GetLibraryM
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 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<ILibraryOwnershipPolicy>(
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<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> 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<IEnumerable<PluginEntity>> 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<PaginatedResultDto<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
return getPluginsResult.Errors;
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
Dictionary<Guid, string> 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))
@@ -58,22 +58,25 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
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 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<UserEntity?> 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<UserEntity?> 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());
}
}
@@ -57,22 +57,25 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
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 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<UserEntity?> 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<UserEntity?> 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());
}
}
@@ -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.
/// <summary>
/// Service for file system permissions.
/// </summary>
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<string> directoryPath = Optional<string>.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<string> parentDirectory = Optional<string>.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;
}
}
@@ -56,24 +56,24 @@ public class ThumbnailService : IThumbnailService
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
public async Task<Result<Thumbnail>> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken)
{
// first, get the type of the image file
// First, get the type of the image file.
Result<ImageType> 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<byte[]> 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<byte[]> adjustedImage = Optional<byte[]>.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<byte[]>.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();
}
@@ -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.
/// </summary>
public class PlatformContextManager : IPlatformContextManager
{
private IPlatformContext? _currentPlatformContext;
private Optional<IPlatformContext> _currentPlatformContext;
private readonly IPlatformContextFactory _platformContextFactory;
private readonly IOperatingSystemInfo _operatingSystemInfo;
@@ -32,13 +33,13 @@ public class PlatformContextManager : IPlatformContextManager
/// <returns>The current platform context.</returns>
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;
}
/// <summary>
@@ -48,12 +49,12 @@ public class PlatformContextManager : IPlatformContextManager
/// <exception cref="ArgumentException">Thrown when an unsupported platform type is provided.</exception>
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<IPlatformContext>.Some(platformType switch
{
PlatformType.Unix => _platformContextFactory.CreateStrategy<IUnixPlatformContext>(),
PlatformType.Windows => _platformContextFactory.CreateStrategy<IWindowsPlatformContext>(),
_ => throw new ArgumentException($"Unsupported platform type: {platformType}"),
};
});
}
}
@@ -43,12 +43,12 @@ public class Library : AggregateRoot<LibraryId>
/// <summary>
/// Gets the path of the image file used as the cover for the library.
/// </summary>
public string? CoverImage { get; private set; }
public Optional<string> CoverImage { get; private set; }
/// <summary>
/// Gets the path of the image file chosen by the user to be used as the cover for the library.
/// </summary>
public string? CoverImageSourcePath { get; private set; }
public Optional<string> CoverImageSourcePath { get; private set; }
/// <summary>
/// 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<LibraryId>
string title,
LibraryType libraryType,
List<FileSystemPathId> contentLocations,
string? coverImage,
Optional<string> coverImage,
bool isEnabled,
bool isLocked,
bool canDownloadMetadataFromWeb,
@@ -150,7 +150,7 @@ public class Library : AggregateRoot<LibraryId>
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations,
string? coverImageSourcePath,
Optional<string> coverImageSourcePath,
bool isEnabled,
bool isLocked,
bool canDownloadMetadataFromWeb,
@@ -159,7 +159,7 @@ public class Library : AggregateRoot<LibraryId>
List<ScanId> scanIds)
{
List<FileSystemPathId> 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<FileSystemPathId> contentLocationResult = FileSystemPathId.Create(contentLocation);
@@ -207,7 +207,7 @@ public class Library : AggregateRoot<LibraryId>
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations,
string? coverImageSourcePath,
Optional<string> coverImageSourcePath,
bool isEnabled,
bool isLocked,
bool canDownloadMetadataFromWeb,
@@ -216,7 +216,7 @@ public class Library : AggregateRoot<LibraryId>
List<ScanId> scanIds)
{
List<FileSystemPathId> 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<FileSystemPathId> contentLocationResult = FileSystemPathId.Create(contentLocation);
@@ -254,7 +254,7 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="path">The internal libray path location of the cover image file.</param>
public void SetInternalLibraryCoverImagePath(string path)
{
CoverImage = path;
CoverImage = Optional<string>.Some(path);
}
/// <summary>
@@ -263,14 +263,14 @@ public class Library : AggregateRoot<LibraryId>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Deleted> 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;
}
}
@@ -46,12 +46,12 @@ public sealed class Isbn : ValueObject
/// <param name="value">The value representing this object.</param>
/// <param name="format">The format of the ISBN representing this object.</param>
/// <returns>The created <see cref="Isbn"/> instance.</returns>
public static Result<Isbn> Create(string? value, IsbnFormat format)
public static Result<Isbn> 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++)
@@ -45,15 +45,15 @@ public class AuthorizationService : IAuthorizationService
/// <returns><see langword="true"/> if the user has the specified permission, <see langword="false"/> otherwise.</returns>
public async Task<bool> HasPermissionAsync(Guid userId, AuthorizationPermission permission, 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;
// 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
/// <returns><see langword="true"/> if the user is in the specified role, <see langword="false"/> otherwise.</returns>
public async Task<bool> IsInRoleAsync(Guid userId, string role, 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;
return getUserResult.Value.UserRole?.Role.RoleName == role;
@@ -83,7 +83,7 @@ public class AuthorizationService : IAuthorizationService
/// <returns><see langword="true"/> if the user satisfies the policy, <see langword="false"/> otherwise.</returns>
public async Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(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<TAuthorizationPolicy>();
return await policy.EvaluateAsync(userId, context, cancellationToken).ConfigureAwait(false);
}
@@ -96,7 +96,7 @@ public class AuthorizationService : IAuthorizationService
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="UserAuthorizationEntity"/>, or an error.</returns>
public async Task<Result<UserAuthorizationEntity>> GetUserAuthorizationAsync(Guid userId, 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)
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<AuthorizationPermission> directPermissions = [.. getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission.PermissionName)];
// get permissions from roles
// Get permissions from roles.
HashSet<AuthorizationPermission>? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions
.Select(rolePermission => rolePermission.Permission.PermissionName)
.ToHashSet();
// combine all permissions
// Combine all permissions.
HashSet<AuthorizationPermission> allPermissions = rolePermissions is not null ? [.. directPermissions.Union(rolePermissions)] : directPermissions;
return new UserAuthorizationEntity
@@ -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);