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