From dfc7112cb7b88288a77acfc5fea17ee7e46cc176 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 10 Sep 2024 19:32:24 +0300 Subject: [PATCH] Adds File System Domain aggregate --- .../DomainLayerServices.cs | 44 +++ .../Common/Enums/FileAccessMode.cs | 37 ++ .../Common/Enums/FileSystemItemStatus.cs | 22 ++ .../Common/Enums/FileSystemItemType.cs | 22 ++ src/Lumina.Domain/Common/Enums/ImageType.cs | 24 ++ .../Common/Enums/PlatformType.cs | 17 + .../Common/Errors/Errors.FileManagement.cs | 11 + .../Common/Errors/Errors.Permission.cs | 18 + .../Common/Errors/Errors.Thumbnails.cs | 18 + .../Entities/Directory.cs | 56 +++ .../FileManagementAggregate/Entities/File.cs | 47 +++ .../FileManagementAggregate/FileSystemItem.cs | 89 +++++ .../Services/DirectoryProviderService.cs | 303 +++++++++++++++++ .../Services/DirectoryService.cs | 321 ++++++++++++++++++ .../Services/FileProviderService.cs | 268 +++++++++++++++ .../Services/FileService.cs | 302 ++++++++++++++++ .../Services/FileSystemPermissionsService.cs | 213 ++++++++++++ .../Services/FileTypeService.cs | 159 +++++++++ .../Services/IDirectoryProviderService.cs | 94 +++++ .../Services/IDirectoryService.cs | 79 +++++ .../Services/IFileProviderService.cs | 99 ++++++ .../Services/IFileService.cs | 71 ++++ .../Services/IFileSystemPermissionsService.cs | 23 ++ .../Services/IFileTypeService.cs | 31 ++ .../Services/IPathService.cs | 57 ++++ .../Services/IThumbnailService.cs | 31 ++ .../Services/PathService.cs | 106 ++++++ .../Services/ThumbnailService.cs | 190 +++++++++++ .../Environment/EnvironmentContext.cs | 42 +++ .../Environment/IEnvironmentContext.cs | 29 ++ .../Strategies/Path/IPathStrategy.cs | 54 +++ .../Strategies/Path/IUnixPathStrategy.cs | 8 + .../Strategies/Path/IWindowsPathStrategy.cs | 8 + .../Strategies/Path/UnixPathStrategy.cs | 121 +++++++ .../Strategies/Path/WindowsPathStrategy.cs | 128 +++++++ .../Strategies/Platform/IPlatformContext.cs | 24 ++ .../Platform/IPlatformContextFactory.cs | 16 + .../Platform/IPlatformContextManager.cs | 27 ++ .../Platform/IUnixPlatformContext.cs | 8 + .../Platform/IWindowsPlatformContext.cs | 8 + .../Platform/PlatformContextFactory.cs | 39 +++ .../Platform/PlatformContextManager.cs | 64 ++++ .../Platform/UnixPlatformContext.cs | 35 ++ .../Platform/WindowsPlatformContext.cs | 35 ++ .../ValueObjects/FileInfo.cs | 92 ----- .../ValueObjects/FileSystemId.cs | 52 +++ .../ValueObjects/FileSystemPathId.cs | 56 +++ .../ValueObjects/PathSegment.cs | 56 +++ .../ValueObjects/StreamInfo.cs | 7 +- .../ValueObjects/Thumbnail.cs | 49 +++ src/Lumina.Domain/Lumina.Domain.csproj | 11 +- 51 files changed, 3626 insertions(+), 95 deletions(-) create mode 100644 src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs create mode 100644 src/Lumina.Domain/Common/Enums/FileAccessMode.cs create mode 100644 src/Lumina.Domain/Common/Enums/FileSystemItemStatus.cs create mode 100644 src/Lumina.Domain/Common/Enums/FileSystemItemType.cs create mode 100644 src/Lumina.Domain/Common/Enums/ImageType.cs create mode 100644 src/Lumina.Domain/Common/Enums/PlatformType.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.Permission.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs delete mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemId.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs new file mode 100644 index 00000000..a2843039 --- /dev/null +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Microsoft.Extensions.DependencyInjection; +using System.IO.Abstractions; +#endregion + +namespace Lumina.Domain.Common.DependencyInjection; + +/// +/// Contains all services of the Domain layer. +/// +public static class DomainLayerServices +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Registers the services of the Domain layer into the dependency injection container. + /// + /// The service collection to add the services to. + /// The updated . + public static IServiceCollection AddDomainLayerServices(this IServiceCollection services) + { + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + return services; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Enums/FileAccessMode.cs b/src/Lumina.Domain/Common/Enums/FileAccessMode.cs new file mode 100644 index 00000000..458b1ca2 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/FileAccessMode.cs @@ -0,0 +1,37 @@ +namespace Lumina.Domain.Common.Enums; + +/// +/// Enumeration for file access mode types. +/// +public enum FileAccessMode +{ + /// + /// Represents the ability to list the contents of a directory. + /// + ListDirectory, + + /// + /// Represents the ability to read file or directory properties. + /// + ReadProperties, + + /// + /// Represents the ability to read the contents of a file. + /// + ReadContents, + + /// + /// Represents the ability to write to a file or directory. + /// + Write, + + /// + /// Represents the ability to execute a file. + /// + Execute, + + /// + /// Represents the ability to delete a file or directory. + /// + Delete, +} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Enums/FileSystemItemStatus.cs b/src/Lumina.Domain/Common/Enums/FileSystemItemStatus.cs new file mode 100644 index 00000000..8d61b550 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/FileSystemItemStatus.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.Common.Enums; + +/// +/// Enumeration for file system item statuses types. +/// +public enum FileSystemItemStatus +{ + /// + /// Indicates that the file system item is accessible. + /// + Accessible, + + /// + /// Indicates that the file system item is inaccessible due to permissions or other restrictions. + /// + Inaccessible, + + /// + /// Indicates that the status of the file system item could not be determined due to an unknown error. + /// + UnknownError +} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Enums/FileSystemItemType.cs b/src/Lumina.Domain/Common/Enums/FileSystemItemType.cs new file mode 100644 index 00000000..4325ad85 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/FileSystemItemType.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.Common.Enums; + +/// +/// Enumeration for the types of file system elements. +/// +public enum FileSystemItemType +{ + /// + /// Represents a drive, such as a hard disk, USB drive, or network drive. + /// + Drive, + + /// + /// Represents a directory, which is a directory that can contain other directories or files. + /// + Directory, + + /// + /// Represents a file, which is a document, executable, or other data stored on the file system. + /// + File +} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Enums/ImageType.cs b/src/Lumina.Domain/Common/Enums/ImageType.cs new file mode 100644 index 00000000..b9f4d423 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/ImageType.cs @@ -0,0 +1,24 @@ +namespace Lumina.Domain.Common.Enums; + +/// +/// Enumeration for known image types. +/// +public enum ImageType +{ + None, + BMP, + GIF, + PNG, + TIFF, + JPEG, + JPEG_CANON, + JPEG_UNKNOWN, + PICT, + ICO, + PSD, + JPEG2000, + AVIF, + WEBP, + TGA, + SVG, +} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Enums/PlatformType.cs b/src/Lumina.Domain/Common/Enums/PlatformType.cs new file mode 100644 index 00000000..936f2d96 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/PlatformType.cs @@ -0,0 +1,17 @@ +namespace Lumina.Domain.Common.Enums; + +/// +/// Enumeration for platform types. +/// +public enum PlatformType +{ + /// + /// Represents Unix-based operating systems, including Linux and macOS. + /// + Unix, + + /// + /// Represents Microsoft Windows operating systems. + /// + Windows, +} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs index 3cda1556..0a567a26 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs @@ -12,11 +12,22 @@ public static partial class Errors public static class FileManagement { #region ==================================================================== PROPERTIES ================================================================================= + public static Error FileCopyError => Error.Failure(nameof(FileCopyError)); + public static Error FileMoveError => Error.Failure(nameof(FileMoveError)); + public static Error DirectoryCopyError => Error.Failure(nameof(DirectoryCopyError)); + public static Error DirectoryMoveError => Error.Failure(nameof(DirectoryMoveError)); + public static Error FileNotFoundError => Error.NotFound(nameof(FileNotFoundError)); + public static Error InvalidPathError => Error.Validation(nameof(InvalidPathError)); public static Error PathCannotBeEmpty => Error.Validation(nameof(PathCannotBeEmpty)); public static Error ExtensionCannotBeEmpty => Error.Validation(nameof(ExtensionCannotBeEmpty)); public static Error StreamIdCannotBeEmpty => Error.Validation(nameof(StreamIdCannotBeEmpty)); public static Error CodecCannotBeEmpty => Error.Validation(nameof(CodecCannotBeEmpty)); public static Error BitrateMustBeAPositiveNumber => Error.Validation(nameof(BitrateMustBeAPositiveNumber)); + public static Error CannotNavigateUpError => Error.Failure(nameof(CannotNavigateUpError)); + public static Error NameCannotBeEmptyError => Error.Validation(nameof(NameCannotBeEmptyError)); + public static Error FileAlreadyExistsError => Error.Conflict(nameof(FileAlreadyExistsError)); + public static Error DirectoryNotFoundError => Error.NotFound(nameof(DirectoryNotFoundError)); + public static Error DirectoryAlreadyExistsError => Error.Conflict(nameof(DirectoryAlreadyExistsError)); #endregion } } \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Errors/Errors.Permission.cs b/src/Lumina.Domain/Common/Errors/Errors.Permission.cs new file mode 100644 index 00000000..5caaa027 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Permission.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Domain permission related error types. +/// +public static partial class Errors +{ + public static class Permission + { + #region ==================================================================== PROPERTIES ================================================================================= + public static Error UnauthorizedAccess => Error.Failure(nameof(UnauthorizedAccess)); + #endregion + } +} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs new file mode 100644 index 00000000..390c3362 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Domain thumbnails related error types. +/// +public static partial class Errors +{ + public static class Thumbnails + { + #region ==================================================================== PROPERTIES ================================================================================= + public static Error NoThumbnail => Error.Failure(nameof(NoThumbnail)); + #endregion + } +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs new file mode 100644 index 00000000..b56211f3 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; + +/// +/// Entity representing a file system directory. +/// +[DebuggerDisplay("{Id.Path}")] +public class Directory : FileSystemItem +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets or sets the collection of file system items that are children to the current directory entity. + /// + public List Items { get; private set; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the directory in the file system path. + /// The name of the directory. + /// The date and time the directory was created. Can be if unknown. + /// The date and time the directory was last modified. Can be if unknown. + public Directory(FileSystemPathId id, string name, DateTime? dateCreated, DateTime? dateModified) : base(id, name, dateCreated, dateModified) + { + Items = []; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Adds a file system item to the directory. + /// + /// The file system item to add. + public void AddItem(FileSystemItem item) + { + Items.Add(item); + } + + /// + /// Removes a file system item from the directory. + /// + /// The file system item to remove. + public void RemoveItem(FileSystemItem item) + { + Items.Remove(item); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs new file mode 100644 index 00000000..6f78e10b --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; + +/// +/// Entity representing a file system file. +/// +[DebuggerDisplay("{Id.Path}")] +public class File : FileSystemItem +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets or sets the size in bytes of the current file entity. + /// + public long Size { get; private set; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the file in the file system path. + /// The name of the file. + /// The date and time the file was created. Can be if unknown. + /// The date and time the file was last modified. Can be if unknown. + /// The size of the file in bytes. + public File(FileSystemPathId id, string name, DateTime? dateCreated, DateTime? dateModified, long size) : base(id, name, dateCreated, dateModified) + { + Size = size; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Updates the size of the file. + /// + /// The new size, in bytes. + public void UpdateSize(long newSize) + { + Size = newSize; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs new file mode 100644 index 00000000..f42319c0 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; + +/// +/// Entity representing a generic file system element. +/// +[DebuggerDisplay("{Name}")] +public abstract class FileSystemItem : AggregateRoot +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets or sets the name of the file system item. + /// + public string Name { get; protected set; } + + /// + /// Gets or sets the creation date of the file system item. + /// Can be if the information is not available. + /// + public DateTime? DateCreated { get; protected set; } + + /// + /// Gets or sets the last modification date of the file system item. + /// Can be if the information is not available. + /// + public DateTime? DateModified { get; protected set; } + + /// + /// Gets or sets the current status of the file system item. + /// Defaults to Accessible. + /// + public FileSystemItemStatus Status { get; protected set; } = FileSystemItemStatus.Accessible; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier for the file system path. + /// The name of the file system item. + /// The date and time the file system item was last modified. Can be if unknown. + /// The date and time the file system item was created. Can be if unknown. + protected FileSystemItem(FileSystemPathId id, string name, DateTime? dateModified, DateTime? dateCreated) : base(id) + { + Name = name; + DateCreated = dateCreated; + DateModified = dateModified; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Renames the file system item to the specified new name. + /// + /// The new name for the file system item. + /// Thrown if the new name is null or whitespace. + public void Rename(string newName) + { + if (string.IsNullOrWhiteSpace(newName)) + throw new ArgumentException("New name cannot be empty", nameof(newName)); + Name = newName; + } + + /// + /// Updates the last modified date of the file system item. + /// + /// The new date and time of last modification. + public void UpdateLastModified(DateTime date) + { + DateModified = date; + } + + /// + /// Sets the status of the filesystem item. + /// + /// The status to be set. + public void SetStatus(FileSystemItemStatus status) + { + Status = status; + } + #endregion +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs new file mode 100644 index 00000000..c03c9d07 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs @@ -0,0 +1,303 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.IO.Abstractions; +using System.Linq; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Directory provider for local file systems. +/// +internal class DirectoryProviderService : IDirectoryProviderService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _fileSystem; + private readonly IFileSystemPermissionsService _fileSystemPermissionsService; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to interact with the local filesystem. + /// Injected service used to determine local filesystem permissions. + public DirectoryProviderService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService) + { + _fileSystem = fileSystem; + _fileSystemPermissionsService = fileSystemPermissionsService; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves a list of subdirectory paths from the specified path, asynchronously. + /// + /// The path from which to retrieve the subdirectory paths. + /// An containing either a task representing the asynchronous operation for retrieving a collection of directory paths or an error. + public ErrorOr>> GetSubdirectoryPathsAsync(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false)) + return Errors.Permission.UnauthorizedAccess; + return Task.Run(() => _fileSystem.Directory.GetDirectories(path.Path) + .OrderBy(p => p) + .Select(p => FileSystemPathId.Create(p)) + .Where(errorOrPathId => !errorOrPathId.IsError) + .Select(errorOrPathId => errorOrPathId.Value) + .AsEnumerable()); + } + + /// + /// Checks if a directory with the specified path exists. + /// + /// The path of the directory whose existance is checked. + /// An containing either the result of checking the existance of a directory, or an error. + public ErrorOr DirectoryExists(FileSystemPathId path) + { + return _fileSystem.Directory.Exists(path.Path); + } + + /// + /// Retrieves the file name from the specified path. + /// + /// The path to extract the file name from. + /// The name of the file without the path, or the last segment of the path if no file name is found. + /// An containing either a file name or an error. + public ErrorOr GetFileName(FileSystemPathId path) + { + return _fileSystem.Path.GetFileName(path.Path); + } + + /// + /// Gets the last write time of a specific path. + /// + /// The path to retrieve the last write time for. + /// An containing either the last write time of , or null if not available, or an error. + public ErrorOr GetLastWriteTime(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) + return Errors.Permission.UnauthorizedAccess; + return _fileSystem.Directory.GetLastWriteTime(path.Path); + } + + /// + /// Gets the creation time of a specific path. + /// + /// The path to retrieve the creation time for. + /// An containing either the creation time of , or null if not available, or an error. + public ErrorOr GetCreationTime(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) + return Errors.Permission.UnauthorizedAccess; + return _fileSystem.Directory.GetCreationTime(path.Path); + } + + /// + /// Creates a new directory with the specified name, at the specified path. + /// + /// The path where the directory will be created.. + /// The name of the directory that will be created. + /// An containing either the path of a created directory, or an error. + public ErrorOr CreateDirectory(FileSystemPathId path, string name) + { + // to create a directory, its parent directory must be writable + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Write, false)) + return Errors.Permission.UnauthorizedAccess; + // create the directory and return its absolute path + string directoryPath = _fileSystem.Directory.CreateDirectory(_fileSystem.Path.Combine(path.Path, name)).FullName; + return FileSystemPathId.Create(directoryPath); + } + + /// + /// Copies a directory for the specified path. + /// + /// Identifier for the path where the directory to be copied is located. + /// Identifier for the path where the directory will be copied. + /// Whether to override existing directories, or not. + /// An containing either the copied directory, or an error. + public ErrorOr CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + { + // check if the source directory exists + if (!_fileSystem.Directory.Exists(sourcePath.Path)) + return Errors.FileManagement.DirectoryNotFoundError; + string destPath = CreateUniqueDirectoryPath(destinationPath.Path); + try + { + // create the new directory + IDirectoryInfo destDirInfo = _fileSystem.DirectoryInfo.New(_fileSystem.Directory.CreateDirectory(destPath).FullName); + // get the information of the source directory + IDirectoryInfo sourceDirInfo = _fileSystem.DirectoryInfo.New(sourcePath.Path); + // copy all files + foreach (IFileInfo fileInfo in sourceDirInfo.GetFiles()) + { + string targetFilePath = _fileSystem.Path.Combine(destPath, fileInfo.Name); + fileInfo.CopyTo(targetFilePath, overrideExisting); + _fileSystem.File.SetAttributes(targetFilePath, fileInfo.Attributes); // preserve file attributes + } + // copy all subdirectories + foreach (IDirectoryInfo subDirInfo in sourceDirInfo.GetDirectories()) + { + ErrorOr newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName); + if (newSourcePathResult.IsError) + return newSourcePathResult.Errors; + ErrorOr newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name)); + if (newDestinationPathResult.IsError) + return newDestinationPathResult.Errors; + // recursive call + ErrorOr copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting); + if (copySubDirResult.IsError) + return copySubDirResult.Errors; + } + return FileSystemPathId.Create(destPath); + } + catch + { + return Errors.FileManagement.DirectoryCopyError; + } + } + + /// + /// Creates a directory path that is unique. + /// + /// The path from which to generate the unique directory path. + /// A unique directory path. + private string CreateUniqueDirectoryPath(string destinationPath) + { + string destPath = destinationPath; + int copyNumber = 1; + // check if the destination directory exists and create a unique directory name + while (_fileSystem.Directory.Exists(destPath) || _fileSystem.File.Exists(destPath)) + destPath = $"{destinationPath} - Copy ({copyNumber++})"; + return destPath; + } + + /// + /// Moves a directory located at to . + /// + /// Identifier for the path where the directory to be moved is located. + /// Identifier for the path where the directory will be moved. + /// Whether to override existing directories, or not. + /// An containing either a moved directory, or an error. + public ErrorOr MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + { + // check if the source directory exists + if (!_fileSystem.Directory.Exists(sourcePath.Path)) + return Errors.FileManagement.DirectoryNotFoundError; + try + { + // if the destination directory does not exist, perform a simple move + if (!_fileSystem.Directory.Exists(destinationPath.Path)) + _fileSystem.Directory.Move(sourcePath.Path, destinationPath.Path); + else + MergeDirectories(sourcePath.Path, destinationPath.Path, overrideExisting); // if the destination directory exists, perform a merge based on the overwrite policy + return FileSystemPathId.Create(destinationPath.Path); + } + catch + { + return Errors.FileManagement.DirectoryMoveError; + } + } + + /// + /// Merges two directories. + /// + /// The source directory to be merged. + /// The destination directory to be merged. + /// Whether to override existing files. + private void MergeDirectories(string sourceDir, string destDir, bool overwrite) + { + // merge files from source directory to destination directory + foreach (string sourceFilePath in _fileSystem.Directory.GetFiles(sourceDir)) + { + string fileName = _fileSystem.Path.GetFileName(sourceFilePath); + string destFilePath = _fileSystem.Path.Combine(destDir, fileName); + // if a file with the same name exists in the destination + if (_fileSystem.File.Exists(destFilePath)) + { + if (overwrite) + { + // overwrite the file in the destination directory + _fileSystem.File.Delete(destFilePath); + _fileSystem.File.Move(sourceFilePath, destFilePath); + } + // otherwise, skip the file + } + else + _fileSystem.File.Move(sourceFilePath, destFilePath); // move the file if it does not exist in the destination directory + } + // recursively merge subdirectories + foreach (string sourceSubDirPath in _fileSystem.Directory.GetDirectories(sourceDir)) + { + string subDirName = _fileSystem.Path.GetFileName(sourceSubDirPath); + string destSubDirPath = _fileSystem.Path.Combine(destDir, subDirName); + // if the subdirectory does not exist in the destination, move it + if (!_fileSystem.Directory.Exists(destSubDirPath)) + _fileSystem.Directory.Move(sourceSubDirPath, destSubDirPath); + else + MergeDirectories(sourceSubDirPath, destSubDirPath, overwrite); // if the subdirectory exists, recursively merge its contents + } + // after merging the contents, delete the source directory if it's now empty + if (!_fileSystem.Directory.EnumerateFileSystemEntries(sourceDir).Any()) + _fileSystem.Directory.Delete(sourceDir); + } + + /// + /// Renames a directory at the specified path. + /// + /// The path of the directory to be renamed. + /// The new name of the directory. + /// An containing either the absolute path of the renamed directory, or an error. + public ErrorOr RenameDirectory(FileSystemPathId path, string name) + { + // to rename a directory, its parent directory must be writable + string? parentDirectory = _fileSystem.Directory.GetParent(path.Path)?.FullName; + if (!string.IsNullOrEmpty(parentDirectory)) + { + ErrorOr parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + if (parendDirectoryResult.IsError) + return parendDirectoryResult.Errors; + string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name); + if (!string.IsNullOrEmpty(newDirectory)) + { + var newDirectoryPathResult = FileSystemPathId.Create(newDirectory); + if (newDirectoryPathResult.IsError) + return newDirectoryPathResult.Errors; + if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false)) + return Errors.Permission.UnauthorizedAccess; + // to rename a directory, it must be executable + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false)) + return Errors.Permission.UnauthorizedAccess; + _fileSystem.Directory.Move(path.Path, newDirectoryPathResult.Value.Path); + return newDirectoryPathResult.Value; + } + else + return Errors.FileManagement.InvalidPathError; + } + else + return Errors.FileManagement.InvalidPathError; + } + + /// + /// Deletes a directory at the specified path. + /// + /// The path of the directory to be deleted. + /// An containing either the result of deleting a directory, or an error. + public ErrorOr DeleteDirectory(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false)) + return Errors.Permission.UnauthorizedAccess; + _fileSystem.DirectoryInfo.New(path.Path).Delete(true); + return true; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs new file mode 100644 index 00000000..5c1c5b96 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs @@ -0,0 +1,321 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Service for handling directories. +/// +public class DirectoryService : IDirectoryService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPlatformContext _platformContext; + private readonly IEnvironmentContext _environmentContext; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for environment contextual services. + /// Injected facade service for platform contextual services. + public DirectoryService(IEnvironmentContext environmentContext, IPlatformContextManager platformContextManager) + { + _platformContext = platformContextManager.GetCurrentContext(); + _environmentContext = environmentContext; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves subdirectories for the specified string path. + /// + /// String representation of the file path. + /// An containing either a collection of subdirectories or an error. + public async Task>> GetSubdirectoriesAsync(string path) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return await GetSubdirectoriesAsync(fileSystemPathIdResult.Value).ConfigureAwait(false); + } + + /// + /// Retrieves subdirectories for the given directory. + /// + /// Directory object to retrieve subdirectories for. + /// An containing either a collection of subdirectories or an error. + public async Task>> GetSubdirectoriesAsync(Directory directory) + { + return await GetSubdirectoriesAsync(directory.Id).ConfigureAwait(false); + } + + /// + /// Retrieves subdirectories for the specified file system path. + /// + /// Identifier for the file path. + /// An containing either a collection of subdirectories or an error. + public async Task>> GetSubdirectoriesAsync(FileSystemPathId path) + { + // retrieve the list of subdirectories + ErrorOr>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPathsAsync(path); + if (subdirectoryPathsResult.IsError) + return subdirectoryPathsResult.Errors; + List result = new(); + IEnumerable subdirectoryPaths = await subdirectoryPathsResult.Value.ConfigureAwait(false); + foreach (FileSystemPathId subPath in subdirectoryPaths) + { + // extract directory details + ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath); + ErrorOr dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath); + ErrorOr dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(subPath); + + // if any error occurred, mark directory as Inaccessible + if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + { + Directory errorDir = new(subPath, !dirNameResult.IsError ? dirNameResult.Value : null!, + !dateCreatedResult.IsError ? dateCreatedResult.Value : null, !dateModifiedResult.IsError ? dateModifiedResult.Value : null); + errorDir.SetStatus(FileSystemItemStatus.Inaccessible); + result.Add(errorDir); + } + else + { + Directory subDirectory = new(subPath, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); + result.Add(subDirectory); + } + } + return result; + } + + /// + /// Creates a directory with the specified , at the specified . + /// + /// String representation of the path where the directory will be created. + /// The name of the directory that will be created. + /// An containing either the result of creating a directory, or an error. + public ErrorOr CreateDirectory(string path, string name) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return CreateDirectory(fileSystemPathIdResult.Value, name); + } + + /// + /// Creates a directory with the specified , at the specified . + /// + /// Identifier for the path where the directory will be created. + /// The name of the directory that will be created. + /// An containing either the result of creating a directory, or an error. + public ErrorOr CreateDirectory(FileSystemPathId path, string name) + { + // first, check if the directory about to be created does not already exist + var combinedPath = _platformContext.PathStrategy.CombinePath(path, name); + if (combinedPath.IsError) + return combinedPath.Errors; + var directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value); + if (directoryExists.IsError) + return directoryExists.Errors; + else if (directoryExists.Value == true) + return Errors.FileManagement.DirectoryAlreadyExistsError; + else + { + // create the new directory + ErrorOr newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name); + if (newDirectoryPathResult.IsError) + return newDirectoryPathResult.Errors; + ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(path); + ErrorOr dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(path); + ErrorOr dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(path); + // if any error occurred, mark directory as Inaccessible + if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + { + Directory errorDir = new(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, + !dateCreatedResult.IsError ? dateCreatedResult.Value : null, !dateModifiedResult.IsError ? dateModifiedResult.Value : null); + errorDir.SetStatus(FileSystemItemStatus.Inaccessible); + return errorDir; + } + else + return new Directory(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); + } + } + + /// + /// Copies a directory located at to . + /// + /// String representation of the path where the directory to be copied is located. + /// String representation of the path where the directory will be copied. + /// Whether to override existing directories, or not. + /// An containing either a copied directory, or an error. + public ErrorOr CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + { + // make sure the paths are in the expected format + if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator)) + sourcePath += _platformContext.PathStrategy.PathSeparator; + if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) + destinationPath += _platformContext.PathStrategy.PathSeparator; + var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (fileSystemSourcePathIdResult.IsError) + return fileSystemSourcePathIdResult.Errors; + var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + } + + /// + /// Copies a directory located at to . + /// + /// Identifier for the path where the directory to be copied is located. + /// Identifier for the path where the directory will be copied. + /// Whether to override existing directories, or not. + /// An containing either the copied directory, or an error. + public ErrorOr CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + { + var directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); + if (directoryExists.IsError) + return directoryExists.Errors; + else if (directoryExists.Value == false) + return Errors.FileManagement.DirectoryNotFoundError; + else + { + // copy the directory + ErrorOr newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + throw new NotImplementedException(); + } + } + + /// + /// Moves a directory located at to . + /// + /// String representation of the path where the directory to be moved is located. + /// String representation of the path where the directory will be moved. + /// Whether to override existing directories, or not. + /// An containing either a moved directory, or an error. + public ErrorOr MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + { + // make sure the paths are in the expected format + if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator)) + sourcePath += _platformContext.PathStrategy.PathSeparator; + if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) + destinationPath += _platformContext.PathStrategy.PathSeparator; + var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (fileSystemSourcePathIdResult.IsError) + return fileSystemSourcePathIdResult.Errors; + var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + } + + /// + /// Moves a directory for the specified path. + /// + /// Identifier for the path where the directory to be moved is located. + /// Identifier for the path where the directory will be moved. + /// Whether to override existing directories, or not. + /// An containing either the moved directory, or an error. + public ErrorOr MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + { + var directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); + if (directoryExists.IsError) + return directoryExists.Errors; + else if (directoryExists.Value == false) + return Errors.FileManagement.DirectoryNotFoundError; + else + { + // move the directory + ErrorOr newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + throw new NotImplementedException(); + } + } + + /// + /// Renames a directory. + /// + /// String representation of the directory path. + /// The new name of the directory. + /// An containing either the renamed directory, or an error. + public ErrorOr RenameDirectory(string path, string name) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return RenameDirectory(fileSystemPathIdResult.Value, name); + } + + /// + /// Renames a directory for the specified path. + /// + /// Identifier for the directory path. + /// The new name of the directory. + /// An containing either the renamed directory, or an error. + public ErrorOr RenameDirectory(FileSystemPathId path, string name) + { + // first, check if the directory about to be created does not already exist + var combinedPath = _platformContext.PathStrategy.CombinePath(path, name); + if (combinedPath.IsError) + return combinedPath.Errors; + var directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value); + if (directoryExists.IsError) + return directoryExists.Errors; + else if (directoryExists.Value == true) + return Errors.FileManagement.DirectoryAlreadyExistsError; + else + { + // rename the directory + ErrorOr newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name); + if (newDirectoryPathResult.IsError) + return newDirectoryPathResult.Errors; + ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); + ErrorOr dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); + ErrorOr dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); + // if any error occurred, mark directory as Inaccessible + if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + { + Directory errorDir = new(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, + !dateCreatedResult.IsError ? dateCreatedResult.Value : null, !dateModifiedResult.IsError ? dateModifiedResult.Value : null); + errorDir.SetStatus(FileSystemItemStatus.Inaccessible); + return errorDir; + } + else + return new Directory(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); + } + } + + /// + /// Delete a directory for the specified string path. + /// + /// String representation of the directory path. + /// An containing either the result of deleting a directory, or an error. + public ErrorOr DeleteDirectory(string path) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return DeleteDirectory(fileSystemPathIdResult.Value); + } + + /// + /// Delete a directory for the specified path. + /// + /// Identifier for the directory path. + /// An containing either the result of deleting a directory, or an error. + public ErrorOr DeleteDirectory(FileSystemPathId path) + { + return _environmentContext.DirectoryProviderService.DeleteDirectory(path); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs new file mode 100644 index 00000000..ae924ffd --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs @@ -0,0 +1,268 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.IO.Abstractions; +using System.Linq; +using System.Threading.Tasks; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// File provider for local file systems. +/// +internal class FileProviderService : IFileProviderService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _fileSystem; + private readonly IFileSystemPermissionsService _fileSystemPermissionsService; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to interact with the local filesystem. + /// Injected service used to determine local filesystem permissions. + public FileProviderService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService) + { + _fileSystem = fileSystem; + _fileSystemPermissionsService = fileSystemPermissionsService; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves a list of file paths at the specified path. + /// + /// The path for which to retrieve the list of files. + /// An containing either a task representing the asynchronous operation for retrieving a collection of file paths or an error. + public ErrorOr>> GetFilePathsAsync(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory)) + return Errors.Permission.UnauthorizedAccess; + return Task.Run(() => _fileSystem.Directory.GetFiles(path.Path) + .OrderBy(p => p) + .Select(p => FileSystemPathId.Create(p)) + .Where(errorOrPathId => !errorOrPathId.IsError) + .Select(errorOrPathId => errorOrPathId.Value) + .AsEnumerable()); + } + + /// + /// Checks if a file with the specified path exists. + /// + /// The path of the file whose existance is checked. + /// An containing either the result of checking the existance of a file, or an error. + public ErrorOr FileExists(FileSystemPathId path) + { + return _fileSystem.File.Exists(path.Path); + } + + /// + /// Retrieves the file name from the specified path. + /// + /// The path to extract the file name from. + /// An containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error. + public ErrorOr GetFileName(FileSystemPathId path) + { + return _fileSystem.Path.GetFileName(path.Path); + } + + /// + /// Retrieves the contents of a file at the specified path. + /// + /// The path for which to retrieve the file contents. + /// An containing either a task representing the asynchronous operation for retrieving the contents of a file at the specified path, or an error. + public ErrorOr> GetFileAsync(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) + return Errors.Permission.UnauthorizedAccess; + return Task.Run(() => System.IO.File.ReadAllBytes(path.Path)); + } + + /// + /// Gets the last write time of a file at the specified path. + /// + /// The path of the file to retrieve the last write time for. + /// An containing either the last write time of , or null if not available, or an error. + public ErrorOr GetLastWriteTime(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) + return Errors.Permission.UnauthorizedAccess; + return _fileSystem.File.GetLastWriteTime(path.Path); + } + + /// + /// Gets the creation time of a file at the specified path. + /// + /// The path of the file to retrieve the creation time for. + /// An containing either the creation time of , or null if not available, or an error. + public ErrorOr GetCreationTime(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) + return Errors.Permission.UnauthorizedAccess; + return _fileSystem.File.GetCreationTime(path.Path); + } + + /// + /// Gets the size of a file at the specified path. + /// + /// The path of the file to retrieve the size for. + /// An containing either the size of or an error. + public ErrorOr GetSize(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) + return Errors.Permission.UnauthorizedAccess; + return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0; + } + + /// + /// Copies a file located at to . + /// + /// Identifier for the path where the file to be copied is located. + /// Identifier for the path of the directory where the file will be copied. + /// Whether to override existing files, or not. + /// An containing either the copied file, or an error. + public ErrorOr CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + { + // check if the source file exists + if (!_fileSystem.File.Exists(sourceFilePath.Path)) + return Errors.FileManagement.FileNotFoundError; + string destinationFilePath; + string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); + // when copying a file to the same location, just copy it with a new name + if (_fileSystem.Path.GetDirectoryName(sourceFilePath.Path) == destinationDirectoryPath.Path) + destinationFilePath = CreateUniqueFilePath(destinationDirectoryPath.Path); + else + { + // check if there is already a file with the same name as the copied file, in the destination directory + if (_fileSystem.File.Exists(destinationDirectoryPath.Path + fileName)) + if (!overrideExisting) + return Errors.FileManagement.FileAlreadyExistsError; + destinationFilePath = destinationDirectoryPath.Path + fileName; + } + try + { + _fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, overrideExisting); // copy the file + _fileSystem.File.SetAttributes(destinationFilePath, _fileSystem.File.GetAttributes(sourceFilePath.Path)); // preserve file attributes + return FileSystemPathId.Create(destinationFilePath); + } + catch + { + return Errors.FileManagement.FileCopyError; + } + } + + /// + /// Creates a file path that is unique + /// + /// The path from which to generate the unique file path. + /// A unique directory path. + private string CreateUniqueFilePath(string destinationFilePath) + { + string? directory = _fileSystem.Path.GetDirectoryName(destinationFilePath); + string? filename = _fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath); + string? extension = _fileSystem.Path.GetExtension(destinationFilePath); + string destFilePath = destinationFilePath; + int copyNumber = 1; + // check if the destination file exists and create a unique file name + if (!string.IsNullOrEmpty(directory) && !string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(extension)) + while (_fileSystem.File.Exists(destFilePath)) + destFilePath = _fileSystem.Path.Combine(directory, $"{filename} - Copy ({copyNumber++}){extension}"); + return destFilePath; + } + + /// + /// Moves a file located at to . + /// + /// Identifier for the path where the file to be moved is located. + /// Identifier for the path of the directory where the file will be moved. + /// Whether to override existing files, or not. + /// An containing either a moved file, or an error. + public ErrorOr MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + { + // check if the source file exists + if (!_fileSystem.File.Exists(sourceFilePath.Path)) + return Errors.FileManagement.FileNotFoundError; + try + { + string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); + string destinationFilePath = destinationDirectoryPath.Path + fileName; + // if the destination file does not exist, perform a simple move + if (!_fileSystem.File.Exists(destinationFilePath)) + _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath); + else + { + if (overrideExisting) + _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, overrideExisting); + else + return Errors.FileManagement.FileAlreadyExistsError; + } + return FileSystemPathId.Create(destinationFilePath); + } + catch + { + return Errors.FileManagement.FileMoveError; + } + } + + /// + /// Renames a file at the specified path. + /// + /// The path of the file to be renamed. + /// The new name of the file. + /// An containing either the absolute path of the renamed file, or an error. + public ErrorOr RenameFile(FileSystemPathId path, string name) + { + string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName; + if (!string.IsNullOrEmpty(parentDirectory)) + { + ErrorOr parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + if (parendDirectoryResult.IsError) + return parendDirectoryResult.Errors; + string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name); + if (!string.IsNullOrEmpty(newFile)) + { + var newFilePathResult = FileSystemPathId.Create(newFile); + if (newFilePathResult.IsError) + return newFilePathResult.Errors; + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute)) + return Errors.Permission.UnauthorizedAccess; + if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write)) + return Errors.Permission.UnauthorizedAccess; + _fileSystem.File.Move(path.Path, newFilePathResult.Value.Path); + return newFilePathResult; + } + else + return Errors.FileManagement.InvalidPathError; + } + else + return Errors.FileManagement.CannotNavigateUpError; + } + + /// + /// Deletes a file at the specified path. + /// + /// The path of the file to be deleted. + /// An containing either the result of deleting a file, or an error. + public ErrorOr DeleteFile(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete)) + return Errors.Permission.UnauthorizedAccess; + _fileSystem.File.Delete(path.Path); + return true; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs new file mode 100644 index 00000000..2cc34a21 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs @@ -0,0 +1,302 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Service for handling file system files. +/// +public class FileService : IFileService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPlatformContext _platformContext; + private readonly IEnvironmentContext _environmentContext; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for environment contextual services. + /// Injected facade service for platform contextual services. + public FileService(IEnvironmentContext environmentContext, IPlatformContextManager platformContextManager) + { + _platformContext = platformContextManager.GetCurrentContext(); + _environmentContext = environmentContext; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves files for the specified string path. + /// + /// String representation of the file path. + /// An containing either a collection of files or an error. + public async Task>> GetFilesAsync(string path) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return await GetFilesAsync(fileSystemPathIdResult.Value).ConfigureAwait(false); + } + + /// + /// Retrieves files associated with a given file. + /// + /// The file object. + /// An containing either a collection of files or an error. + public async Task>> GetFilesAsync(File file) + { + return await GetFilesAsync(file.Id).ConfigureAwait(false); + } + + /// + /// Retrieves files for a specified file path Id. + /// + /// Identifier for the file path. + /// An containing either a collection of files or an error. + public async Task>> GetFilesAsync(FileSystemPathId path) + { + // retrieve the list of files + ErrorOr>> filePathsResult = _environmentContext.FileProviderService.GetFilePathsAsync(path); + if (filePathsResult.IsError) + return filePathsResult.Errors; + List result = new(); + IEnumerable filePaths = await filePathsResult.Value.ConfigureAwait(false); + foreach (FileSystemPathId filePath in filePaths) + { + // extract file details and add to the result list + ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath); + ErrorOr dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath); + ErrorOr dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath); + ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(filePath); + long size = sizeResult.Value ?? 0; + // if any of the details returned an error, set inaccessible status + if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + { + File errorFile = new(filePath, !fileNameResult.IsError ? fileNameResult.Value : null!, + !dateCreatedResult.IsError ? dateCreatedResult.Value : null, !dateModifiedResult.IsError ? dateModifiedResult.Value : null, size); + errorFile.SetStatus(FileSystemItemStatus.Inaccessible); + result.Add(errorFile); + } + else + { + File file = new(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); + result.Add(file); + } + } + return result; + } + + /// + /// Copies a file located at to . + /// + /// String representation of the path where the file to be copied is located. + /// String representation of the path of the directory where the file will be copied. + /// Whether to override existing files, or not. + /// An containing either a copied file, or an error. + public ErrorOr CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + { + // make sure the paths are in the expected format + if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) + destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; + var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); + if (fileSystemSourcePathIdResult.IsError) + return fileSystemSourcePathIdResult.Errors; + var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + } + + /// + /// Copies a file for the specified path. + /// + /// Identifier for the path where the file to be copied is located. + /// Identifier for the path of the directory where the file will be copied. + /// Whether to override existing files, or not. + /// An containing either the copied file, or an error. + public ErrorOr CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + { + var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); + if (fileExists.IsError) + return fileExists.Errors; + else if (fileExists.Value == false) + return Errors.FileManagement.FileNotFoundError; + else + { + // copy the file + ErrorOr copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + if (copyFileResult.IsError) + return copyFileResult.Errors; + ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value); + ErrorOr dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(copyFileResult.Value); + ErrorOr dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value); + ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(copyFileResult.Value); + long size = sizeResult.Value ?? 0; + // if any of the details returned an error, set inaccessible status + if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + { + File errorFile = new(copyFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, + !dateCreatedResult.IsError ? dateCreatedResult.Value : null, !dateModifiedResult.IsError ? dateModifiedResult.Value : null, size); + errorFile.SetStatus(FileSystemItemStatus.Inaccessible); + return errorFile; + } + else + return new File(copyFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); + } + } + + /// + /// Moves a file located at to . + /// + /// String representation of the path where the file to be moved is located. + /// String representation of the path of the directory where the file will be moved. + /// Whether to override existing files, or not. + /// An containing either a moved file, or an error. + public ErrorOr MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + { + // make sure the paths are in the expected format + if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) + destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; + var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); + if (fileSystemSourcePathIdResult.IsError) + return fileSystemSourcePathIdResult.Errors; + var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + } + + /// + /// Moves a file for the specified path. + /// + /// Identifier for the path where the file to be moved is located. + /// Identifier for the path of the directory where the file will be moved. + /// Whether to override existing files, or not. + /// An containing either the moved file, or an error. + public ErrorOr MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + { + var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); + if (fileExists.IsError) + return fileExists.Errors; + else if (fileExists.Value == false) + return Errors.FileManagement.FileNotFoundError; + else + { + // move the file + ErrorOr moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + if (moveFileResult.IsError) + return moveFileResult.Errors; + ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value); + ErrorOr dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(moveFileResult.Value); + ErrorOr dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value); + ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(moveFileResult.Value); + long size = sizeResult.Value ?? 0; + // if any of the details returned an error, set inaccessible status + if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + { + File errorFile = new(moveFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, + !dateCreatedResult.IsError ? dateCreatedResult.Value : null, !dateModifiedResult.IsError ? dateModifiedResult.Value : null, size); + errorFile.SetStatus(FileSystemItemStatus.Inaccessible); + return errorFile; + } + else + return new File(moveFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); + } + } + + /// + /// Renames a file. + /// + /// String representation of the file path. + /// The new name of the file. + /// An containing either the renamed file, or an error. + public ErrorOr RenameFile(string path, string name) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return RenameFile(fileSystemPathIdResult.Value, name); + } + + /// + /// Renames a file for the specified path. + /// + /// Identifier for the file path. + /// The new name of the file. + /// An containing either the renamed file, or an error. + public ErrorOr RenameFile(FileSystemPathId path, string name) + { + // first, check if the directory about to be created does not already exist + var combinedPath = _platformContext.PathStrategy.CombinePath(path, name); + if (combinedPath.IsError) + return combinedPath.Errors; + var fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value); + if (fileExists.IsError) + return fileExists.Errors; + else if (fileExists.Value == true) + return Errors.FileManagement.FileAlreadyExistsError; + else + { + // rename the file + ErrorOr newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name); + if (newFilePathResult.IsError) + return newFilePathResult.Errors; + ErrorOr fileNameResult = _environmentContext.FileProviderService.GetFileName(newFilePathResult.Value); + ErrorOr dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(newFilePathResult.Value); + ErrorOr dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value); + ErrorOr sizeResult = _environmentContext.FileProviderService.GetSize(newFilePathResult.Value); + long size = sizeResult.Value ?? 0; + // if any of the details returned an error, set inaccessible status + if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) + { + File errorFile = new(newFilePathResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, + !dateCreatedResult.IsError ? dateCreatedResult.Value : null, !dateModifiedResult.IsError ? dateModifiedResult.Value : null, size); + errorFile.SetStatus(FileSystemItemStatus.Inaccessible); + return errorFile; + } + else + return new File(newFilePathResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); + } + } + + /// + /// Delete a file for the specified string path. + /// + /// String representation of the file path. + /// An containing either the result of deleting a file, or an error. + public ErrorOr DeleteFile(string path) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return DeleteFile(fileSystemPathIdResult.Value); + } + + /// + /// Delete a file for the specified string path. + /// + /// Identifier for the file path. + /// An containing either the result of deleting a file, or an error. + public ErrorOr DeleteFile(FileSystemPathId path) + { + return _environmentContext.FileProviderService.DeleteFile(path); + } + + public ErrorOr ReadFile(FileSystemPathId path) + { + return true; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs new file mode 100644 index 00000000..88249cd0 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs @@ -0,0 +1,213 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Mono.Unix; +using Mono.Unix.Native; +using System; +using System.IO; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Principal; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Service for file system permissions. +/// +internal class FileSystemPermissionsService : IFileSystemPermissionsService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPlatformContextManager _platformContextManager; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for platform contextual services. + public FileSystemPermissionsService(IPlatformContextManager platformContextManager) + { + _platformContextManager = platformContextManager; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks if can be accessed. + /// + /// The path to be accessed. + /// The mode in which to access the path. + /// Indicates whether the path represents a file or directory. + /// , if can be accessed, otherwise. + public bool CanAccessPath(FileSystemPathId path, FileAccessMode accessMode, bool isFile = true) + { + PlatformType platformType = _platformContextManager.GetCurrentContext().Platform; + if (platformType == PlatformType.Unix) + return CanAccessPathLinux(path.Path, accessMode); + else if (platformType == PlatformType.Windows) +#pragma warning disable CA1416 // Validate platform compatibility + return CanAccessPathWindows(path.Path, accessMode, isFile); +#pragma warning restore CA1416 // Validate platform compatibility + else + throw new PlatformNotSupportedException("Support for this platform is not compiled into this assembly."); + } + + /// + /// Checks if a the current user has access permissions on Linux for , with . + /// + /// The path for which to check the access. + /// The access mode in which to check that path access. + /// if the current user has rights for the specified path and acccess mode, otherwise. + /// Thrown when trying to check access for a mode that is not supported + private static bool CanAccessPathLinux(string path, FileAccessMode accessMode) + { + AccessModes modes; + UnixFileSystemInfo fileInfo = new UnixFileInfo(path); + switch (accessMode) + { + case FileAccessMode.ReadProperties: + // we would typically need execute permissions on a directory, to list its contents or view file properties + if (fileInfo.FileType == FileTypes.Directory) + return fileInfo.CanAccess(AccessModes.X_OK); + // for files, just verifying existence might be sufficient for reading properties + return fileInfo.Exists; + case FileAccessMode.ReadContents: + return fileInfo.CanAccess(AccessModes.R_OK); + case FileAccessMode.Write: + modes = AccessModes.W_OK; + break; + case FileAccessMode.Execute: + modes = AccessModes.X_OK; + break; + case FileAccessMode.ListDirectory: + modes = AccessModes.F_OK; // check existence, not an exact match but the closest + break; + case FileAccessMode.Delete: + if (fileInfo.FileType == FileTypes.Directory) + return fileInfo.CanAccess(AccessModes.W_OK | AccessModes.X_OK); // to delete a directory, we need write and execute permissions on the directory itself + else + { + // to delete a file, we need write permission on the parent directory + string? parentDirectoryPath = Path.GetDirectoryName(path); + if (string.IsNullOrEmpty(parentDirectoryPath)) + return false; // if path is a root directory or has no parent, deletion is not possible + UnixDirectoryInfo parentDirectoryInfo = new(parentDirectoryPath); + return parentDirectoryInfo.CanAccess(AccessModes.W_OK); + } + default: + throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode"); + } + return new UnixDirectoryInfo(path).CanAccess(modes); + } + + /// + /// Checks if a the current user has access permissions on Windows for , with . + /// + /// The path for which to check the access. + /// The access mode in which to check that path access. + /// Indicates whether the path represents a file or directory. + /// if the current user has rights for the specified path and acccess mode, otherwise. + /// Thrown when trying to check access for a mode that is not supported. + [SupportedOSPlatform("windows")] + private static bool CanAccessPathWindows(string path, FileAccessMode accessMode, bool isFile = true) + { + // translate to filesystem access modes (multiple can match per case) + FileSystemRights rights = accessMode switch + { + FileAccessMode.ReadProperties => FileSystemRights.ReadAttributes, + FileAccessMode.ReadContents => FileSystemRights.ReadData | FileSystemRights.ReadExtendedAttributes, + FileAccessMode.Write => FileSystemRights.WriteData | FileSystemRights.AppendData, + FileAccessMode.Execute => FileSystemRights.ExecuteFile, + FileAccessMode.ListDirectory => FileSystemRights.ListDirectory, + FileAccessMode.Delete => FileSystemRights.Delete, + _ => throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode"), + }; + 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); + } + else + { + if (HasAccess(rights, path, isFile)) + { + try + { + switch (accessMode) + { + case FileAccessMode.ReadProperties: + // just accessing file info for properties, without opening it + FileSystemInfo fileSystemInfo = isFile ? new FileInfo(path) : new DirectoryInfo(path); + _ = fileSystemInfo.CreationTime; // trigger potential access denial + break; + case FileAccessMode.ReadContents: + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + stream.Close(); + break; + } + return true; + } + catch + { + return false; + } + } + } + return false; + } + + /// + /// Checks if the current user or group has the access for , on Windows platforms. + /// + /// The rights for which to check access. + /// The path for which to check the access . + /// Indicates whether the path represents a file or directory. + /// , if the current user or group has for , otherwise. + [SupportedOSPlatform("windows")] + private static bool HasAccess(FileSystemRights rights, string path, bool isFile = true) + { + bool allowAccess = false; + AuthorizationRuleCollection acl; + WindowsIdentity identity = WindowsIdentity.GetCurrent(); + WindowsPrincipal principal = new(identity); + // 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??... + if (isFile) + { + FileInfo fileInfo = new(path); + acl = fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); + } + else + { + DirectoryInfo directoryInfo = new(path); + 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 + 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 + else if (accessRule.AccessControlType.Equals(AccessControlType.Allow) && (accessRule.FileSystemRights & rights) == rights) + allowAccess = true; + } + } + + } + catch + { + return false; + } + return allowAccess; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs new file mode 100644 index 00000000..c33fc661 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.IO.Abstractions; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Class defining methods for handling file-related operations. +/// +public class FileTypeService : IFileTypeService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _fileSystem; + private readonly IFileSystemPermissionsService _fileSystemPermissionsService; + private const int BUFFER_SIZE = 16; // 16 bytes should be more than enough for common images header types + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to interact with the local filesystem. + /// Injected service used to determine local filesystem permissions. + public FileTypeService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService) + { + _fileSystem = fileSystem; + _fileSystemPermissionsService = fileSystemPermissionsService; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Determines if is of type image or not, and returns its type. + /// + /// The file to determine if it is an image or not. + /// An containing the type of image or an error. + public async Task> GetImageTypeAsync(File file) + { + return await GetImageTypeAsync(file.Id).ConfigureAwait(false); + } + + /// + /// Determines if a file identified by is of type image or not, and returns its type. + /// + /// The path of the file to determine if it is an image or not. + /// An containing the type of image or an error. + public async Task> GetImageTypeAsync(FileSystemPathId path) + { + // check if the user has access permissions to the provided path + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) + return Errors.Permission.UnauthorizedAccess; + Memory buffer = new byte[BUFFER_SIZE]; + using var stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); + // check if the file's length is less than the buffer size + if (stream.Length < BUFFER_SIZE) + return ImageType.None; + // read only the first bytes of the file, equal to the buffer size + await stream.ReadAsync(buffer).ConfigureAwait(false); + byte[] firstBytes = buffer[..BUFFER_SIZE].ToArray(); + // check if its a known image type, based on header bytes + ImageType type = IdentifyHeader(firstBytes); + if (type != ImageType.None) + return type; + // no known image header types were found, check other methods + string content = Encoding.UTF8.GetString(buffer.ToArray()); + if (IsSvg(content, path.Path)) + return ImageType.SVG; + else if (IsTga(buffer.ToArray())) + return ImageType.TGA; + else + return ImageType.None; + } + + /// + /// Determines if the content of a file identified by belongs to a SVG. + /// + /// The initial content of the file to check. + /// Path of the file to check. + /// if the file is a SVG image, otherwise. + private bool IsSvg(string initialContent, string path) + { + // check if it starts with + /// Determines if the buffer represents a TGA file. + /// + /// Byte array to check. + /// if the file is a TGA image, otherwise. + private static bool IsTga(byte[] buffer) + { + if (buffer.Length < 18) + return false; + byte imageType = buffer[2]; + return imageType == 1 || imageType == 2 || imageType == 10; + } + + /// + /// Identifies the image type based on the provided header bytes. + /// + /// The first bytes of the file, typically used to identify the file type. + /// The type of the image, or if unrecognized. + private static ImageType IdentifyHeader(byte[] firstBytes) + { + if (Encoding.ASCII.GetBytes("BM").SequenceEqual(firstBytes[..2])) + return ImageType.BMP; // BMP + if (Encoding.ASCII.GetBytes("GIF").SequenceEqual(firstBytes[..3])) + return ImageType.GIF; // GIF + if (new byte[] { 137, 80, 78, 71 }.SequenceEqual(firstBytes[..4])) + return ImageType.PNG; // PNG + if (new byte[] { 73, 73, 42 }.SequenceEqual(firstBytes[..3]) || new byte[] { 77, 77, 42 }.SequenceEqual(firstBytes[..3])) + return ImageType.TIFF; // TIFF + if (new byte[] { 255, 216, 255, 224 }.SequenceEqual(firstBytes[..4])) + return ImageType.JPEG; // JPEG + if (new byte[] { 255, 216, 255, 225 }.SequenceEqual(firstBytes[..4])) + return ImageType.JPEG_CANON; // JPEG CANON + if (new byte[] { 255, 216, 255, 226 }.SequenceEqual(firstBytes[..4])) + return ImageType.JPEG_UNKNOWN; // JPEG UNKNOWN + if (new byte[] { 0x00, 0x11, 0x02, 0xFF }.SequenceEqual(firstBytes[..4])) + return ImageType.PICT; // PICT + if (new byte[] { 0x00, 0x00, 0x01, 0x00 }.SequenceEqual(firstBytes[..4])) + return ImageType.ICO; // ICO + if (new byte[] { 0x38, 0x42, 0x50, 0x53 }.SequenceEqual(firstBytes[..4])) + return ImageType.PSD; // PSD + if (new byte[] { 0xFF, 0x4F, 0xFF, 0x51 }.SequenceEqual(firstBytes[..4])) + return ImageType.JPEG2000; // JPEG 2000 + if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x70, 0x20, 0x20 }.SequenceEqual(firstBytes[..8])) + return ImageType.AVIF; // AVIF + if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20 }.SequenceEqual(firstBytes[..8])) + return ImageType.JPEG2000; // JPEG 2000 (variant) + if (new byte[] { 0x52, 0x49, 0x46, 0x46 }.SequenceEqual(firstBytes[..4]) && new byte[] { 0x57, 0x45, 0x42, 0x50 }.SequenceEqual(firstBytes[8..12])) + return ImageType.WEBP; // WEBP + return ImageType.None; + } + #endregion +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs new file mode 100644 index 00000000..5de743c7 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface defining the directory provider service. +/// +public interface IDirectoryProviderService +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves a list of subdirectory paths from the specified path, asynchronously. + /// + /// The path from which to retrieve the subdirectory paths. + /// An containing either a task representing the asynchronous operation for retrieving a collection of directory paths or an error. + ErrorOr>> GetSubdirectoryPathsAsync(FileSystemPathId path); + + /// + /// Checks if a directory with the specified path exists. + /// + /// The path of the directory whose existance is checked. + /// An containing either the result of checking the existance of a directory, or an error. + ErrorOr DirectoryExists(FileSystemPathId path); + + /// + /// Retrieves the file name from the specified path. + /// + /// The path to extract the file name from. + /// An containing either a file name or an error. + ErrorOr GetFileName(FileSystemPathId path); + + /// + /// Gets the last write time of a specific path. + /// + /// The path to retrieve the last write time for. + /// The last write time for the specified path, or null if unavailable. + /// An containing either the last write time of , or null if not available, or an error. + ErrorOr GetLastWriteTime(FileSystemPathId path); + + /// + /// Gets the creation time of a specific path. + /// + /// The path to retrieve the creation time for. + /// An containing either the creation time of , or null if not available, or an error. + ErrorOr GetCreationTime(FileSystemPathId path); + + /// + /// Creates a new directory with the specified name, at the specified path. + /// + /// The path where the directory will be created. + /// The name of the directory that will be created. + /// An containing either the path of a created directory, or an error. + ErrorOr CreateDirectory(FileSystemPathId path, string name); + + /// + /// Copies a directory located at to . + /// + /// Identifier for the path where the directory to be copied is located. + /// Identifier for the path where the directory will be copied. + /// Whether to override existing directories, or not. + /// An containing either the copied directory, or an error. + ErrorOr CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); + + /// + /// Moves a directory located at to . + /// + /// Identifier for the path where the directory to be moved is located. + /// Identifier for the path where the directory will be moved. + /// Whether to override existing directories, or not. + /// An containing either a moved directory, or an error. + ErrorOr MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); + + /// + /// Renames a directory at the specified path. + /// + /// The path of the directory to be renamed. + /// The new name of the directory. + /// An containing either the absolute path of the renamed directory, or an error. + ErrorOr RenameDirectory(FileSystemPathId path, string name); + + /// + /// Deletes a directory at the specified path. + /// + /// The path of the directory to be deleted. + /// An containing either the result of deleting a directory, or an error. + ErrorOr DeleteDirectory(FileSystemPathId path); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs new file mode 100644 index 00000000..98accfbe --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface for the service for handling directories. +/// +public interface IDirectoryService +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves subdirectories for the specified string path. + /// + /// String representation of the file path. + /// An containing either a collection of subdirectories or an error. + Task>> GetSubdirectoriesAsync(string path); + + /// + /// Retrieves subdirectories for the given directory. + /// + /// Directory object to retrieve subdirectories for. + /// An containing either a collection of subdirectories or an error. + Task>> GetSubdirectoriesAsync(Directory directory); + + /// + /// Retrieves subdirectories for the specified file system path. + /// + /// Identifier for the file path. + /// An containing either a collection of subdirectories or an error. + Task>> GetSubdirectoriesAsync(FileSystemPathId path); + + /// + /// Creates a directory with the specified , at the specified . + /// + /// String representation of the path where the directory will be created. + /// The name of the directory that will be created. + /// An containing either a created directory, or an error. + ErrorOr CreateDirectory(string path, string name); + + /// + /// Copies a directory located at to . + /// + /// String representation of the path where the directory to be copied is located. + /// String representation of the path where the directory will be copied. + /// Whether to override existing directories, or not. + /// An containing either a copied directory, or an error. + ErrorOr CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + + /// + /// Moves a directory located at to . + /// + /// String representation of the path where the directory to be moved is located. + /// String representation of the path where the directory will be moved. + /// Whether to override existing directories, or not. + /// An containing either a moved directory, or an error. + ErrorOr MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + + /// + /// Renames a directory with the specified , at the specified . + /// + /// String representation of the path of the directory that will be renamed. + /// The new name of the directory. + /// An containing either a renamed directory, or an error. + ErrorOr RenameDirectory(string path, string name); + + /// + /// Delete a directory for the specified string path. + /// + /// String representation of the directory path. + /// An containing either the result of deleting a directory, or an error. + ErrorOr DeleteDirectory(string path); + #endregion +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs new file mode 100644 index 00000000..3e3e3943 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface defining the file provider service. +/// +public interface IFileProviderService +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves a list of files at the specified path. + /// + /// The path for which to retrieve the list of files. + /// An containing either a task representing the asynchronous operation for retrieving a collection of file paths, or an error. + ErrorOr>> GetFilePathsAsync(FileSystemPathId path); + + /// + /// Retrieves the contents of a file at the specified path. + /// + /// The path for which to retrieve the file contents. + /// An containing either a task representing the asynchronous operation for retrieving the contents of a file at the specified path, or an error. + ErrorOr> GetFileAsync(FileSystemPathId path); + + /// + /// Checks if a file with the specified path exists. + /// + /// The path of the file whose existance is checked. + /// An containing either the result of checking the existance of a file, or an error. + ErrorOr FileExists(FileSystemPathId path); + + /// + /// Retrieves the file name from the specified path. + /// + /// The path to extract the file name from. + /// An containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error. + ErrorOr GetFileName(FileSystemPathId path); + + /// + /// Gets the last write time of a file at the specified path. + /// + /// The path of the file to retrieve the last write time for. + /// An containing either the last write time of , or null if not available, or an error. + ErrorOr GetLastWriteTime(FileSystemPathId path); + + /// + /// Gets the creation time of a file at the specified path. + /// + /// The path of the file to retrieve the creation time for. + /// An containing either the creation time of , or null if not available, or an error. + ErrorOr GetCreationTime(FileSystemPathId path); + + /// + /// Gets the size of a file at the specified path. + /// + /// The path of the file to retrieve the size for. + /// An containing either the size of or an error. + ErrorOr GetSize(FileSystemPathId path); + + /// + /// Copies a file located at to . + /// + /// Identifier for the path where the file to be copied is located. + /// Identifier for the path of the directory where the file will be copied. + /// Whether to override existing files, or not. + /// An containing either the copied file, or an error. + ErrorOr CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); + + /// + /// Moves a file located at to . + /// + /// Identifier for the path where the file to be moved is located. + /// Identifier for the path of the directory where the file will be moved. + /// Whether to override existing files, or not. + /// An containing either a moved file, or an error. + ErrorOr MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); + + /// + /// Renames a file at the specified path. + /// + /// The path of the file to be renamed. + /// The new name of the file. + /// An containing either the absolute path of the renamed file, or an error. + ErrorOr RenameFile(FileSystemPathId path, string name); + + /// + /// Deletes a file at the specified path. + /// + /// The path of the file to be deleted. + /// An containing either the result of deleting a file, or an error. + ErrorOr DeleteFile(FileSystemPathId path); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs new file mode 100644 index 00000000..d9d8780a --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface for the service for handling file system files. +/// +public interface IFileService +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Retrieves files for the specified string path. + /// + /// String representation of the file path. + /// An containing either a collection of files or an error. + Task>> GetFilesAsync(string path); + + /// + /// Retrieves files associated with a given file. + /// + /// The file object. + /// An containing either a collection of files or an error. + Task>> GetFilesAsync(File file); + + /// + /// Retrieves files for a specified file path ID. + /// + /// Identifier for the file path. + /// An containing either a collection of files or an error. + Task>> GetFilesAsync(FileSystemPathId path); + + /// + /// Copies a file located at to . + /// + /// String representation of the path where the file to be copied is located. + /// String representation of the path where the file will be copied. + /// Whether to override existing files, or not. + /// An containing either a copied file, or an error. + ErrorOr CopyFile(string sourcePath, string destinationPath, bool? overrideExisting); + + /// + /// Moves a file located at to . + /// + /// String representation of the path where the file to be moved is located. + /// String representation of the path where the file will be moved. + /// Whether to override existing files, or not. + /// An containing either a moved file, or an error. + ErrorOr MoveFile(string sourcePath, string destinationPath, bool? overrideExisting); + + /// + /// Renames a file with the specified , at the specified . + /// + /// String representation of the path of the file that will be renamed. + /// The new name of the file. + /// An containing either a renamed file, or an error. + ErrorOr RenameFile(string path, string name); + + /// + /// Delete a file for the specified string path. + /// + /// String representation of the file path. + /// An containing either the result of deleting a file, or an error. + ErrorOr DeleteFile(string path); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs new file mode 100644 index 00000000..35d01d64 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface for file system permission service. +/// +public interface IFileSystemPermissionsService +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks if can be accessed. + /// + /// The path to be accessed. + /// The mode in which to access the path. + /// Indicates whether the path represents a file or directory. + /// , if can be accessed, otherwise. + bool CanAccessPath(FileSystemPathId path, FileAccessMode accessMode, bool isFile = true); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs new file mode 100644 index 00000000..da7a1a9f --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface defining methods for handling file-related operations based on different sources. +/// +public interface IFileTypeService +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Determines if is of type image or not, and returns its type. + /// + /// The file to determine if it is an image or not. + /// An containing the type of image or an error. + Task> GetImageTypeAsync(File file); + + /// + /// Determines if a file identified by is of type image or not, and returns its type. + /// + /// The path of the file to determine if it is an image or not. + /// An containing the type of image or an error. + Task> GetImageTypeAsync(FileSystemPathId path); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs new file mode 100644 index 00000000..f49a8e5e --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface for the service for handling file system paths. +/// +public interface IPathService +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the character used to separate path segments. + /// + char PathSeparator { get; } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks if is a valid path. + /// + /// The path to be checked. + /// if is a valid path, otherwise. + bool IsValidPath(string path); + + /// + /// Tries to combine with . + /// + /// The path to be combined. + /// The name to be combined with the path. + /// An containing the combined path, or an error. + ErrorOr CombinePath(string path, string name); + + /// + /// Parses into path segments. + /// + /// The path to be parsed. + /// An containing the path segments, or an error. + ErrorOr> ParsePath(string path); + + /// + /// Goes up one level from , and returns the path segments. + /// + /// The path from which to navigate up one level. + /// An containing the path segments of the path up one level from , or an error. + ErrorOr> GoUpOneLevel(string path); + + /// + /// Returns a collection of characters that are invalid for paths. + /// + /// A collection of characters that are invalid in the context of paths. + char[] GetInvalidPathCharsForPlatform(); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs new file mode 100644 index 00000000..58765b81 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Interface for the service for handling thumbnails. +/// +public interface IThumbnailService +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the thumbnail of a file at the specified path. + /// + /// String representation of the file path. + /// The quality of the thumbnail to get. + /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. + Task> GetThumbnailAsync(string path, int quality); + + /// + /// Gets the thumbnail of a file at the specified path. + /// + /// The path object. + /// The quality of the thumbnail to get. + /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. + Task> GetThumbnailAsync(FileSystemPathId path, int quality); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs new file mode 100644 index 00000000..a02a1ec9 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Service defining methods for handling path-related operations. +/// +public class PathService : IPathService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPlatformContext _platformContext; + #endregion + + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the character used to separate path segments. + /// + public char PathSeparator + { + get { return _platformContext.PathStrategy.PathSeparator; } + } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for platform contextual services. + public PathService(IPlatformContextManager platformContextManager) + { + _platformContext = platformContextManager.GetCurrentContext(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks if is a valid path. + /// + /// The path to be checked. + /// if is a valid path, otherwise. + public bool IsValidPath(string path) + { + ErrorOr newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsError) + return false; + return _platformContext.PathStrategy.IsValidPath(newPathResult.Value); + } + + /// + /// Tries to combine with . + /// + /// The path to be combined. + /// The name to be combined with the path. + /// An containing the combined path, or an error. + public ErrorOr CombinePath(string path, string name) + { + ErrorOr newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsError) + return newPathResult.Errors; + ErrorOr combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name); + if (combinedPathResult.IsError) + return combinedPathResult.Errors; + return combinedPathResult.Value.Path; + } + + /// + /// Parses into path segments. + /// + /// The path to be parsed. + /// An containing the path segments, or an error. + public ErrorOr> ParsePath(string path) + { + ErrorOr newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsError) + return newPathResult.Errors; + return _platformContext.PathStrategy.ParsePath(newPathResult.Value); + } + + /// + /// Goes up one level from , and returns the path segments. + /// + /// The path from which to navigate up one level. + /// An containing the path segments of the path up one level from , or an error. + public ErrorOr> GoUpOneLevel(string path) + { + ErrorOr newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsError) + return newPathResult.Errors; + return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value); + } + + /// + /// Returns a collection of characters that are invalid for paths. + /// + /// A collection of characters that are invalid in the context of paths. + public char[] GetInvalidPathCharsForPlatform() + { + return _platformContext.PathStrategy.GetInvalidPathCharsForPlatform(); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs new file mode 100644 index 00000000..a1aa3c72 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs @@ -0,0 +1,190 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.Processing; +using System; +using System.IO; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; + +/// +/// Service for handling thumbnails. +/// +public class ThumbnailService : IThumbnailService +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IEnvironmentContext _environmentContext; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected environment context. + public ThumbnailService(IEnvironmentContext environmentContext) + { + _environmentContext = environmentContext; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the thumbnail of a file at the specified path. + /// + /// String representation of the file path. + /// The quality of the thumbnail to get. + /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. + public async Task> GetThumbnailAsync(string path, int quality) + { + var fileSystemPathIdResult = FileSystemPathId.Create(path); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality); + } + + /// + /// Gets the thumbnail of a file at the specified path. + /// + /// The path of the file for which to get the thumbnail. + /// The quality of the thumbnail to get. + /// 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) + { + // first, get the type of the image file + var imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path); + if (imageTypeResult.IsError) + return imageTypeResult.Errors; + if (imageTypeResult.Value != ImageType.None) + { + // then, get its bytes + var resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); + if (resultFileContents.IsError) + return resultFileContents.Errors; + byte[] fileContents = await resultFileContents.Value; + // finally, resize or adjust quality based on image type + byte[]? adjustedImage = null; + if (imageTypeResult.Value == ImageType.JPEG || imageTypeResult.Value == ImageType.JPEG_CANON || imageTypeResult.Value == ImageType.JPEG2000 + || imageTypeResult.Value == ImageType.JPEG_UNKNOWN || imageTypeResult.Value == ImageType.PNG || imageTypeResult.Value == ImageType.BMP + || imageTypeResult.Value == ImageType.WEBP || imageTypeResult.Value == ImageType.GIF || imageTypeResult.Value == ImageType.TIFF || imageTypeResult.Value == ImageType.TGA) + adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality); + return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents); + } + else + return Errors.Thumbnails.NoThumbnail; + } + + /// + /// Adjusts the quality or compression of an image, based on its format. + /// + /// The byte array of the source image. + /// The format of the image whose quality is adjusted. + /// A value between 1 (lowest quality) to 100 (highest quality). + /// A byte array representing the processed image. + private static async Task AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality) + { + using var inputMemoryStream = new MemoryStream(imageBytes); + using var outputMemoryStream = new MemoryStream(); + switch (imageType) + { + case ImageType.JPEG: + case ImageType.JPEG2000: + case ImageType.JPEG_CANON: + case ImageType.JPEG_UNKNOWN: + { + using var image = await Image.LoadAsync(inputMemoryStream); + await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality }); + break; + } + case ImageType.PNG: + { + using var image = await Image.LoadAsync(inputMemoryStream); + // PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression + int compressionLevel = MapRange(quality, 1, 100, 1, 9); + var encoder = new PngEncoder { CompressionLevel = (PngCompressionLevel)compressionLevel }; + await image.SaveAsync(outputMemoryStream, encoder); + break; + } + case ImageType.BMP: + { + using var image = await Image.LoadAsync(inputMemoryStream); + await image.SaveAsync(outputMemoryStream, new PngEncoder()); // convert BMP to PNG for compression + break; + } + default: + return imageBytes; // for unsupported formats, just return the original bytes + } + return outputMemoryStream.ToArray(); + } + + /// + /// Adjusts the quality or size of an image, based on its format. + /// + /// The byte array of the source image. + /// The format of the image whose quality is adjusted. + /// A value between 1 (lowest quality) to 100 (highest quality). + /// The bytes of the adjusted image. + private static async Task AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality) + { + using var inputMemoryStream = new MemoryStream(imageBytes); + using var outputMemoryStream = new MemoryStream(); + Image image = await Image.LoadAsync(inputMemoryStream); + double ratio = quality / 100.0; + int newWidth = (int)(image.Width * ratio); + int newHeight = (int)(image.Height * ratio); + // ensure new dimensions are not zero + newWidth = Math.Max(1, newWidth); + newHeight = Math.Max(1, newHeight); + var options = new ResizeOptions + { + Size = new Size(newWidth, newHeight), + Mode = ResizeMode.Max + }; + // resize the image to the specified size + image.Mutate(ctx => ctx.Resize(options)); + // save the resized image and return its bytes + switch (imageType) + { + case ImageType.BMP: + case ImageType.PNG: + case ImageType.GIF: + case ImageType.TGA: + case ImageType.WEBP: + case ImageType.TIFF: + case ImageType.JPEG: + case ImageType.JPEG2000: + case ImageType.JPEG_CANON: + case ImageType.JPEG_UNKNOWN: + await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!); + break; + default: + return imageBytes; // for unsupported formats, just return the original bytes + } + return outputMemoryStream.ToArray(); + } + + /// + /// Maps a given value from a source range to a target range. + /// + /// The value to map. + /// The inclusive lower bound of the source range. + /// The inclusive upper bound of the source range. + /// The inclusive lower bound of the target range. + /// The inclusive upper bound of the target range. + /// + /// A value mapped to the target range. + /// + private static int MapRange(int value, int fromSource, int toSource, int fromTarget, int toTarget) + { + return (value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource) + fromTarget; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs new file mode 100644 index 00000000..12114b94 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs @@ -0,0 +1,42 @@ +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; + +/// +/// Represents the context for environment-specific operations and services. +/// +internal class EnvironmentContext : IEnvironmentContext +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the service for identifying and handling different file types. + /// + public IFileTypeService FileTypeService { get; private set; } + + /// + /// Gets the service for performing file-related operations. + /// + public IFileProviderService FileProviderService { get; private set; } + + /// + /// Gets the service for performing directory-related operations. + /// + public IDirectoryProviderService DirectoryProviderService { get; private set; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for directory providers. + /// Injected service for file providers. + /// Injected service for file type. + public EnvironmentContext(IDirectoryProviderService directoryProviderService, IFileProviderService fileProviderService, IFileTypeService fileTypeService) + { + FileTypeService = fileTypeService; + FileProviderService = fileProviderService; + DirectoryProviderService = directoryProviderService; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs new file mode 100644 index 00000000..8e0dae20 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; + +/// +/// Interface for defining the contract of an environment-specific context, encapsulating all platform-specific services and strategies. +/// +public interface IEnvironmentContext +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the service for identifying and handling different file types. + /// + IFileTypeService FileTypeService { get; } + + /// + /// Gets the service for providing file system files. + /// + IFileProviderService FileProviderService { get; } + + /// + /// Gets the service for providing file system directories. + /// + IDirectoryProviderService DirectoryProviderService { get; } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs new file mode 100644 index 00000000..d56164b1 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; + +/// +/// Interface defining methods for handling path-related operations based on different platforms. +/// +public interface IPathStrategy +{ + #region ==================================================================== PROPERTIES ================================================================================= + public char PathSeparator { get; } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks if is a valid path. + /// + /// The path to be checked. + /// if is a valid path, otherwise. + bool IsValidPath(FileSystemPathId path); + + /// + /// Tries to combine with . + /// + /// The path to be combined. + /// The name to be combined with the path. + /// An containing the combined path, or an error. + ErrorOr CombinePath(FileSystemPathId path, string name); + + /// + /// Parses into path segments. + /// + /// The path to be parsed. + /// An containing the path segments, or an error. + ErrorOr> ParsePath(FileSystemPathId path); + + /// + /// Goes up one level from , and returns the path segments. + /// + /// The path from which to navigate up one level. + /// An containing the path segments of the path up one level from , or an error. + ErrorOr> GoUpOneLevel(FileSystemPathId path); + + /// + /// Returns a collection of characters that are invalid for paths. + /// + /// A collection of characters that are invalid in the context of paths + char[] GetInvalidPathCharsForPlatform(); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs new file mode 100644 index 00000000..74feabe5 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; + +/// +/// Interface defining methods for handling path-related operations on UNIX platforms. +/// +public interface IUnixPathStrategy : IPathStrategy +{ +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs new file mode 100644 index 00000000..47599331 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; + +/// +/// Interface defining methods for handling path-related operations on Windows platforms. +/// +public interface IWindowsPathStrategy : IPathStrategy +{ +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs new file mode 100644 index 00000000..f1e23e11 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; + +/// +/// Service defining methods for handling path-related operations on UNIX platforms. +/// +public class UnixPathStrategy : IUnixPathStrategy +{ + #region ==================================================================== PROPERTIES ================================================================================= + public char PathSeparator + { + get { return '/'; } + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks if is a valid path. + /// + /// The path to be checked. + /// if is a valid path, otherwise. + public bool IsValidPath(FileSystemPathId path) + { + // check for invalid path characters + var invalidChars = GetInvalidPathCharsForPlatform(); + if (path.Path.IndexOfAny(invalidChars) >= 0) + return false; + // check for relative paths + if (path.Path.StartsWith("./") || path.Path.StartsWith("../")) + return false; + var pathPattern = @"^\/([\w\-\.\~!$&'()*+,;=:@ ]+(\/[\w\-\.\~!$&'()*+,;=:@ ]+)*)?\/?$"; + return Regex.IsMatch(path.Path, pathPattern); + } + + /// + /// Tries to combine with . + /// + /// The path to be combined. + /// The name to be combined with the path. + /// An containing the combined path, or an error. + public ErrorOr CombinePath(FileSystemPathId path, string name) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.FileManagement.NameCannotBeEmptyError; + // trim any directory separator characters from the end of the path + string subpath = path.Path.TrimEnd(PathSeparator); + // if the name begins with a directory separator, remove it + name = name.TrimStart(PathSeparator); + // combine the two parts with the Unix directory separator character + return FileSystemPathId.Create(subpath + PathSeparator + name); + } + + /// + /// Parses into path segments. + /// + /// The path to be parsed. + /// An containing the path segments, or an error. + public ErrorOr> ParsePath(FileSystemPathId path) + { + // if path starts with anything other than '/', it's considered relative and invalid for this parser + if (!path.Path.StartsWith(PathSeparator)) + return Errors.FileManagement.InvalidPathError; + // get the path segments + var splitSegments = path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries).ToList(); + IEnumerable segments = splitSegments.Select((segment, index) => + { + bool isDirectory; + if (segment.Contains('.')) + isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the path ends with a '/' + else + isDirectory = true; + return new PathSegment(segment, isDirectory, isDrive: false); + }); + return ErrorOrFactory.From(segments); + } + + /// + /// Goes up one level from , and returns the path segments. + /// + /// The path from which to navigate up one level. + /// An containing the path segments of the path up one level from , or an error. + public ErrorOr> GoUpOneLevel(FileSystemPathId path) + { + // validation: ensure the path is not null or empty + if (!IsValidPath(path)) + return Errors.FileManagement.InvalidPathError; + // trim trailing slash for consistent processing + string tempPath = path.Path; + if (tempPath.EndsWith("/")) + tempPath = tempPath.TrimEnd(PathSeparator); + // find the last occurrence of a slash + var lastIndex = tempPath.LastIndexOf(PathSeparator); + // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error + if (lastIndex < 0) + return Errors.FileManagement.CannotNavigateUpError; + // return the path up to the last slash, or, if there's only the root slash, return that one instead + ErrorOr newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); + if (newPathResult.IsError) + return newPathResult.Errors; + return ParsePath(newPathResult.Value); + } + + /// + /// Returns a collection of characters that are invalid for paths. + /// + /// A collection of characters that are invalid in the context of paths + public char[] GetInvalidPathCharsForPlatform() + { + return ['\0']; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs new file mode 100644 index 00000000..cce1f4d0 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using ErrorOr; +using System.Collections.Generic; +using Lumina.Domain.Common.Errors; +using System.Text.RegularExpressions; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; + +/// +/// Service defining methods for handling path-related operations on Windows platforms. +/// +public class WindowsPathStrategy : IWindowsPathStrategy +{ + #region ==================================================================== PROPERTIES ================================================================================= + public char PathSeparator + { + get { return '\\'; } + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks if is a valid path. + /// + /// The path to be checked. + /// if is a valid path, otherwise. + public bool IsValidPath(FileSystemPathId path) + { + // check for invalid path characters + var invalidChars = GetInvalidPathCharsForPlatform(); + if (path.Path.IndexOfAny(invalidChars) >= 0) + return false; + // regular expression to match valid absolute paths + // this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share) + var pathPattern = @"^[a-zA-Z]:\\(?:[a-zA-Z0-9\s().-]+\\)*[a-zA-Z0-9\s().-]*\\?$"; + return Regex.IsMatch(path.Path, pathPattern); + } + + /// + /// Tries to combine with . + /// + /// The path to be combined. + /// The name to be combined with the path. + /// An containing the combined path, or an error. + public ErrorOr CombinePath(FileSystemPathId path, string name) + { + if (name == null) + return Errors.FileManagement.NameCannotBeEmptyError; + // trim any directory separator characters from the end of the path + string subpath = path.Path.TrimEnd(PathSeparator); + // if the name begins with a directory separator, remove it + name = name.TrimStart(PathSeparator); + // combine the two parts with the Windows directory separator character + return FileSystemPathId.Create(subpath + PathSeparator + name); + } + + /// + /// Parses into path segments. + /// + /// The path to be parsed. + /// An containing the path segments, or an error. + public ErrorOr> ParsePath(FileSystemPathId path) + { + // Windows paths usually start with a drive letter and colon, e.g., "C:" + if (!path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator) + return Errors.FileManagement.InvalidPathError; + return ErrorOrFactory.From(GetPathSegments()); + IEnumerable GetPathSegments() + { + // the drive segment + yield return new PathSegment(path.Path[..2], isDirectory: false, isDrive: true); + // extract the other segments + var segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + for (var i = 0; i < segments.Length; i++) + { + var segment = segments[i]; + bool isDirectory; + if (segment.Contains('.')) + isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter + else + isDirectory = true; + yield return new PathSegment(segment, isDirectory, isDrive: false); + } + } + } + + /// + /// Goes up one level from , and returns the path segments. + /// + /// The path from which to navigate up one level. + /// An containing the path segments of the path up one level from , or an error. + public ErrorOr> GoUpOneLevel(FileSystemPathId path) + { + // validation: ensure the path is not null or empty + if (!IsValidPath(path)) + return Errors.FileManagement.InvalidPathError; + // if path is just a drive letter followed by ":\", return null + if (Regex.IsMatch(path.Path, @"^[a-zA-Z]:\\?$")) + return Errors.FileManagement.CannotNavigateUpError; + // trim trailing slash for consistent processing + string tempPath = path.Path; + if (tempPath.EndsWith("\\")) + tempPath = tempPath.TrimEnd(PathSeparator); + // find the last occurrence of a slash + var lastIndex = tempPath.LastIndexOf(PathSeparator); + // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error + if (lastIndex < 0) + return Errors.FileManagement.CannotNavigateUpError; + // if we are at the drive root level after trimming, return drive root, otherwise, return the path up to the last slash + ErrorOr newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]); + if (newPathResult.IsError) + return newPathResult.Errors; + return ParsePath(newPathResult.Value); + } + + /// + /// Returns a collection of characters that are invalid for paths. + /// + /// A collection of characters that are invalid in the context of paths + public char[] GetInvalidPathCharsForPlatform() + { + return ['<', '>', '"', '/', '|', '?', '*']; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs new file mode 100644 index 00000000..1cf3adde --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Interface for defining the contract of a platform-specific context. +/// +public interface IPlatformContext +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the platform for the current platform context. + /// + PlatformType Platform { get; } + + /// + /// Gets the path strategy for the current platform context. + /// + IPathStrategy PathStrategy { get; } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs new file mode 100644 index 00000000..1738472e --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs @@ -0,0 +1,16 @@ +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Interface defining an factory for creating platform contexts. +/// +public interface IPlatformContextFactory +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates and returns the appropriate platform context. + /// + /// The type of platform context to create. + /// The created platform context. + TIPlatformContext CreateStrategy() where TIPlatformContext : IPlatformContext; + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs new file mode 100644 index 00000000..527249fd --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using Lumina.Domain.Common.Enums; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Interface for managing the platform context. +/// +public interface IPlatformContextManager +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the current platform context. + /// + /// The current platform context. + IPlatformContext GetCurrentContext(); + + /// + /// Sets the current platform context. + /// + /// The platform to be set. + /// Thrown when an unsupported platform type is provided. + void SetCurrentPlatform(PlatformType platformType); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs new file mode 100644 index 00000000..3331f7e6 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Interface defining the platform context for UNIX platforms. +/// +public interface IUnixPlatformContext : IPlatformContext +{ +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs new file mode 100644 index 00000000..de3e7239 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Interface defining the platform context for Windows platforms. +/// +internal interface IWindowsPlatformContext : IPlatformContext +{ +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs new file mode 100644 index 00000000..4579eeca --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.DependencyInjection; +using System; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Defines a factory for creating platform contexts. +/// +public class PlatformContextFactory : IPlatformContextFactory +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IServiceProvider _serviceProvider; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The service provider. + public PlatformContextFactory(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates and returns the appropriate platform context. + /// + /// The type of platform context to create. + /// The created platform context. + public TPlatformContext CreateStrategy() where TPlatformContext : IPlatformContext + { + return _serviceProvider.GetRequiredService() ?? throw new ArgumentException(); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs new file mode 100644 index 00000000..1a0c1c38 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using System; +using System.Runtime.InteropServices; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Service for managing the platform context. +/// +public class PlatformContextManager : IPlatformContextManager +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private IPlatformContext? _currentPlatformContext; + private readonly IPlatformContextFactory _platformContextFactory; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating platform contexts. + public PlatformContextManager(IPlatformContextFactory platformContextFactory) + { + _platformContextFactory = platformContextFactory; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the current platform context. + /// + /// The current platform context. + public IPlatformContext GetCurrentContext() + { + // set a default context if none is set + if (_currentPlatformContext is null) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + SetCurrentPlatform(PlatformType.Unix); + else + SetCurrentPlatform(PlatformType.Windows); + } + return _currentPlatformContext!; + } + + /// + /// Sets the current platform context. + /// + /// The platform to be set. + /// Thrown when an unsupported platform type is provided. + public void SetCurrentPlatform(PlatformType platformType) + { + // determine the correct context based on platformType + _currentPlatformContext = platformType switch + { + PlatformType.Unix => _platformContextFactory.CreateStrategy(), + PlatformType.Windows => _platformContextFactory.CreateStrategy(), + _ => throw new ArgumentException($"Unsupported platform type: {platformType}"), + }; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs new file mode 100644 index 00000000..dee7629a --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Platform context for UNIX platforms. +/// +internal class UnixPlatformContext : IUnixPlatformContext +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the platform type, which is Unix for this context. + /// + public PlatformType Platform { get; } = PlatformType.Unix; + + /// + /// Gets the path strategy for Unix platforms. + /// + public IPathStrategy PathStrategy { get; private set; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for creating path strategies for UNIX platforms. + public UnixPlatformContext(IUnixPathStrategy unixPathStrategy) + { + PathStrategy = unixPathStrategy; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs new file mode 100644 index 00000000..3f67c41a --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Platform context for Windows platforms. +/// +public class WindowsPlatformContext : IWindowsPlatformContext +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the platform type, which is Windows for this context. + /// + public PlatformType Platform { get; } = PlatformType.Windows; + + /// + /// Gets the path strategy for Windows platforms. + /// + public IPathStrategy PathStrategy { get; private set; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for creating path strategies for Windows platforms. + public WindowsPlatformContext(IWindowsPathStrategy windowsPathStrategy) + { + PathStrategy = windowsPathStrategy; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs deleted file mode 100644 index 8aa2f743..00000000 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs +++ /dev/null @@ -1,92 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.Errors; -#endregion - -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; - -/// -/// Value Object for the information of a file. -/// -public class FileInfo : ValueObject -{ - #region ==================================================================== PROPERTIES ================================================================================= - /// - /// Gets the path of the file. - /// - public string Path { get; } - - /// - /// Gets the extension of the file. - /// - public string FileExtension { get; } - - /// - /// Gets the size of the file, in bytes. - /// - public long SizeInBytes { get; } - - /// - /// Gets the last modification date of the file. - /// - public DateTime LastModified { get; } - - /// - /// Gets the optional MIME type of the file. - /// - public Optional MimeType { get; } - #endregion - - #region ====================================================================== CTOR ===================================================================================== - /// - /// Initializes a new instance of the class. - /// - /// The full path of the file. - /// The file extension. - /// The size of the file in bytes. - /// The date and time when the file was last modified. - /// The MIME type of the file, if available. - private FileInfo(string path, string fileExtension, long sizeInBytes, DateTime lastModified, Optional mimeType) - { - Path = path; - FileExtension = fileExtension; - SizeInBytes = sizeInBytes; - LastModified = lastModified; - MimeType = mimeType; - } - #endregion - - #region ===================================================================== METHODS =================================================================================== - /// - /// Creates a new instance of the class. - /// - /// The full path of the file. - /// The file extension. - /// The size of the file in bytes. - /// The date and time when the file was last modified. - /// The MIME type of the file, if available. - /// - /// An containing either a successfully created , or an error message. - /// - public static ErrorOr Create(string path, string fileExtension, long sizeInBytes, DateTime lastModified, Optional mimeType) - { - if (path is null) - return Errors.FileManagement.PathCannotBeEmpty; - if (fileExtension is null) - return Errors.FileManagement.ExtensionCannotBeEmpty; - return new FileInfo(path, fileExtension, sizeInBytes, lastModified, mimeType); - } - - /// - public override IEnumerable GetEqualityComponents() - { - yield return Path; - yield return SizeInBytes; - yield return FileExtension; - yield return LastModified; - yield return MimeType; - } - #endregion -} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemId.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemId.cs new file mode 100644 index 00000000..40cce931 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemId.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; + +/// +/// Value Object for the Id of a book. +/// +[DebuggerDisplay("{Value}")] +public sealed class FileSystemId : EntityId +{ + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private FileSystemId(Guid value) : base(value) + { + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static FileSystemId CreateUnique() + { + return new FileSystemId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static FileSystemId Create(Guid value) + { + return new FileSystemId(value); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs new file mode 100644 index 00000000..8d3dd05a --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; + +/// +/// Value Object uniquely identifying file system items. +/// +[DebuggerDisplay("{Path}")] +public sealed class FileSystemPathId : ValueObject +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the value of this object. + /// + public string Path { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The path of the file system item. + private FileSystemPathId(string path) + { + Path = path; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + public override IEnumerable GetEqualityComponents() + { + yield return Path; + } + + /// + /// Creates a new instance of the class. + /// + /// The path of the file system item. + /// + /// An containing either a successfully created or an error message. + /// + public static ErrorOr Create(string path) + { + if (string.IsNullOrWhiteSpace(path)) + return Errors.FileManagement.InvalidPathError; + return new FileSystemPathId(path); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs new file mode 100644 index 00000000..d8e3d326 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; + +/// +/// Value object uniquely identifying path segments. +/// +[DebuggerDisplay("{Name}")] +public class PathSegment : ValueObject +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the name of the path segment. + /// + public string Name { get; } + + /// + /// Gets the value indicating if the current path segment is a file system directory or not. + /// + public bool IsDirectory { get; } + + /// + /// Gets the value indicating if the current path segment is a file system drive or not. + /// + public bool IsDrive { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The name of the path segment. + /// Value indicating if the current path segment is a file system directory or not. + /// Value indicating if the current path segment is a file system drive or not. + public PathSegment(string name, bool isDirectory, bool isDrive) + { + Name = name; + IsDirectory = isDirectory; + IsDrive = isDrive; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + public override IEnumerable GetEqualityComponents() + { + yield return Name; + yield return IsDirectory; + yield return IsDrive; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs index 5edf393b..282e7e8e 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.Errors; +using System.Collections.Generic; +using System.Diagnostics; #endregion namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; @@ -10,6 +12,7 @@ namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.V /// /// Value Object for the information about a media stream. /// +[DebuggerDisplay("{StreamId}")] public class StreamInfo : ValueObject { #region ==================================================================== PROPERTIES ================================================================================= @@ -100,7 +103,7 @@ public class StreamInfo : ValueObject /// The sample rate of the stream (for audio). /// The number of channels (for audio). /// - /// An containing either a successfully created , or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( string streamId, diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs new file mode 100644 index 00000000..12cb98ed --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Models.Core; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; + +/// +/// Value object for file system thumbnails. +/// +[DebuggerDisplay("{Type}")] +public class Thumbnail : ValueObject +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the type of the image represented by this thumbnail. + /// + public ImageType Type { get; } + + /// + /// Gets the bytes of the image represented by this thumbnail. + /// + public byte[] Bytes { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The type of the image represented by this thumbnail. + /// The bytes of the image represented by this thumbnail. + public Thumbnail(ImageType type, byte[] bytes) + { + Type = type; + Bytes = bytes; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + public override IEnumerable GetEqualityComponents() + { + yield return Type; + yield return Bytes; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index 2d93ae59..cf0f9fd9 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -2,7 +2,7 @@ net8.0 - enable + disable enable ..\..\bin\ false @@ -14,6 +14,15 @@ + + + + + + + + +