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

@@ -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++)