Implements directory browser dialog, part 1: file system treeview

This commit is contained in:
BinaryAlley committed 2024-09-15 13:07:53 +03:00
1 parent 4a53348013
commit 4e4ecbbfca
318 files changed
+6012 -1184

No files matched your search

@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.FileManagement.Directories.Queries;
/// <summary>
/// Query for retrieving the list of directories at a path.
/// </summary>
/// <param name="Path">The path for which to retrieve the list of directories.</param>
public record GetDirectoriesQuery(string Path) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster;
using MapsterMapper;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Directories.Queries;
/// <summary>
/// Handler for the query to get all directories.
/// </summary>
public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IDirectoryService _directoryService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandler"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
public GetDirectoriesQueryHandler(IDirectoryService directoryService)
{
_directoryService = directoryService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the list of directories at the specified path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
}
#endregion
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileManagement.Directories.Queries;
/// <summary>
/// Validates the needed validation rules for <see cref="GetDirectoriesQuery"/>.
/// </summary>
public class GetDirectoriesQueryValidator : AbstractValidator<GetDirectoriesQuery>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryValidator"/> class.
/// </summary>
public GetDirectoriesQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code);
}
#endregion
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.FileManagement.Directories.Queries;
/// <summary>
/// Query for retrieving the tree of directories of a path.
/// </summary>
/// <param name="Path">The path for which to retrieve the tree of directories.</param>
public record GetDirectoryTreeQuery(string Path) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
@@ -0,0 +1,179 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Mapster;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Directories.Queries;
/// <summary>
/// Handler for the query to get a directory tree.
/// </summary>
public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IDirectoryService _directoryService;
private readonly IFileService _fileService;
private readonly IPathService _pathService;
private readonly IDriveService _driveService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryHandler"/> class.
/// </summary>
/// <param name="driveService">Injected service for handling file system drives.</param>
/// <param name="directoryService">Injected service for handling directories.</param>
/// <param name="fileService">Injected service for handling files.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
public GetDirectoryTreeQueryHandler(IDriveService driveService, IDirectoryService directoryService, IFileService fileService, IPathService pathService)
{
_directoryService = directoryService;
_fileService = fileService;
_pathService = pathService;
_driveService = driveService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the tree of expanded directories leading up to the requested path, with the additional list of drives, and children of the last child directory.
/// </summary>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDirectoryTreeQuery request, CancellationToken cancellationToken)
{
List<FileSystemTreeNodeResponse> result = [];
// retrieve the list of drives
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> getDrivesResult = GetDrives();
if (getDrivesResult.IsError)
return getDrivesResult.Errors;
result.AddRange(getDrivesResult.Value);
ErrorOr<IEnumerable<PathSegment>> pathPartsResults = _pathService.ParsePath(request.Path);
if (pathPartsResults.IsError)
return pathPartsResults.Errors;
List<PathSegment> pathParts = pathPartsResults.Value.ToList();
string currentPath = pathParts[0].Name;
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> buildDirectoryTreeResult = BuildDirectoryTree(result, pathParts, out FileSystemTreeNodeResponse currentNode);
if (buildDirectoryTreeResult.IsError)
return buildDirectoryTreeResult.Errors;
// add subdirectories of the last directory node
ErrorOr<Success> loadChildrenResult = LoadChildren(currentNode);
if (loadChildrenResult.IsError)
return loadChildrenResult.Errors;
return await ValueTask.FromResult(result);
}
/// <summary>
/// Gets the root drives (on Windows), or an empty list on Unix-based systems.
/// </summary>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing a list of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
/// </returns>
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> GetDrives()
{
ErrorOr<IEnumerable<FileSystemItem>> driveResult = _driveService.GetDrives();
if (driveResult.IsError)
return driveResult.Errors;
return ErrorOrFactory.From(driveResult.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>());
}
/// <summary>
/// Builds the tree of directories based on the parsed path parts.
/// </summary>
/// <param name="drives">The list of available drives.</param>
/// <param name="pathParts">The list of parsed path segments (directories).</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing a list of <see cref="FileSystemTreeNodeResponse"/> representing the directory tree, or an error message.
/// </returns>
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> BuildDirectoryTree(List<FileSystemTreeNodeResponse> drives, List<PathSegment> pathParts, out FileSystemTreeNodeResponse currentNode)
{
// find the root drive that matches the first part of the path
FileSystemTreeNodeResponse drive = drives.First(d => d.Name.Contains(pathParts[0].Name));
drive.IsExpanded = true;
currentNode = drive;
string currentPath = pathParts[0].Name;
// traverse the remaining path parts to build the tree structure
for (int i = 1; i < pathParts.Count; i++)
{
ErrorOr<string> combinedPathResult = _pathService.CombinePath(currentPath, pathParts[i].Name);
if (combinedPathResult.IsError)
return combinedPathResult.Errors;
currentPath = combinedPathResult.Value;
// create a new node for the directory and add it as a child of the current node
FileSystemTreeNodeResponse newNode = new FileSystemTreeNodeResponse
{
Path = currentPath,
Name = pathParts[i].Name,
ItemType = FileSystemItemType.Directory,
IsExpanded = true
};
currentNode.Children.Add(newNode);
currentNode = newNode; // move to the new node
}
return new List<FileSystemTreeNodeResponse> { drive };
}
/// <summary>
/// Loads the child directories and files of the specified directory node.
/// </summary>
/// <param name="node">The directory node to load children for.</param>
/// <returns>A result indicating a successful operation, or an error message.</returns>
private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node)
{
// get subdirectories under the current node's path
ErrorOr<IEnumerable<Directory>> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path);
if (subDirectoriesResult.IsError)
return subDirectoriesResult.Errors;
// add each subdirectory as a child node of the current directory
foreach (Directory subDirectory in subDirectoriesResult.Value)
{
FileSystemTreeNodeResponse subDirNode = new FileSystemTreeNodeResponse
{
Name = subDirectory.Name,
Path = subDirectory.Id.Path,
ItemType = FileSystemItemType.Directory,
IsExpanded = false,
ChildrenLoaded = false
};
node.Children.Add(subDirNode);
}
// get files under the current node's path
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(node.Path);
if (filesResult.IsError)
return filesResult.Errors;
// add each file as a child node of the current directory
foreach (File file in filesResult.Value)
{
FileSystemTreeNodeResponse fileNode = new FileSystemTreeNodeResponse
{
Name = file.Name,
Path = file.Id.Path,
ItemType = FileSystemItemType.File,
IsExpanded = false,
ChildrenLoaded = true
};
node.Children.Add(fileNode);
}
node.ChildrenLoaded = true;
return Result.Success;
}
#endregion
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileManagement.Directories.Queries;
/// <summary>
/// Validates the needed validation rules for <see cref="GetDirectoryTreeQuery"/>.
/// </summary>
public class GetDirectoryTreeQueryValidator : AbstractValidator<GetDirectoryTreeQuery>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryValidator"/> class.
/// </summary>
public GetDirectoryTreeQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code);
}
#endregion
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.FileManagement.Drives.Queries;
/// <summary>
/// Query for retrieving the list of drives.
/// </summary>
public record GetDrivesQuery() : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Drives.Queries;
/// <summary>
/// Handler for the query to get all drives.
/// </summary>
public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IDriveService _driveService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesQueryHandler"/> class.
/// </summary>
/// <param name="driveService">Injected service for handling file system drives.</param>
public GetDrivesQueryHandler(IDriveService driveService)
{
_driveService = driveService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the list of file system drives.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemItem>> result = _driveService.GetDrives();
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
}
#endregion
}
@@ -0,0 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
#endregion
namespace Lumina.Application.Core.FileManagement.FileSystem.Queries;
/// <summary>
/// Query for retrieving the file system type.
/// </summary>
public record GetFileSystemQuery() : IRequest<FileSystemTypeResponse>;
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.FileSystem.Queries;
/// <summary>
/// Handler for the query to get the file system type.
/// </summary>
public class GetFileSystemQueryHandler : IRequestHandler<GetFileSystemQuery, FileSystemTypeResponse>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPlatformContext _platformContext;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetFileSystemQueryHandler"/> class.
/// </summary>
/// <param name="platformContextManager">Injected service for managing platform contexts.</param>
public GetFileSystemQueryHandler(IPlatformContextManager platformContextManager)
{
_platformContext = platformContextManager.GetCurrentContext();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the type of the file system.
/// </summary>
/// <param name="request">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The type of the file system.</returns>
public ValueTask<FileSystemTypeResponse> Handle(GetFileSystemQuery request, CancellationToken cancellationToken)
{
return ValueTask.FromResult(new FileSystemTypeResponse(_platformContext.Platform));
}
#endregion
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.FileManagement.Files.Queries;
/// <summary>
/// Query for retrieving the list of files at a path.
/// </summary>
/// <param name="Path">The path for which to retrieve the list of files.</param>
public record GetFilesQuery(string Path) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Files.Queries;
/// <summary>
/// Handler for the query to get all files.
/// </summary>
public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFileService _fileService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryHandler"/> class.
/// </summary>
/// <param name="fileService">Injected service for handling files.</param>
public GetFilesQueryHandler(IFileService fileService)
{
_fileService = fileService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the list of files at the specified path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="FileSystemTreeNodeResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
}
#endregion
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileManagement.Files.Queries;
/// <summary>
/// Validates the needed validation rules for <see cref="GetFilesQuery"/>.
/// </summary>
public class GetFilesQueryValidator : AbstractValidator<GetFilesQuery>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryValidator"/> class.
/// </summary>
public GetFilesQueryValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code);
}
#endregion
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Commands;
/// <summary>
/// Command for combining two file system path.
/// </summary>
/// <param name="OriginalPath">The path to combine to.</param>
/// <param name="NewPath">The path to combine with.</param>
public record CombinePathCommand(
string OriginalPath, string NewPath
) : IRequest<ErrorOr<PathSegmentResponse>>;
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Commands;
/// <summary>
/// Handler for the command to split a file system path.
/// </summary>
public class CombinePathCommandHandler : IRequestHandler<CombinePathCommand, ErrorOr<PathSegmentResponse>>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _pathService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for handling file system paths.</param>
public CombinePathCommandHandler(IPathService pathService)
{
_pathService = pathService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Combines two file system paths.
/// </summary>
/// <param name="request">The command containing the requested paths.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="PathSegmentResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(CombinePathCommand request, CancellationToken cancellationToken)
{
ErrorOr<string> result = _pathService.CombinePath(request.OriginalPath, request.NewPath);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors));
}
#endregion
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Commands;
/// <summary>
/// Validates the needed validation rules for <see cref="CombinePathCommand"/>.
/// </summary>
public class CombinePathCommandValidator : AbstractValidator<CombinePathCommand>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathCommandValidator"/> class.
/// </summary>
public CombinePathCommandValidator()
{
RuleFor(x => x.OriginalPath).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code);
RuleFor(x => x.NewPath).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code);
}
#endregion
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Commands;
/// <summary>
/// Command for splitting a file system path.
/// </summary>
/// <param name="Path">The path to split.</param>
public record SplitPathCommand(
string Path
) : IRequest<ErrorOr<IEnumerable<PathSegmentResponse>>>;
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Mapster;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Commands;
/// <summary>
/// Handler for the command to split a file system path.
/// </summary>
public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr<IEnumerable<PathSegmentResponse>>>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _pathService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for handling file system paths.</param>
public SplitPathCommandHandler(IPathService pathService)
{
_pathService = pathService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the path components of the specified path.
/// </summary>
/// <param name="request">The command containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PathSegmentResponse"/>, or an error message.
/// </returns>
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegment>> result = _pathService.ParsePath(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<PathSegmentResponse>>()), errors => errors));
}
#endregion
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Commands;
/// <summary>
/// Validates the needed validation rules for <see cref="SplitPathCommand"/>.
/// </summary>
public class SplitPathCommandValidator : AbstractValidator<SplitPathCommand>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandValidator"/> class.
/// </summary>
public SplitPathCommandValidator()
{
RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code);
}
#endregion
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Queries;
/// <summary>
/// Query for retrieving the root of a path.
/// </summary>
/// <param name="Path">The path for which to get the path root.</param>
public record GetPathRootQuery(string Path) : IRequest<ErrorOr<PathSegmentResponse>>;
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Mapster;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Queries;
/// <summary>
/// Handler for the query to get the root of a file system path.
/// </summary>
public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr<PathSegmentResponse>>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _pathService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for managing file system paths.</param>
public GetPathRootQueryHandler(IPathService pathService)
{
_pathService = pathService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the root of the specified file system path.
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The root of the specified path.</returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken)
{
ErrorOr<PathSegment> result = _pathService.GetPathRoot(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<PathSegmentResponse>()), errors => errors));
}
#endregion
}
@@ -0,0 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.FileManagement;
using Mediator;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Queries;
/// <summary>
/// Query for retrieving the file system path separator.
/// </summary>
public record GetPathSeparatorQuery() : IRequest<PathSeparatorResponse>;
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.FileManagement.Paths.Queries;
/// <summary>
/// Handler for the query to get the path separator character of a file system path.
/// </summary>
public class GetPathSeparatorQueryHandler : IRequestHandler<GetPathSeparatorQuery, PathSeparatorResponse>
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _pathService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorQueryHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for managing file system paths.</param>
public GetPathSeparatorQueryHandler(IPathService pathService)
{
_pathService = pathService;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Gets the path separator character of a file system path.
/// </summary>
/// <param name="request">The query containing the request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The file system path separator character.</returns>
public ValueTask<PathSeparatorResponse> Handle(GetPathSeparatorQuery request, CancellationToken cancellationToken)
{
return ValueTask.FromResult(new PathSeparatorResponse(_pathService.PathSeparator.ToString()));
}
#endregion
}
@@ -1,10 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.Models.Books;
using Lumina.Application.Common.Models.Contributors;
using Lumina.Domain.Common.Enums;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Contracts.Models.MediaContributors;
using Lumina.Contracts.Models.WrittenContentLibrary;
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Mediator;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
@@ -12,12 +14,29 @@ namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Comma
/// <summary>
/// Command for adding a book.
/// </summary>
/// <param name="Metadata">Written content metadata of the book.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback), if applicable.</param>
/// <param name="Edition">The edition of the book, if applicable.</param>
/// <param name="VolumeNumber">The volume or book number in the series, if applicable.</param>
/// <param name="Series">The series name, if the book is part of a series.</param>
/// <param name="ASIN">The ASIN (Amazon Standard Identification Number) of the book, if applicable.</param>
/// <param name="GoodreadsId">The Goodreads ID of the book, if applicable.</param>
/// <param name="LCCN">The Library of Congress Control Number (LCCN) of the book, if applicable.</param>
/// <param name="OCLCNumber">The OCLC Number (WorldCat identifier) of the book, if applicable.</param>
/// <param name="OpenLibraryId">The Open Library ID of the book, if applicable.</param>
/// <param name="LibraryThingId">The LibraryThing ID of the book, if applicable.</param>
/// <param name="GoogleBooksId">The Google Books ID of the book, if applicable.</param>
/// <param name="BarnesAndNobleId">The Barnes & Noble ID of the book, if applicable.</param>
/// <param name="AppleBooksId">The Apple Books ID of the book, if applicable.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
public record AddBookCommand(
WrittenContentMetadataDto Metadata,
WrittenContentMetadataModel Metadata,
BookFormat? Format,
string? Edition,
int? VolumeNumber,
BookSeriesDto? Series,
BookSeriesModel? Series,
string? ASIN,
string? GoodreadsId,
string? LCCN,
@@ -27,7 +46,7 @@ public record AddBookCommand(
string? GoogleBooksId,
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto> ISBNs,
List<MediaContributorDto> Contributors,
List<BookRatingDto> Ratings
List<IsbnModel> ISBNs,
List<MediaContributorModel> Contributors,
List<BookRatingModel> Ratings
) : IRequest<ErrorOr<Book>>;
@@ -2,8 +2,8 @@
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Models.Books;
using Lumina.Domain.Common.Enums;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects;
@@ -12,6 +12,11 @@ using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.E
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
using MapsterMapper;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
@@ -46,7 +51,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<Book>> Handle(AddBookCommand request, CancellationToken cancellationToken)
{
@@ -162,11 +167,11 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
return createBookResult.Errors;
var bookRepository = _unitOfWork.GetRepository<IBookRepository>();
var persistenceBook = _mapper.Map<BookDto>(createBookResult.Value);
var insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken);
var persistenceBook = _mapper.Map<BookModel>(createBookResult.Value);
var insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsError)
return insertBookResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return createBookResult.Value;
}
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
@@ -2,6 +2,7 @@
using ErrorOr;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Mediator;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries;
@@ -3,8 +3,11 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using MapsterMapper;
using Mapster;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries;
@@ -16,7 +19,6 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IUnitOfWork _unitOfWork;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -24,11 +26,9 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
/// Initializes a new instance of the <see cref="GetBooksQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="mapper">Injected service for mapping objects.</param>
public GetBooksQueryHandler(IUnitOfWork unitOfWork, IMapper mapper)
public GetBooksQueryHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
}
#endregion
@@ -39,15 +39,13 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{T}"/> containing either a collection of <see cref="Book"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="Book"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<Book>>> Handle(GetBooksQuery request, CancellationToken cancellationToken)
{
var bookRepository = _unitOfWork.GetRepository<IBookRepository>();
var getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getBooksResult.IsError)
return getBooksResult.Errors;
return ErrorOrFactory.From(getBooksResult.Value.Select(book => _mapper.Map<Book>(book)));
return getBooksResult.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<Book>>()), errors => errors);
}
#endregion
}
}