mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds File System Domain aggregate
This commit is contained in:
1 parent
4301b0a3ee
commit
dfc7112cb7
51 files changed
+3626
-95
No files matched your search
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains all services of the Domain layer.
|
||||
/// </summary>
|
||||
public static class DomainLayerServices
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Registers the services of the Domain layer into the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddDomainLayerServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<IDirectoryService, DirectoryService>();
|
||||
services.AddScoped<IFileService, FileService>();
|
||||
services.AddScoped<IFileSystemPermissionsService, FileSystemPermissionsService>();
|
||||
services.AddScoped<IDirectoryProviderService, DirectoryProviderService>();
|
||||
services.AddScoped<IFileProviderService, FileProviderService>();
|
||||
services.AddScoped<IThumbnailService, ThumbnailService>();
|
||||
services.AddScoped<IPathService, PathService>();
|
||||
services.AddScoped<IFileTypeService, FileTypeService>();
|
||||
services.AddScoped<IEnvironmentContext, EnvironmentContext>();
|
||||
services.AddScoped<IPlatformContextFactory, PlatformContextFactory>();
|
||||
services.AddScoped<IUnixPlatformContext, UnixPlatformContext>();
|
||||
services.AddScoped<IWindowsPlatformContext, WindowsPlatformContext>();
|
||||
services.AddScoped<IPlatformContextManager, PlatformContextManager>();
|
||||
services.AddScoped<IUnixPathStrategy, UnixPathStrategy>();
|
||||
services.AddScoped<IWindowsPathStrategy, WindowsPathStrategy>();
|
||||
services.AddSingleton<IFileSystem, FileSystem>();
|
||||
return services;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace Lumina.Domain.Common.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for file access mode types.
|
||||
/// </summary>
|
||||
public enum FileAccessMode
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the ability to list the contents of a directory.
|
||||
/// </summary>
|
||||
ListDirectory,
|
||||
|
||||
/// <summary>
|
||||
/// Represents the ability to read file or directory properties.
|
||||
/// </summary>
|
||||
ReadProperties,
|
||||
|
||||
/// <summary>
|
||||
/// Represents the ability to read the contents of a file.
|
||||
/// </summary>
|
||||
ReadContents,
|
||||
|
||||
/// <summary>
|
||||
/// Represents the ability to write to a file or directory.
|
||||
/// </summary>
|
||||
Write,
|
||||
|
||||
/// <summary>
|
||||
/// Represents the ability to execute a file.
|
||||
/// </summary>
|
||||
Execute,
|
||||
|
||||
/// <summary>
|
||||
/// Represents the ability to delete a file or directory.
|
||||
/// </summary>
|
||||
Delete,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Lumina.Domain.Common.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for file system item statuses types.
|
||||
/// </summary>
|
||||
public enum FileSystemItemStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// Indicates that the file system item is accessible.
|
||||
/// </summary>
|
||||
Accessible,
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that the file system item is inaccessible due to permissions or other restrictions.
|
||||
/// </summary>
|
||||
Inaccessible,
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that the status of the file system item could not be determined due to an unknown error.
|
||||
/// </summary>
|
||||
UnknownError
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Lumina.Domain.Common.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the types of file system elements.
|
||||
/// </summary>
|
||||
public enum FileSystemItemType
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a drive, such as a hard disk, USB drive, or network drive.
|
||||
/// </summary>
|
||||
Drive,
|
||||
|
||||
/// <summary>
|
||||
/// Represents a directory, which is a directory that can contain other directories or files.
|
||||
/// </summary>
|
||||
Directory,
|
||||
|
||||
/// <summary>
|
||||
/// Represents a file, which is a document, executable, or other data stored on the file system.
|
||||
/// </summary>
|
||||
File
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace Lumina.Domain.Common.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for known image types.
|
||||
/// </summary>
|
||||
public enum ImageType
|
||||
{
|
||||
None,
|
||||
BMP,
|
||||
GIF,
|
||||
PNG,
|
||||
TIFF,
|
||||
JPEG,
|
||||
JPEG_CANON,
|
||||
JPEG_UNKNOWN,
|
||||
PICT,
|
||||
ICO,
|
||||
PSD,
|
||||
JPEG2000,
|
||||
AVIF,
|
||||
WEBP,
|
||||
TGA,
|
||||
SVG,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Lumina.Domain.Common.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for platform types.
|
||||
/// </summary>
|
||||
public enum PlatformType
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents Unix-based operating systems, including Linux and macOS.
|
||||
/// </summary>
|
||||
Unix,
|
||||
|
||||
/// <summary>
|
||||
/// Represents Microsoft Windows operating systems.
|
||||
/// </summary>
|
||||
Windows,
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// Domain permission related error types.
|
||||
/// </summary>
|
||||
public static partial class Errors
|
||||
{
|
||||
public static class Permission
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
public static Error UnauthorizedAccess => Error.Failure(nameof(UnauthorizedAccess));
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// Domain thumbnails related error types.
|
||||
/// </summary>
|
||||
public static partial class Errors
|
||||
{
|
||||
public static class Thumbnails
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
public static Error NoThumbnail => Error.Failure(nameof(NoThumbnail));
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+56
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Entity representing a file system directory.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Id.Path}")]
|
||||
public class Directory : FileSystemItem
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of file system items that are children to the current directory entity.
|
||||
/// </summary>
|
||||
public List<FileSystemItem> Items { get; private set; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Directory"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the directory in the file system path.</param>
|
||||
/// <param name="name">The name of the directory.</param>
|
||||
/// <param name="dateCreated">The date and time the directory was created. Can be <see langword="null"/> if unknown.</param>
|
||||
/// <param name="dateModified">The date and time the directory was last modified. Can be <see langword="null"/> if unknown.</param>
|
||||
public Directory(FileSystemPathId id, string name, DateTime? dateCreated, DateTime? dateModified) : base(id, name, dateCreated, dateModified)
|
||||
{
|
||||
Items = [];
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Adds a file system item to the directory.
|
||||
/// </summary>
|
||||
/// <param name="item">The file system item to add.</param>
|
||||
public void AddItem(FileSystemItem item)
|
||||
{
|
||||
Items.Add(item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a file system item from the directory.
|
||||
/// </summary>
|
||||
/// <param name="item">The file system item to remove.</param>
|
||||
public void RemoveItem(FileSystemItem item)
|
||||
{
|
||||
Items.Remove(item);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+47
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Entity representing a file system file.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Id.Path}")]
|
||||
public class File : FileSystemItem
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets or sets the size in bytes of the current file entity.
|
||||
/// </summary>
|
||||
public long Size { get; private set; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="File"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the file in the file system path.</param>
|
||||
/// <param name="name">The name of the file.</param>
|
||||
/// <param name="dateCreated">The date and time the file was created. Can be <see langword="null"/> if unknown.</param>
|
||||
/// <param name="dateModified">The date and time the file was last modified. Can be <see langword="null"/> if unknown.</param>
|
||||
/// <param name="size">The size of the file in bytes.</param>
|
||||
public File(FileSystemPathId id, string name, DateTime? dateCreated, DateTime? dateModified, long size) : base(id, name, dateCreated, dateModified)
|
||||
{
|
||||
Size = size;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Updates the size of the file.
|
||||
/// </summary>
|
||||
/// <param name="newSize">The new size, in bytes.</param>
|
||||
public void UpdateSize(long newSize)
|
||||
{
|
||||
Size = newSize;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+89
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Entity representing a generic file system element.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Name}")]
|
||||
public abstract class FileSystemItem : AggregateRoot<FileSystemPathId>
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the file system item.
|
||||
/// </summary>
|
||||
public string Name { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the creation date of the file system item.
|
||||
/// Can be <see langword="null"/> if the information is not available.
|
||||
/// </summary>
|
||||
public DateTime? DateCreated { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the last modification date of the file system item.
|
||||
/// Can be <see langword="null"/> if the information is not available.
|
||||
/// </summary>
|
||||
public DateTime? DateModified { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current status of the file system item.
|
||||
/// Defaults to Accessible.
|
||||
/// </summary>
|
||||
public FileSystemItemStatus Status { get; protected set; } = FileSystemItemStatus.Accessible;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemItem"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier for the file system path.</param>
|
||||
/// <param name="name">The name of the file system item.</param>
|
||||
/// <param name="dateModified">The date and time the file system item was last modified. Can be <see langword="null"/> if unknown.</param>
|
||||
/// <param name="dateCreated">The date and time the file system item was created. Can be <see langword="null"/> if unknown.</param>
|
||||
protected FileSystemItem(FileSystemPathId id, string name, DateTime? dateModified, DateTime? dateCreated) : base(id)
|
||||
{
|
||||
Name = name;
|
||||
DateCreated = dateCreated;
|
||||
DateModified = dateModified;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Renames the file system item to the specified new name.
|
||||
/// </summary>
|
||||
/// <param name="newName">The new name for the file system item.</param>
|
||||
/// <exception cref="ArgumentException">Thrown if the new name is null or whitespace.</exception>
|
||||
public void Rename(string newName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(newName))
|
||||
throw new ArgumentException("New name cannot be empty", nameof(newName));
|
||||
Name = newName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the last modified date of the file system item.
|
||||
/// </summary>
|
||||
/// <param name="date">The new date and time of last modification.</param>
|
||||
public void UpdateLastModified(DateTime date)
|
||||
{
|
||||
DateModified = date;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the status of the filesystem item.
|
||||
/// </summary>
|
||||
/// <param name="status">The status to be set.</param>
|
||||
public void SetStatus(FileSystemItemStatus status)
|
||||
{
|
||||
Status = status;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+303
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Directory provider for local file systems.
|
||||
/// </summary>
|
||||
internal class DirectoryProviderService : IDirectoryProviderService
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IFileSystemPermissionsService _fileSystemPermissionsService;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoryProviderService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
|
||||
/// <param name="fileSystemPermissionsService">Injected service used to determine local filesystem permissions.</param>
|
||||
public DirectoryProviderService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
_fileSystemPermissionsService = fileSystemPermissionsService;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves a list of subdirectory paths from the specified path, asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to retrieve the subdirectory paths.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a task representing the asynchronous operation for retrieving a collection of directory paths or an error.</returns>
|
||||
public ErrorOr<Task<IEnumerable<FileSystemPathId>>> 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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a directory with the specified path exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the directory whose existance is checked.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a directory, or an error.</returns>
|
||||
public ErrorOr<bool> DirectoryExists(FileSystemPathId path)
|
||||
{
|
||||
return _fileSystem.Directory.Exists(path.Path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the file name from the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to extract the file name from.</param>
|
||||
/// <returns>The name of the file without the path, or the last segment of the path if no file name is found.</returns>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a file name or an error.</returns>
|
||||
public ErrorOr<string> GetFileName(FileSystemPathId path)
|
||||
{
|
||||
return _fileSystem.Path.GetFileName(path.Path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last write time of a specific path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to retrieve the last write time for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the last write time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
public ErrorOr<DateTime?> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the creation time of a specific path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to retrieve the creation time for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the creation time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
public ErrorOr<DateTime?> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new directory with the specified name, at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path where the directory will be created..</param>
|
||||
/// <param name="name">The name of the directory that will be created.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the path of a created directory, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a directory for the specified path.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied directory, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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<FileSystemPathId> newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName);
|
||||
if (newSourcePathResult.IsError)
|
||||
return newSourcePathResult.Errors;
|
||||
ErrorOr<FileSystemPathId> newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name));
|
||||
if (newDestinationPathResult.IsError)
|
||||
return newDestinationPathResult.Errors;
|
||||
// recursive call
|
||||
ErrorOr<FileSystemPathId> copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting);
|
||||
if (copySubDirResult.IsError)
|
||||
return copySubDirResult.Errors;
|
||||
}
|
||||
return FileSystemPathId.Create(destPath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Errors.FileManagement.DirectoryCopyError;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a directory path that is unique.
|
||||
/// </summary>
|
||||
/// <param name="destinationPath">The path from which to generate the unique directory path.</param>
|
||||
/// <returns>A unique directory path.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merges two directories.
|
||||
/// </summary>
|
||||
/// <param name="sourceDir">The source directory to be merged.</param>
|
||||
/// <param name="destDir">The destination directory to be merged.</param>
|
||||
/// <param name="overwrite">Whether to override existing files.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames a directory at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the directory to be renamed.</param>
|
||||
/// <param name="name">The new name of the directory.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed directory, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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<FileSystemPathId> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a directory at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the directory to be deleted.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
public ErrorOr<bool> 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
|
||||
}
|
||||
+321
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service for handling directories.
|
||||
/// </summary>
|
||||
public class DirectoryService : IDirectoryService
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IPlatformContext _platformContext;
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoryProviderService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
|
||||
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
|
||||
public DirectoryService(IEnvironmentContext environmentContext, IPlatformContextManager platformContextManager)
|
||||
{
|
||||
_platformContext = platformContextManager.GetCurrentContext();
|
||||
_environmentContext = environmentContext;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public async Task<ErrorOr<IEnumerable<Directory>>> GetSubdirectoriesAsync(string path)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return await GetSubdirectoriesAsync(fileSystemPathIdResult.Value).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the given directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public async Task<ErrorOr<IEnumerable<Directory>>> GetSubdirectoriesAsync(Directory directory)
|
||||
{
|
||||
return await GetSubdirectoriesAsync(directory.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public async Task<ErrorOr<IEnumerable<Directory>>> GetSubdirectoriesAsync(FileSystemPathId path)
|
||||
{
|
||||
// retrieve the list of subdirectories
|
||||
ErrorOr<Task<IEnumerable<FileSystemPathId>>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPathsAsync(path);
|
||||
if (subdirectoryPathsResult.IsError)
|
||||
return subdirectoryPathsResult.Errors;
|
||||
List<Directory> result = new();
|
||||
IEnumerable<FileSystemPathId> subdirectoryPaths = await subdirectoryPathsResult.Value.ConfigureAwait(false);
|
||||
foreach (FileSystemPathId subPath in subdirectoryPaths)
|
||||
{
|
||||
// extract directory details
|
||||
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath);
|
||||
ErrorOr<DateTime?> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath);
|
||||
ErrorOr<DateTime?> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the path where the directory will be created.</param>
|
||||
/// <param name="name">The name of the directory that will be created.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of creating a directory, or an error.</returns>
|
||||
public ErrorOr<Directory> CreateDirectory(string path, string name)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return CreateDirectory(fileSystemPathIdResult.Value, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the path where the directory will be created.</param>
|
||||
/// <param name="name">The name of the directory that will be created.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of creating a directory, or an error.</returns>
|
||||
public ErrorOr<Directory> 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<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name);
|
||||
if (newDirectoryPathResult.IsError)
|
||||
return newDirectoryPathResult.Errors;
|
||||
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(path);
|
||||
ErrorOr<DateTime?> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(path);
|
||||
ErrorOr<DateTime?> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied directory, or an error.</returns>
|
||||
public ErrorOr<Directory> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied directory, or an error.</returns>
|
||||
public ErrorOr<Directory> 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<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
|
||||
public ErrorOr<Directory> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory for the specified path.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the moved directory, or an error.</returns>
|
||||
public ErrorOr<Directory> 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<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames a directory.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the directory path.</param>
|
||||
/// <param name="name">The new name of the directory.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed directory, or an error.</returns>
|
||||
public ErrorOr<Directory> RenameDirectory(string path, string name)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return RenameDirectory(fileSystemPathIdResult.Value, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames a directory for the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the directory path.</param>
|
||||
/// <param name="name">The new name of the directory.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed directory, or an error.</returns>
|
||||
public ErrorOr<Directory> 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<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name);
|
||||
if (newDirectoryPathResult.IsError)
|
||||
return newDirectoryPathResult.Errors;
|
||||
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
|
||||
ErrorOr<DateTime?> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
|
||||
ErrorOr<DateTime?> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a directory for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the directory path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
public ErrorOr<bool> DeleteDirectory(string path)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return DeleteDirectory(fileSystemPathIdResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a directory for the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the directory path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
public ErrorOr<bool> DeleteDirectory(FileSystemPathId path)
|
||||
{
|
||||
return _environmentContext.DirectoryProviderService.DeleteDirectory(path);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+268
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// File provider for local file systems.
|
||||
/// </summary>
|
||||
internal class FileProviderService : IFileProviderService
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IFileSystemPermissionsService _fileSystemPermissionsService;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileProviderService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
|
||||
/// <param name="fileSystemPermissionsService">Injected service used to determine local filesystem permissions.</param>
|
||||
public FileProviderService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
_fileSystemPermissionsService = fileSystemPermissionsService;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves a list of file paths at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the list of files.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a task representing the asynchronous operation for retrieving a collection of file paths or an error.</returns>
|
||||
public ErrorOr<Task<IEnumerable<FileSystemPathId>>> 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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a file with the specified path exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file whose existance is checked.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a file, or an error.</returns>
|
||||
public ErrorOr<bool> FileExists(FileSystemPathId path)
|
||||
{
|
||||
return _fileSystem.File.Exists(path.Path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the file name from the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to extract the file name from.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> 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.</returns>
|
||||
public ErrorOr<string> GetFileName(FileSystemPathId path)
|
||||
{
|
||||
return _fileSystem.Path.GetFileName(path.Path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the contents of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the file contents.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a task representing the asynchronous operation for retrieving the contents of a file at the specified path, or an error.</returns>
|
||||
public ErrorOr<Task<byte[]>> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last write time of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to retrieve the last write time for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the last write time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
public ErrorOr<DateTime?> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the creation time of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to retrieve the creation time for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the creation time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
public ErrorOr<DateTime?> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the size of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to retrieve the size for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the size of <paramref name="path"/> or an error.</returns>
|
||||
public ErrorOr<long?> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a file path that is unique
|
||||
/// </summary>
|
||||
/// <param name="destinationFilePath">The path from which to generate the unique file path.</param>
|
||||
/// <returns>A unique directory path.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to be renamed.</param>
|
||||
/// <param name="name">The new name of the file.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed file, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> RenameFile(FileSystemPathId path, string name)
|
||||
{
|
||||
string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName;
|
||||
if (!string.IsNullOrEmpty(parentDirectory))
|
||||
{
|
||||
ErrorOr<FileSystemPathId> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to be deleted.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
|
||||
public ErrorOr<bool> 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
|
||||
}
|
||||
+302
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service for handling file system files.
|
||||
/// </summary>
|
||||
public class FileService : IFileService
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IPlatformContext _platformContext;
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
|
||||
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
|
||||
public FileService(IEnvironmentContext environmentContext, IPlatformContextManager platformContextManager)
|
||||
{
|
||||
_platformContext = platformContextManager.GetCurrentContext();
|
||||
_environmentContext = environmentContext;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves files for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public async Task<ErrorOr<IEnumerable<File>>> GetFilesAsync(string path)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return await GetFilesAsync(fileSystemPathIdResult.Value).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files associated with a given file.
|
||||
/// </summary>
|
||||
/// <param name="file">The file object.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public async Task<ErrorOr<IEnumerable<File>>> GetFilesAsync(File file)
|
||||
{
|
||||
return await GetFilesAsync(file.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files for a specified file path Id.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public async Task<ErrorOr<IEnumerable<File>>> GetFilesAsync(FileSystemPathId path)
|
||||
{
|
||||
// retrieve the list of files
|
||||
ErrorOr<Task<IEnumerable<FileSystemPathId>>> filePathsResult = _environmentContext.FileProviderService.GetFilePathsAsync(path);
|
||||
if (filePathsResult.IsError)
|
||||
return filePathsResult.Errors;
|
||||
List<File> result = new();
|
||||
IEnumerable<FileSystemPathId> filePaths = await filePathsResult.Value.ConfigureAwait(false);
|
||||
foreach (FileSystemPathId filePath in filePaths)
|
||||
{
|
||||
// extract file details and add to the result list
|
||||
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath);
|
||||
ErrorOr<DateTime?> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath);
|
||||
ErrorOr<DateTime?> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath);
|
||||
ErrorOr<long?> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">String representation of the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationDirectoryPath">String representation of the path of the directory where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied file, or an error.</returns>
|
||||
public ErrorOr<File> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a file for the specified path.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns>
|
||||
public ErrorOr<File> 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<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
|
||||
if (copyFileResult.IsError)
|
||||
return copyFileResult.Errors;
|
||||
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value);
|
||||
ErrorOr<DateTime?> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(copyFileResult.Value);
|
||||
ErrorOr<DateTime?> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value);
|
||||
ErrorOr<long?> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">String representation of the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationDirectoryPath">String representation of the path of the directory where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
|
||||
public ErrorOr<File> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a file for the specified path.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the moved file, or an error.</returns>
|
||||
public ErrorOr<File> 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<FileSystemPathId> moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
|
||||
if (moveFileResult.IsError)
|
||||
return moveFileResult.Errors;
|
||||
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value);
|
||||
ErrorOr<DateTime?> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(moveFileResult.Value);
|
||||
ErrorOr<DateTime?> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value);
|
||||
ErrorOr<long?> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames a file.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="name">The new name of the file.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed file, or an error.</returns>
|
||||
public ErrorOr<File> RenameFile(string path, string name)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return RenameFile(fileSystemPathIdResult.Value, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames a file for the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="name">The new name of the file.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed file, or an error.</returns>
|
||||
public ErrorOr<File> 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<FileSystemPathId> newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name);
|
||||
if (newFilePathResult.IsError)
|
||||
return newFilePathResult.Errors;
|
||||
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(newFilePathResult.Value);
|
||||
ErrorOr<DateTime?> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(newFilePathResult.Value);
|
||||
ErrorOr<DateTime?> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value);
|
||||
ErrorOr<long?> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a file for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
|
||||
public ErrorOr<bool> DeleteFile(string path)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return DeleteFile(fileSystemPathIdResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a file for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
|
||||
public ErrorOr<bool> DeleteFile(FileSystemPathId path)
|
||||
{
|
||||
return _environmentContext.FileProviderService.DeleteFile(path);
|
||||
}
|
||||
|
||||
public ErrorOr<bool> ReadFile(FileSystemPathId path)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+213
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service for file system permissions.
|
||||
/// </summary>
|
||||
internal class FileSystemPermissionsService : IFileSystemPermissionsService
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IPlatformContextManager _platformContextManager;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemPermissionsService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
|
||||
public FileSystemPermissionsService(IPlatformContextManager platformContextManager)
|
||||
{
|
||||
_platformContextManager = platformContextManager;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> can be accessed.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be accessed.</param>
|
||||
/// <param name="accessMode">The mode in which to access the path.</param>
|
||||
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
|
||||
/// <returns><see langword="true"/>, if <paramref name="path"/> can be accessed, <see langword="false"/> otherwise.</returns>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a the current user has access permissions on Linux for <paramref name="path"/>, with <paramref name="accessMode"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to check the access.</param>
|
||||
/// <param name="accessMode">The access mode in which to check that path access.</param>
|
||||
/// <returns><see langword="true"/> if the current user has rights for the specified path and acccess mode, <see langword="false"/> otherwise.</returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown when trying to check access for a mode that is not supported</exception>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a the current user has access permissions on Windows for <paramref name="path"/>, with <paramref name="accessMode"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to check the access.</param>
|
||||
/// <param name="accessMode">The access mode in which to check that path access.</param>
|
||||
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
|
||||
/// <returns><see langword="true"/> if the current user has rights for the specified path and acccess mode, <see langword="false"/> otherwise.</returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown when trying to check access for a mode that is not supported.</exception>
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current user or group has the access <paramref name="rights"/> for <paramref name="path"/>, on Windows platforms.
|
||||
/// </summary>
|
||||
/// <param name="rights">The rights for which to check access.</param>
|
||||
/// <param name="path">The path for which to check the access <paramref name="rights"/>.</param>
|
||||
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
|
||||
/// <returns><see langword="true"/>, if the current user or group has <paramref name="rights"/> for <paramref name="path"/>, <see langword="false"/> otherwise.</returns>
|
||||
[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
|
||||
}
|
||||
+159
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Class defining methods for handling file-related operations.
|
||||
/// </summary>
|
||||
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 =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileTypeService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
|
||||
/// <param name="fileSystemPermissionsService">Injected service used to determine local filesystem permissions.</param>
|
||||
public FileTypeService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
_fileSystemPermissionsService = fileSystemPermissionsService;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Determines if <paramref name="file"/> is of type image or not, and returns its type.
|
||||
/// </summary>
|
||||
/// <param name="file">The file to determine if it is an image or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
|
||||
public async Task<ErrorOr<ImageType>> GetImageTypeAsync(File file)
|
||||
{
|
||||
return await GetImageTypeAsync(file.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if a file identified by <paramref name="path"/> is of type image or not, and returns its type.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to determine if it is an image or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
|
||||
public async Task<ErrorOr<ImageType>> 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<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the content of a file identified by <paramref name="path"/> belongs to a SVG.
|
||||
/// </summary>
|
||||
/// <param name="initialContent">The initial content of the file to check.</param>
|
||||
/// <param name="path">Path of the file to check.</param>
|
||||
/// <returns><see langword="true"/> if the file is a SVG image, <see langword="false"/> otherwise.</returns>
|
||||
private bool IsSvg(string initialContent, string path)
|
||||
{
|
||||
// check if it starts with <svg
|
||||
if (initialContent.StartsWith("<svg", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
// check if it starts with <?xml
|
||||
if (initialContent.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Read more content from the file
|
||||
using var stream = _fileSystem.FileStream.New(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
byte[] svgBuffer = new byte[1000];
|
||||
stream.Read(svgBuffer, 0, 1000);
|
||||
string extendedContent = Encoding.UTF8.GetString(svgBuffer);
|
||||
// check if the extended content contains <svg
|
||||
return extendedContent.Contains("<svg", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the buffer represents a TGA file.
|
||||
/// </summary>
|
||||
/// <param name="buffer">Byte array to check.</param>
|
||||
/// <returns><see langword="true"/> if the file is a TGA image, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsTga(byte[] buffer)
|
||||
{
|
||||
if (buffer.Length < 18)
|
||||
return false;
|
||||
byte imageType = buffer[2];
|
||||
return imageType == 1 || imageType == 2 || imageType == 10;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Identifies the image type based on the provided header bytes.
|
||||
/// </summary>
|
||||
/// <param name="firstBytes">The first bytes of the file, typically used to identify the file type.</param>
|
||||
/// <returns>The type of the image, or <see cref="{ImageType.None}"/> if unrecognized.</returns>
|
||||
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
|
||||
}
|
||||
+94
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining the directory provider service.
|
||||
/// </summary>
|
||||
public interface IDirectoryProviderService
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves a list of subdirectory paths from the specified path, asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to retrieve the subdirectory paths.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a task representing the asynchronous operation for retrieving a collection of directory paths or an error.</returns>
|
||||
ErrorOr<Task<IEnumerable<FileSystemPathId>>> GetSubdirectoryPathsAsync(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a directory with the specified path exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the directory whose existance is checked.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a directory, or an error.</returns>
|
||||
ErrorOr<bool> DirectoryExists(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the file name from the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to extract the file name from.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a file name or an error.</returns>
|
||||
ErrorOr<string> GetFileName(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last write time of a specific path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to retrieve the last write time for.</param>
|
||||
/// <returns>The last write time for the specified path, or null if unavailable.</returns>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the last write time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
ErrorOr<DateTime?> GetLastWriteTime(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the creation time of a specific path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to retrieve the creation time for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the creation time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
ErrorOr<DateTime?> GetCreationTime(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new directory with the specified name, at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path where the directory will be created.</param>
|
||||
/// <param name="name">The name of the directory that will be created.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the path of a created directory, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> CreateDirectory(FileSystemPathId path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied directory, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Renames a directory at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the directory to be renamed.</param>
|
||||
/// <param name="name">The new name of the directory.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed directory, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> RenameDirectory(FileSystemPathId path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a directory at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the directory to be deleted.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
ErrorOr<bool> DeleteDirectory(FileSystemPathId path);
|
||||
#endregion
|
||||
}
|
||||
+79
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for handling directories.
|
||||
/// </summary>
|
||||
public interface IDirectoryService
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
Task<ErrorOr<IEnumerable<Directory>>> GetSubdirectoriesAsync(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the given directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
Task<ErrorOr<IEnumerable<Directory>>> GetSubdirectoriesAsync(Directory directory);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
Task<ErrorOr<IEnumerable<Directory>>> GetSubdirectoriesAsync(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the path where the directory will be created.</param>
|
||||
/// <param name="name">The name of the directory that will be created.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a created directory, or an error.</returns>
|
||||
ErrorOr<Directory> CreateDirectory(string path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be copied is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied directory, or an error.</returns>
|
||||
ErrorOr<Directory> CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the directory to be moved is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the directory will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
|
||||
ErrorOr<Directory> MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Renames a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the path of the directory that will be renamed.</param>
|
||||
/// <param name="name">The new name of the directory.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a renamed directory, or an error.</returns>
|
||||
ErrorOr<Directory> RenameDirectory(string path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Delete a directory for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the directory path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
ErrorOr<bool> DeleteDirectory(string path);
|
||||
#endregion
|
||||
}
|
||||
+99
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining the file provider service.
|
||||
/// </summary>
|
||||
public interface IFileProviderService
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves a list of files at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the list of files.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a task representing the asynchronous operation for retrieving a collection of file paths, or an error.</returns>
|
||||
ErrorOr<Task<IEnumerable<FileSystemPathId>>> GetFilePathsAsync(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the contents of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the file contents.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a task representing the asynchronous operation for retrieving the contents of a file at the specified path, or an error.</returns>
|
||||
ErrorOr<Task<byte[]>> GetFileAsync(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a file with the specified path exists.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file whose existance is checked.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a file, or an error.</returns>
|
||||
ErrorOr<bool> FileExists(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the file name from the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to extract the file name from.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> 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.</returns>
|
||||
ErrorOr<string> GetFileName(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last write time of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to retrieve the last write time for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the last write time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
ErrorOr<DateTime?> GetLastWriteTime(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the creation time of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to retrieve the creation time for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the creation time of <paramref name="path"/>, or null if not available, or an error.</returns>
|
||||
ErrorOr<DateTime?> GetCreationTime(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the size of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to retrieve the size for.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the size of <paramref name="path"/> or an error.</returns>
|
||||
ErrorOr<long?> GetSize(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Copies a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Renames a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to be renamed.</param>
|
||||
/// <param name="name">The new name of the file.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed file, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> RenameFile(FileSystemPathId path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to be deleted.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
|
||||
ErrorOr<bool> DeleteFile(FileSystemPathId path);
|
||||
#endregion
|
||||
}
|
||||
+71
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for handling file system files.
|
||||
/// </summary>
|
||||
public interface IFileService
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Retrieves files for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
Task<ErrorOr<IEnumerable<File>>> GetFilesAsync(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files associated with a given file.
|
||||
/// </summary>
|
||||
/// <param name="file">The file object.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
Task<ErrorOr<IEnumerable<File>>> GetFilesAsync(File file);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files for a specified file path ID.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
Task<ErrorOr<IEnumerable<File>>> GetFilesAsync(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Copies a file located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the file to be copied is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the file will be copied.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied file, or an error.</returns>
|
||||
ErrorOr<File> CopyFile(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a file located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">String representation of the path where the file to be moved is located.</param>
|
||||
/// <param name="destinationPath">String representation of the path where the file will be moved.</param>
|
||||
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
|
||||
ErrorOr<File> MoveFile(string sourcePath, string destinationPath, bool? overrideExisting);
|
||||
|
||||
/// <summary>
|
||||
/// Renames a file with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the path of the file that will be renamed.</param>
|
||||
/// <param name="name">The new name of the file.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a renamed file, or an error.</returns>
|
||||
ErrorOr<File> RenameFile(string path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Delete a file for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
|
||||
ErrorOr<bool> DeleteFile(string path);
|
||||
#endregion
|
||||
}
|
||||
+23
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for file system permission service.
|
||||
/// </summary>
|
||||
public interface IFileSystemPermissionsService
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> can be accessed.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be accessed.</param>
|
||||
/// <param name="accessMode">The mode in which to access the path.</param>
|
||||
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
|
||||
/// <returns><see langword="true"/>, if <paramref name="path"/> can be accessed, <see langword="false"/> otherwise.</returns>
|
||||
bool CanAccessPath(FileSystemPathId path, FileAccessMode accessMode, bool isFile = true);
|
||||
#endregion
|
||||
}
|
||||
+31
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining methods for handling file-related operations based on different sources.
|
||||
/// </summary>
|
||||
public interface IFileTypeService
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Determines if <paramref name="file"/> is of type image or not, and returns its type.
|
||||
/// </summary>
|
||||
/// <param name="file">The file to determine if it is an image or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
|
||||
Task<ErrorOr<ImageType>> GetImageTypeAsync(File file);
|
||||
|
||||
/// <summary>
|
||||
/// Determines if a file identified by <paramref name="path"/> is of type image or not, and returns its type.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to determine if it is an image or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
|
||||
Task<ErrorOr<ImageType>> GetImageTypeAsync(FileSystemPathId path);
|
||||
#endregion
|
||||
}
|
||||
+57
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for handling file system paths.
|
||||
/// </summary>
|
||||
public interface IPathService
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the character used to separate path segments.
|
||||
/// </summary>
|
||||
char PathSeparator { get; }
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> is a valid path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
|
||||
bool IsValidPath(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be combined.</param>
|
||||
/// <param name="path">The name to be combined with the path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
|
||||
ErrorOr<string> CombinePath(string path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Parses <paramref name="path"/> into path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be parsed.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
|
||||
ErrorOr<IEnumerable<PathSegment>> ParsePath(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to navigate up one level.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
|
||||
char[] GetInvalidPathCharsForPlatform();
|
||||
#endregion
|
||||
}
|
||||
+31
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for handling thumbnails.
|
||||
/// </summary>
|
||||
public interface IThumbnailService
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Gets the thumbnail of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="quality">The quality of the thumbnail to get.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
|
||||
Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the thumbnail of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path object.</param>
|
||||
/// <param name="quality">The quality of the thumbnail to get.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
|
||||
Task<ErrorOr<Thumbnail>> GetThumbnailAsync(FileSystemPathId path, int quality);
|
||||
#endregion
|
||||
}
|
||||
+106
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service defining methods for handling path-related operations.
|
||||
/// </summary>
|
||||
public class PathService : IPathService
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IPlatformContext _platformContext;
|
||||
#endregion
|
||||
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the character used to separate path segments.
|
||||
/// </summary>
|
||||
public char PathSeparator
|
||||
{
|
||||
get { return _platformContext.PathStrategy.PathSeparator; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PathService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
|
||||
public PathService(IPlatformContextManager platformContextManager)
|
||||
{
|
||||
_platformContext = platformContextManager.GetCurrentContext();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> is a valid path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
|
||||
public bool IsValidPath(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
if (newPathResult.IsError)
|
||||
return false;
|
||||
return _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be combined.</param>
|
||||
/// <param name="path">The name to be combined with the path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
|
||||
public ErrorOr<string> CombinePath(string path, string name)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
ErrorOr<FileSystemPathId> combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name);
|
||||
if (combinedPathResult.IsError)
|
||||
return combinedPathResult.Errors;
|
||||
return combinedPathResult.Value.Path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses <paramref name="path"/> into path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be parsed.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
|
||||
public ErrorOr<IEnumerable<PathSegment>> ParsePath(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return _platformContext.PathStrategy.ParsePath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to navigate up one level.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
|
||||
public char[] GetInvalidPathCharsForPlatform()
|
||||
{
|
||||
return _platformContext.PathStrategy.GetInvalidPathCharsForPlatform();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+190
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service for handling thumbnails.
|
||||
/// </summary>
|
||||
public class ThumbnailService : IThumbnailService
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThumbnailService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="environmentContext">Injected environment context.</param>
|
||||
public ThumbnailService(IEnvironmentContext environmentContext)
|
||||
{
|
||||
_environmentContext = environmentContext;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Gets the thumbnail of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="quality">The quality of the thumbnail to get.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
|
||||
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality)
|
||||
{
|
||||
var fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the thumbnail of a file at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file for which to get the thumbnail.</param>
|
||||
/// <param name="quality">The quality of the thumbnail to get.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
|
||||
public async Task<ErrorOr<Thumbnail>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adjusts the quality or compression of an image, based on its format.
|
||||
/// </summary>
|
||||
/// <param name="imageBytes">The byte array of the source image.</param>
|
||||
/// <param name="imageType">The format of the image whose quality is adjusted.</param>
|
||||
/// <param name="quality">A value between 1 (lowest quality) to 100 (highest quality).</param>
|
||||
/// <returns>A byte array representing the processed image.</returns>
|
||||
private static async Task<byte[]> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adjusts the quality or size of an image, based on its format.
|
||||
/// </summary>
|
||||
/// <param name="imageBytes">The byte array of the source image.</param>
|
||||
/// <param name="imageType">The format of the image whose quality is adjusted.</param>
|
||||
/// <param name="quality">A value between 1 (lowest quality) to 100 (highest quality).</param>
|
||||
/// <returns>The bytes of the adjusted image.</returns>
|
||||
private static async Task<byte[]> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a given value from a source range to a target range.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to map.</param>
|
||||
/// <param name="fromSource">The inclusive lower bound of the source range.</param>
|
||||
/// <param name="toSource">The inclusive upper bound of the source range.</param>
|
||||
/// <param name="fromTarget">The inclusive lower bound of the target range.</param>
|
||||
/// <param name="toTarget">The inclusive upper bound of the target range.</param>
|
||||
/// <returns>
|
||||
/// A value mapped to the target range.
|
||||
/// </returns>
|
||||
private static int MapRange(int value, int fromSource, int toSource, int fromTarget, int toTarget)
|
||||
{
|
||||
return (value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource) + fromTarget;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+42
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the context for environment-specific operations and services.
|
||||
/// </summary>
|
||||
internal class EnvironmentContext : IEnvironmentContext
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the service for identifying and handling different file types.
|
||||
/// </summary>
|
||||
public IFileTypeService FileTypeService { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the service for performing file-related operations.
|
||||
/// </summary>
|
||||
public IFileProviderService FileProviderService { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the service for performing directory-related operations.
|
||||
/// </summary>
|
||||
public IDirectoryProviderService DirectoryProviderService { get; private set; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EnvironmentContext"/> class.
|
||||
/// </summary>
|
||||
/// <param name="directoryProviderService">Injected service for directory providers.</param>
|
||||
/// <param name="fileProviderService">Injected service for file providers.</param>
|
||||
/// <param name="fileTypeService">Injected service for file type.</param>
|
||||
public EnvironmentContext(IDirectoryProviderService directoryProviderService, IFileProviderService fileProviderService, IFileTypeService fileTypeService)
|
||||
{
|
||||
FileTypeService = fileTypeService;
|
||||
FileProviderService = fileProviderService;
|
||||
DirectoryProviderService = directoryProviderService;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+29
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for defining the contract of an environment-specific context, encapsulating all platform-specific services and strategies.
|
||||
/// </summary>
|
||||
public interface IEnvironmentContext
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the service for identifying and handling different file types.
|
||||
/// </summary>
|
||||
IFileTypeService FileTypeService { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the service for providing file system files.
|
||||
/// </summary>
|
||||
IFileProviderService FileProviderService { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the service for providing file system directories.
|
||||
/// </summary>
|
||||
IDirectoryProviderService DirectoryProviderService { get; }
|
||||
#endregion
|
||||
}
|
||||
+54
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining methods for handling path-related operations based on different platforms.
|
||||
/// </summary>
|
||||
public interface IPathStrategy
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
public char PathSeparator { get; }
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> is a valid path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
|
||||
bool IsValidPath(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be combined.</param>
|
||||
/// <param name="path">The name to be combined with the path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
|
||||
ErrorOr<FileSystemPathId> CombinePath(FileSystemPathId path, string name);
|
||||
|
||||
/// <summary>
|
||||
/// Parses <paramref name="path"/> into path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be parsed.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
|
||||
ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to navigate up one level.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths</returns>
|
||||
char[] GetInvalidPathCharsForPlatform();
|
||||
#endregion
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining methods for handling path-related operations on UNIX platforms.
|
||||
/// </summary>
|
||||
public interface IUnixPathStrategy : IPathStrategy
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining methods for handling path-related operations on Windows platforms.
|
||||
/// </summary>
|
||||
public interface IWindowsPathStrategy : IPathStrategy
|
||||
{
|
||||
}
|
||||
+121
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service defining methods for handling path-related operations on UNIX platforms.
|
||||
/// </summary>
|
||||
public class UnixPathStrategy : IUnixPathStrategy
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
public char PathSeparator
|
||||
{
|
||||
get { return '/'; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> is a valid path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be combined.</param>
|
||||
/// <param name="name">The name to be combined with the path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses <paramref name="path"/> into path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be parsed.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
|
||||
public ErrorOr<IEnumerable<PathSegment>> 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<PathSegment> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to navigate up one level.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
public ErrorOr<IEnumerable<PathSegment>> 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<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return ParsePath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths</returns>
|
||||
public char[] GetInvalidPathCharsForPlatform()
|
||||
{
|
||||
return ['\0'];
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+128
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service defining methods for handling path-related operations on Windows platforms.
|
||||
/// </summary>
|
||||
public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
public char PathSeparator
|
||||
{
|
||||
get { return '\\'; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> is a valid path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be combined.</param>
|
||||
/// <param name="name">The name to be combined with the path.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
|
||||
public ErrorOr<FileSystemPathId> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses <paramref name="path"/> into path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to be parsed.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
|
||||
public ErrorOr<IEnumerable<PathSegment>> 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<PathSegment> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to navigate up one level.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
|
||||
public ErrorOr<IEnumerable<PathSegment>> 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<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return ParsePath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of paths</returns>
|
||||
public char[] GetInvalidPathCharsForPlatform()
|
||||
{
|
||||
return ['<', '>', '"', '/', '|', '?', '*'];
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+24
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for defining the contract of a platform-specific context.
|
||||
/// </summary>
|
||||
public interface IPlatformContext
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the platform for the current platform context.
|
||||
/// </summary>
|
||||
PlatformType Platform { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path strategy for the current platform context.
|
||||
/// </summary>
|
||||
IPathStrategy PathStrategy { get; }
|
||||
#endregion
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining an factory for creating platform contexts.
|
||||
/// </summary>
|
||||
public interface IPlatformContextFactory
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Creates and returns the appropriate platform context.
|
||||
/// </summary>
|
||||
/// <typeparam name="TIPlatformContext">The type of platform context to create.</typeparam>
|
||||
/// <returns>The created platform context.</returns>
|
||||
TIPlatformContext CreateStrategy<TIPlatformContext>() where TIPlatformContext : IPlatformContext;
|
||||
#endregion
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using Lumina.Domain.Common.Enums;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for managing the platform context.
|
||||
/// </summary>
|
||||
public interface IPlatformContextManager
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Gets the current platform context.
|
||||
/// </summary>
|
||||
/// <returns>The current platform context.</returns>
|
||||
IPlatformContext GetCurrentContext();
|
||||
|
||||
/// <summary>
|
||||
/// Sets the current platform context.
|
||||
/// </summary>
|
||||
/// <param name="platformType">The platform to be set.</param>
|
||||
/// <exception cref="ArgumentException">Thrown when an unsupported platform type is provided.</exception>
|
||||
void SetCurrentPlatform(PlatformType platformType);
|
||||
#endregion
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining the platform context for UNIX platforms.
|
||||
/// </summary>
|
||||
public interface IUnixPlatformContext : IPlatformContext
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining the platform context for Windows platforms.
|
||||
/// </summary>
|
||||
internal interface IWindowsPlatformContext : IPlatformContext
|
||||
{
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a factory for creating platform contexts.
|
||||
/// </summary>
|
||||
public class PlatformContextFactory : IPlatformContextFactory
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlatformContextFactory"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider.</param>
|
||||
public PlatformContextFactory(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Creates and returns the appropriate platform context.
|
||||
/// </summary>
|
||||
/// <typeparam name="TPlatformContext">The type of platform context to create.</typeparam>
|
||||
/// <returns>The created platform context.</returns>
|
||||
public TPlatformContext CreateStrategy<TPlatformContext>() where TPlatformContext : IPlatformContext
|
||||
{
|
||||
return _serviceProvider.GetRequiredService<TPlatformContext>() ?? throw new ArgumentException();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+64
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing the platform context.
|
||||
/// </summary>
|
||||
public class PlatformContextManager : IPlatformContextManager
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private IPlatformContext? _currentPlatformContext;
|
||||
private readonly IPlatformContextFactory _platformContextFactory;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlatformContextManager"/> class.
|
||||
/// </summary>
|
||||
/// <param name="platformContextFactory">Injected factory for creating platform contexts.</param>
|
||||
public PlatformContextManager(IPlatformContextFactory platformContextFactory)
|
||||
{
|
||||
_platformContextFactory = platformContextFactory;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Gets the current platform context.
|
||||
/// </summary>
|
||||
/// <returns>The current platform context.</returns>
|
||||
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!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the current platform context.
|
||||
/// </summary>
|
||||
/// <param name="platformType">The platform to be set.</param>
|
||||
/// <exception cref="ArgumentException">Thrown when an unsupported platform type is provided.</exception>
|
||||
public void SetCurrentPlatform(PlatformType platformType)
|
||||
{
|
||||
// determine the correct context based on platformType
|
||||
_currentPlatformContext = platformType switch
|
||||
{
|
||||
PlatformType.Unix => _platformContextFactory.CreateStrategy<IUnixPlatformContext>(),
|
||||
PlatformType.Windows => _platformContextFactory.CreateStrategy<IWindowsPlatformContext>(),
|
||||
_ => throw new ArgumentException($"Unsupported platform type: {platformType}"),
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+35
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Platform context for UNIX platforms.
|
||||
/// </summary>
|
||||
internal class UnixPlatformContext : IUnixPlatformContext
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the platform type, which is Unix for this context.
|
||||
/// </summary>
|
||||
public PlatformType Platform { get; } = PlatformType.Unix;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path strategy for Unix platforms.
|
||||
/// </summary>
|
||||
public IPathStrategy PathStrategy { get; private set; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnixPlatformContext"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unixPathStrategy">Injected service for creating path strategies for UNIX platforms.</param>
|
||||
public UnixPlatformContext(IUnixPathStrategy unixPathStrategy)
|
||||
{
|
||||
PathStrategy = unixPathStrategy;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+35
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Platform context for Windows platforms.
|
||||
/// </summary>
|
||||
public class WindowsPlatformContext : IWindowsPlatformContext
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the platform type, which is Windows for this context.
|
||||
/// </summary>
|
||||
public PlatformType Platform { get; } = PlatformType.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path strategy for Windows platforms.
|
||||
/// </summary>
|
||||
public IPathStrategy PathStrategy { get; private set; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WindowsPlatformContext"/> class.
|
||||
/// </summary>
|
||||
/// <param name="windowsPathStrategy">Injected service for creating path strategies for Windows platforms.</param>
|
||||
public WindowsPlatformContext(IWindowsPathStrategy windowsPathStrategy)
|
||||
{
|
||||
PathStrategy = windowsPathStrategy;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
-92
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the information of a file.
|
||||
/// </summary>
|
||||
public class FileInfo : ValueObject
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the path of the file.
|
||||
/// </summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the extension of the file.
|
||||
/// </summary>
|
||||
public string FileExtension { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the size of the file, in bytes.
|
||||
/// </summary>
|
||||
public long SizeInBytes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last modification date of the file.
|
||||
/// </summary>
|
||||
public DateTime LastModified { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional MIME type of the file.
|
||||
/// </summary>
|
||||
public Optional<string> MimeType { get; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileInfo"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">The full path of the file.</param>
|
||||
/// <param name="fileExtension">The file extension.</param>
|
||||
/// <param name="sizeInBytes">The size of the file in bytes.</param>
|
||||
/// <param name="lastModified">The date and time when the file was last modified.</param>
|
||||
/// <param name="mimeType">The MIME type of the file, if available.</param>
|
||||
private FileInfo(string path, string fileExtension, long sizeInBytes, DateTime lastModified, Optional<string> mimeType)
|
||||
{
|
||||
Path = path;
|
||||
FileExtension = fileExtension;
|
||||
SizeInBytes = sizeInBytes;
|
||||
LastModified = lastModified;
|
||||
MimeType = mimeType;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FileInfo"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">The full path of the file.</param>
|
||||
/// <param name="fileExtension">The file extension.</param>
|
||||
/// <param name="sizeInBytes">The size of the file in bytes.</param>
|
||||
/// <param name="lastModified">The date and time when the file was last modified.</param>
|
||||
/// <param name="mimeType">The MIME type of the file, if available.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="FileInfo"/>, or an error message.
|
||||
/// </returns>
|
||||
public static ErrorOr<FileInfo> Create(string path, string fileExtension, long sizeInBytes, DateTime lastModified, Optional<string> 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);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Path;
|
||||
yield return SizeInBytes;
|
||||
yield return FileExtension;
|
||||
yield return LastModified;
|
||||
yield return MimeType;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+52
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a book.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Value}")]
|
||||
public sealed class FileSystemId : EntityId<Guid>
|
||||
{
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The value representing this object.</param>
|
||||
private FileSystemId(Guid value) : base(value)
|
||||
{
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FileSystemId"/> class.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="FileSystemId"/> instance.</returns>
|
||||
public static FileSystemId CreateUnique()
|
||||
{
|
||||
return new FileSystemId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FileSystemId"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The value used to create the <see cref="FileSystemId"/> instance.</param>
|
||||
/// <returns>The created <see cref="FileSystemId"/> instance.</returns>
|
||||
public static FileSystemId Create(Guid value)
|
||||
{
|
||||
return new FileSystemId(value);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Value;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+56
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object uniquely identifying file system items.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Path}")]
|
||||
public sealed class FileSystemPathId : ValueObject
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the value of this object.
|
||||
/// </summary>
|
||||
public string Path { get; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemPathId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file system item.</param>
|
||||
private FileSystemPathId(string path)
|
||||
{
|
||||
Path = path;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <inheritdoc />
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FileSystemPathId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file system item.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="FileSystemPathId"/> or an error message.
|
||||
/// </returns>
|
||||
public static ErrorOr<FileSystemPathId> Create(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
return Errors.FileManagement.InvalidPathError;
|
||||
return new FileSystemPathId(path);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+56
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Value object uniquely identifying path segments.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Name}")]
|
||||
public class PathSegment : ValueObject
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the name of the path segment.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value indicating if the current path segment is a file system directory or not.
|
||||
/// </summary>
|
||||
public bool IsDirectory { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value indicating if the current path segment is a file system drive or not.
|
||||
/// </summary>
|
||||
public bool IsDrive { get; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PathSegment"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the path segment.</param>
|
||||
/// <param name="isDirectory">Value indicating if the current path segment is a file system directory or not.</param>
|
||||
/// <param name="isDrive">Value indicating if the current path segment is a file system drive or not.</param>
|
||||
public PathSegment(string name, bool isDirectory, bool isDrive)
|
||||
{
|
||||
Name = name;
|
||||
IsDirectory = isDirectory;
|
||||
IsDrive = isDrive;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <inheritdoc/>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Name;
|
||||
yield return IsDirectory;
|
||||
yield return IsDrive;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+5
-2
@@ -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
|
||||
/// <summary>
|
||||
/// Value Object for the information about a media stream.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{StreamId}")]
|
||||
public class StreamInfo : ValueObject
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
@@ -100,7 +103,7 @@ public class StreamInfo : ValueObject
|
||||
/// <param name="sampleRate">The sample rate of the stream (for audio).</param>
|
||||
/// <param name="channels">The number of channels (for audio).</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="StreamInfo"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="StreamInfo"/>, or an error message.
|
||||
/// </returns>
|
||||
public static ErrorOr<StreamInfo> Create(
|
||||
string streamId,
|
||||
|
||||
+49
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Value object for file system thumbnails.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Type}")]
|
||||
public class Thumbnail : ValueObject
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
/// <summary>
|
||||
/// Gets the type of the image represented by this thumbnail.
|
||||
/// </summary>
|
||||
public ImageType Type { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bytes of the image represented by this thumbnail.
|
||||
/// </summary>
|
||||
public byte[] Bytes { get; }
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Thumbnail"/> class.
|
||||
/// </summary>
|
||||
/// <param name="type">The type of the image represented by this thumbnail.</param>
|
||||
/// <param name="bytes">The bytes of the image represented by this thumbnail.</param>
|
||||
public Thumbnail(ImageType type, byte[] bytes)
|
||||
{
|
||||
Type = type;
|
||||
Bytes = bytes;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <inheritdoc/>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Type;
|
||||
yield return Bytes;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>..\..\bin\</BaseOutputPath>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
@@ -14,6 +14,15 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ErrorOr" Version="2.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
|
||||
<PackageReference Include="System.IO.Abstractions" Version="21.0.29" />
|
||||
<PackageReference Include="System.IO.FileSystem.AccessControl" Version="5.0.0" />
|
||||
<PackageReference Include="Mono.Posix.NETStandard" Version="5.20.1-preview" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Core\Aggregates\FileManagement\FileManagementAggregate\Entities\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in new issue
Block a user