mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Implements directory browser dialog, part 6: hidden file system items toggle
This commit is contained in:
1 parent
cd44f11d9e
commit
debad9ef74
74 files changed
+596
-427
No files matched your search
+15
-29
@@ -13,36 +13,16 @@ end_of_line = lf
|
||||
insert_final_newline = true
|
||||
dotnet_style_operator_placement_when_wrapping = end_of_line
|
||||
dotnet_style_coalesce_expression = true:suggestion
|
||||
dotnet_style_explicit_tuple_names = true:suggestion
|
||||
dotnet_style_prefer_simplified_interpolation = true:suggestion
|
||||
dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion
|
||||
dotnet_style_namespace_match_folder = true:suggestion
|
||||
dotnet_style_allow_multiple_blank_lines_experimental = true:silent
|
||||
dotnet_style_allow_statement_immediately_after_block_experimental = true:silent
|
||||
dotnet_style_null_propagation = true:warning
|
||||
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
|
||||
dotnet_style_prefer_auto_properties = true:suggestion
|
||||
dotnet_style_object_initializer = true:suggestion
|
||||
dotnet_style_collection_initializer = true:suggestion
|
||||
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
|
||||
dotnet_style_prefer_conditional_expression_over_return = true:silent
|
||||
dotnet_style_explicit_tuple_names = true:suggestion
|
||||
dotnet_style_prefer_inferred_tuple_names = true:suggestion
|
||||
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
|
||||
dotnet_style_prefer_compound_assignment = true:suggestion
|
||||
dotnet_style_prefer_simplified_interpolation = true:suggestion
|
||||
dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion
|
||||
dotnet_style_namespace_match_folder = true:suggestion
|
||||
dotnet_style_prefer_simplified_boolean_expressions = true:warning
|
||||
dotnet_style_readonly_field = true:error
|
||||
dotnet_style_predefined_type_for_locals_parameters_members = true:warning
|
||||
dotnet_style_predefined_type_for_member_access = true:warning
|
||||
dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning
|
||||
dotnet_style_allow_multiple_blank_lines_experimental = true:silent
|
||||
dotnet_style_allow_statement_immediately_after_block_experimental = true:silent
|
||||
dotnet_code_quality_unused_parameters = all:warning
|
||||
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
|
||||
dotnet_style_qualification_for_field = false:silent
|
||||
dotnet_style_qualification_for_property = false:silent
|
||||
dotnet_style_qualification_for_method = false:silent
|
||||
dotnet_style_qualification_for_event = false:silent
|
||||
|
||||
# Development files
|
||||
[*.{cs,csx,cshtml,csproj,razor,sln,props,targets,json,md,yml,gitignore,}]
|
||||
@@ -89,13 +69,13 @@ dotnet_style_prefer_conditional_expression_over_return = true:silent
|
||||
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
|
||||
dotnet_style_prefer_inferred_tuple_names = true:suggestion
|
||||
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
|
||||
dotnet_style_prefer_simplified_boolean_expressions = true:warning
|
||||
dotnet_style_prefer_simplified_boolean_expressions = true:refactoring
|
||||
|
||||
# Field preferences
|
||||
dotnet_style_readonly_field = true:error
|
||||
|
||||
# Parameter preferences
|
||||
dotnet_code_quality_unused_parameters = all:warning
|
||||
dotnet_code_quality_unused_parameters = all:suggestion
|
||||
|
||||
# Strings
|
||||
csharp_style_prefer_string_interpolation = true:suggestion
|
||||
@@ -304,7 +284,7 @@ dotnet_naming_rule.readonly_fields_should_be_underscore_camel_case.severity = wa
|
||||
|
||||
# Additional C# style preferences
|
||||
csharp_style_namespace_declarations = file_scoped:error # no need for an extra indentation for namespace, when a single type per file rule is enforced.
|
||||
csharp_style_prefer_method_group_conversion = true:error # more explicit style is preferred
|
||||
csharp_style_prefer_method_group_conversion = false:none # more explicit style is preferred
|
||||
csharp_style_prefer_top_level_statements = false:error # this abomination needs to die!
|
||||
csharp_style_prefer_primary_constructors = false:error # primary constructors don't inject into readonly fields, immutability is much more important than conciseness
|
||||
csharp_style_prefer_null_check_over_type_check = true:suggestion
|
||||
@@ -324,3 +304,9 @@ csharp_style_prefer_switch_expression = true:suggestion
|
||||
csharp_style_prefer_pattern_matching = true:silent
|
||||
csharp_style_prefer_not_pattern = true:suggestion
|
||||
csharp_style_prefer_extended_property_pattern = true:suggestion
|
||||
|
||||
# JS
|
||||
dotnet_diagnostic.TS6385.severity = none
|
||||
|
||||
# IDE0001: Simplify Names
|
||||
dotnet_diagnostic.IDE0001.severity = refactoring
|
||||
@@ -2,6 +2,8 @@
|
||||
using ErrorOr;
|
||||
using FluentValidation;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -49,7 +51,7 @@ public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TReques
|
||||
if (validationResult.IsValid)
|
||||
return await next(request, cancellationToken).ConfigureAwait(false);
|
||||
// after the command handler is executed
|
||||
System.Collections.Generic.List<Error> errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage));
|
||||
List<Error> errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage));
|
||||
// the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic
|
||||
// this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!)
|
||||
return (dynamic)errors;
|
||||
|
||||
@@ -23,7 +23,10 @@ public static class ApplicationLayerServices
|
||||
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
|
||||
{
|
||||
// register Mediator
|
||||
services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped);
|
||||
services.AddMediator(options =>
|
||||
{
|
||||
options.ServiceLifetime = ServiceLifetime.Scoped;
|
||||
});
|
||||
|
||||
// register the validation behavior
|
||||
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
|
||||
|
||||
+2
-1
@@ -11,4 +11,5 @@ namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirector
|
||||
/// 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<DirectoryResponse>>>;
|
||||
/// <param name="IncludeHiddenElements">Whether to include hidden directories or not.</param>
|
||||
public record GetDirectoriesQuery(string Path, bool IncludeHiddenElements) : IRequest<ErrorOr<IEnumerable<DirectoryResponse>>>;
|
||||
+1
-1
@@ -43,7 +43,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, E
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path);
|
||||
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<DirectoryResponse>>()), errors => errors));
|
||||
}
|
||||
#endregion
|
||||
|
||||
+3
-2
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Mediator;
|
||||
@@ -12,4 +12,5 @@ namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirector
|
||||
/// </summary>
|
||||
/// <param name="Path">The path for which to retrieve the tree of directories.</param>
|
||||
/// <param name="IncludeFiles">Whether to include files in the directory tree or not.</param>
|
||||
public record GetDirectoryTreeQuery(string Path, bool IncludeFiles) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
/// <param name="IncludeHiddenElements">Whether to include hidden files and directories or not.</param>
|
||||
public record GetDirectoryTreeQuery(string Path, bool IncludeFiles, bool IncludeHiddenElements) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
+13
-12
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
@@ -66,15 +66,16 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
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, request.IncludeFiles);
|
||||
return loadChildrenResult.IsError ? (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)loadChildrenResult.Errors : (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)await ValueTask.FromResult(result);
|
||||
ErrorOr<Success> loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles, request.IncludeHiddenElements);
|
||||
if (loadChildrenResult.IsError)
|
||||
return loadChildrenResult.Errors;
|
||||
return await ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -86,9 +87,9 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> GetDrives()
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemItem>> driveResult = _driveService.GetDrives();
|
||||
return driveResult.IsError
|
||||
? (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)driveResult.Errors
|
||||
: ErrorOrFactory.From(driveResult.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>());
|
||||
if (driveResult.IsError)
|
||||
return driveResult.Errors;
|
||||
return ErrorOrFactory.From(driveResult.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -102,7 +103,7 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
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));
|
||||
FileSystemTreeNodeResponse drive = drives.First(drive => drive.Name.Contains(pathParts[0].Name));
|
||||
drive.IsExpanded = true;
|
||||
currentNode = drive;
|
||||
string currentPath = pathParts[0].Name;
|
||||
@@ -135,10 +136,10 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
/// <param name="node">The directory node to load children for.</param>
|
||||
/// <param name="includeFiles">Whether to include files in the directories or not.</param>
|
||||
/// <returns>A result indicating a successful operation, or an error message.</returns>
|
||||
private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles)
|
||||
private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles, bool includeHiddenElements)
|
||||
{
|
||||
// get subdirectories under the current node's path
|
||||
ErrorOr<IEnumerable<Directory>> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path);
|
||||
ErrorOr<IEnumerable<Directory>> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path, includeHiddenElements);
|
||||
if (subDirectoriesResult.IsError)
|
||||
return subDirectoriesResult.Errors;
|
||||
// add each subdirectory as a child node of the current directory
|
||||
@@ -157,7 +158,7 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
if (includeFiles)
|
||||
{
|
||||
// get files under the current node's path
|
||||
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(node.Path);
|
||||
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(node.Path, includeHiddenElements);
|
||||
if (filesResult.IsError)
|
||||
return filesResult.Errors;
|
||||
// add each file as a child node of the current directory
|
||||
@@ -178,4 +179,4 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
return Result.Success;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -11,4 +11,5 @@ namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDire
|
||||
/// 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 GetTreeDirectoriesQuery(string Path) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
/// <param name="IncludeHiddenElements">Whether to include hidden directories or not.</param>
|
||||
public record GetTreeDirectoriesQuery(string Path, bool IncludeHiddenElements) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
+1
-1
@@ -43,7 +43,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler<GetTreeDirectories
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path);
|
||||
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -11,4 +11,5 @@ namespace Lumina.Application.Core.FileManagement.Files.Queries.GetFiles;
|
||||
/// 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<FileResponse>>>;
|
||||
/// <param name="IncludeHiddenElements">Whether to include hidden files and directories or not.</param>
|
||||
public record GetFilesQuery(string Path, bool IncludeHiddenElements) : IRequest<ErrorOr<IEnumerable<FileResponse>>>;
|
||||
+1
-1
@@ -43,7 +43,7 @@ public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path);
|
||||
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileResponse>>()), errors => errors));
|
||||
}
|
||||
#endregion
|
||||
|
||||
+2
-1
@@ -11,4 +11,5 @@ namespace Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles;
|
||||
/// 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 GetTreeFilesQuery(string Path) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
/// <param name="IncludeHiddenElements">Whether to include hidden files and directories or not.</param>
|
||||
public record GetTreeFilesQuery(string Path, bool IncludeHiddenElements) : IRequest<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>;
|
||||
+1
-1
@@ -43,7 +43,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, Error
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path);
|
||||
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
|
||||
}
|
||||
#endregion
|
||||
|
||||
+3
-2
@@ -3,6 +3,7 @@ using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Contracts.Enums.BookLibrary;
|
||||
using Lumina.Contracts.Models.MediaContributors;
|
||||
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
@@ -57,7 +58,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
|
||||
{
|
||||
// TODO: update Api.Book.md documentation when the functionality is fully implemented
|
||||
List<MediaContributorId> contributorIds = [];
|
||||
foreach (Contracts.Models.MediaContributors.MediaContributorModel mediaContributor in request.Contributors)
|
||||
foreach (MediaContributorModel mediaContributor in request.Contributors)
|
||||
{
|
||||
// TODO: add logic to search the media contributors repository for existing contributors, based on the provided names
|
||||
}
|
||||
@@ -176,4 +177,4 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
|
||||
return createBookResult.Value;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -1,7 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
|
||||
using Mapster;
|
||||
using Mediator;
|
||||
@@ -44,8 +45,8 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
|
||||
public async ValueTask<ErrorOr<IEnumerable<Book>>> Handle(GetBooksQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
|
||||
ErrorOr<IEnumerable<Contracts.Models.WrittenContentLibrary.BookLibrary.BookModel>> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<IEnumerable<BookModel>> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
return getBooksResult.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<Book>>()), errors => errors);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.DataAccess.Core.Repositories.Common.Factory;
|
||||
@@ -30,7 +30,10 @@ public static class DataAccessLayerServices
|
||||
string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
||||
if (!Directory.Exists(basePath))
|
||||
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
|
||||
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}"));
|
||||
services.AddDbContext<LuminaDbContext>(options =>
|
||||
{
|
||||
options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}");
|
||||
});
|
||||
services.AddScoped<IUnitOfWork, UnitOfWork>();
|
||||
|
||||
Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes();
|
||||
@@ -55,4 +58,4 @@ public static class DataAccessLayerServices
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Contracts.Models.Common;
|
||||
@@ -43,7 +43,7 @@ internal sealed class BookRepository : IBookRepository
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
|
||||
public async Task<ErrorOr<Created>> InsertAsync(BookModel book, CancellationToken cancellationToken)
|
||||
{
|
||||
bool jobExists = await _luminaDbContext.Books.AnyAsync(_book => _book.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
bool jobExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (jobExists)
|
||||
return Errors.WrittenContent.BookAlreadyExists;
|
||||
|
||||
@@ -78,4 +78,4 @@ internal sealed class BookRepository : IBookRepository
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Models.Common;
|
||||
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -39,9 +40,8 @@ public class LuminaDbContext : DbContext
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
// find all the entity configurations in the assembly and apply them
|
||||
modelBuilder
|
||||
.Ignore<List<IDomainEvent>>()
|
||||
.ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly);
|
||||
modelBuilder.Ignore<List<IDomainEvent>>()
|
||||
.ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly);
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
@@ -53,10 +53,10 @@ public class LuminaDbContext : DbContext
|
||||
public override int SaveChanges()
|
||||
{
|
||||
// get all the entity entries that are either added or modified
|
||||
IEnumerable<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry> entries = ChangeTracker.Entries()
|
||||
.Where(e => e.Entity is IStorageEntity &&
|
||||
(e.State is EntityState.Added or EntityState.Modified));
|
||||
foreach (Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry? entityEntry in entries)
|
||||
IEnumerable<EntityEntry> entries = ChangeTracker.Entries()
|
||||
.Where(e => e.Entity is IStorageEntity &&
|
||||
(e.State is EntityState.Added or EntityState.Modified));
|
||||
foreach (EntityEntry? entityEntry in entries)
|
||||
{
|
||||
// if the entity is in Added state, set the Created property to the current date and time
|
||||
if (entityEntry.State == EntityState.Added)
|
||||
@@ -68,4 +68,4 @@ public class LuminaDbContext : DbContext
|
||||
return base.SaveChanges();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,9 @@ public class Genre : ValueObject
|
||||
/// </returns>
|
||||
public static ErrorOr<Genre> Create(string name)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(name) ? (ErrorOr<Genre>)Errors.Errors.Metadata.GenreNameCannotBeEmpty : (ErrorOr<Genre>)new Genre(name);
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return Errors.Errors.Metadata.GenreNameCannotBeEmpty;
|
||||
return new Genre(name);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -59,4 +61,4 @@ public class Genre : ValueObject
|
||||
return Name;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -58,11 +58,13 @@ public class LanguageInfo : ValueObject
|
||||
/// </returns>
|
||||
public static ErrorOr<LanguageInfo> Create(string languageCode, string languageName, Optional<string> nativeName)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(languageCode)
|
||||
? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.LanguageCodeCannotBeEmpty
|
||||
: string.IsNullOrWhiteSpace(languageName)
|
||||
? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.LanguageNameCannotBeEmpty
|
||||
: languageCode.Length != 2 ? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.InvalidIsoCode : (ErrorOr<LanguageInfo>)new LanguageInfo(languageCode, languageName, nativeName);
|
||||
if (string.IsNullOrWhiteSpace(languageCode))
|
||||
return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty;
|
||||
if (string.IsNullOrWhiteSpace(languageName))
|
||||
return Errors.Errors.Metadata.LanguageNameCannotBeEmpty;
|
||||
if (languageCode.Length != 2)
|
||||
return Errors.Errors.Metadata.InvalidIsoCode;
|
||||
return new LanguageInfo(languageCode, languageName, nativeName);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -82,4 +84,4 @@ public class LanguageInfo : ValueObject
|
||||
return $"{LanguageCode} - {LanguageName}";
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -96,15 +96,15 @@ public class ReleaseInfo : ValueObject
|
||||
Optional<string> releaseCountry,
|
||||
Optional<string> releaseVersion)
|
||||
{
|
||||
return originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value
|
||||
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch
|
||||
: reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value
|
||||
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch
|
||||
: originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value
|
||||
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate
|
||||
: originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value
|
||||
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear
|
||||
: (ErrorOr<ReleaseInfo>)new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion);
|
||||
if (originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value)
|
||||
return Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch;
|
||||
if (reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value)
|
||||
return Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch;
|
||||
if (originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value)
|
||||
return Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate;
|
||||
if (originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value)
|
||||
return Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear;
|
||||
return new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -118,4 +118,4 @@ public class ReleaseInfo : ValueObject
|
||||
yield return ReleaseVersion;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,9 @@ public class Tag : ValueObject
|
||||
/// </returns>
|
||||
public static ErrorOr<Tag> Create(string name)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(name) ? (ErrorOr<Tag>)Errors.Errors.Metadata.TagNameCannotBeEmpty : (ErrorOr<Tag>)new Tag(name);
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return Errors.Errors.Metadata.TagNameCannotBeEmpty;
|
||||
return new Tag(name);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -59,4 +61,4 @@ public class Tag : ValueObject
|
||||
return Name;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -80,7 +80,9 @@ public sealed class Directory : FileSystemItem
|
||||
dateCreated,
|
||||
dateModified);
|
||||
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
|
||||
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : (ErrorOr<Directory>)newDirectory;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return newDirectory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -107,7 +109,9 @@ public sealed class Directory : FileSystemItem
|
||||
dateCreated,
|
||||
dateModified);
|
||||
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
|
||||
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : (ErrorOr<Directory>)newDirectory;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return newDirectory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -143,4 +147,4 @@ public sealed class Directory : FileSystemItem
|
||||
return Result.Updated;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
@@ -81,7 +81,9 @@ public sealed class File : FileSystemItem
|
||||
dateModified,
|
||||
size);
|
||||
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
|
||||
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : (ErrorOr<File>)newFile;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return newFile;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -112,7 +114,9 @@ public sealed class File : FileSystemItem
|
||||
dateModified,
|
||||
size);
|
||||
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
|
||||
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : (ErrorOr<File>)newFile;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return newFile;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -150,4 +154,4 @@ public sealed class File : FileSystemItem
|
||||
return Result.Updated;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
@@ -55,7 +55,9 @@ public sealed class UnixRootItem : FileSystemItem
|
||||
createPathResult.Value,
|
||||
PATH);
|
||||
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
|
||||
return setStatusResult.IsError ? (ErrorOr<UnixRootItem>)setStatusResult.Errors : (ErrorOr<UnixRootItem>)newRoot;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return newRoot;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
@@ -59,7 +59,9 @@ public sealed class WindowsRootItem : FileSystemItem
|
||||
createPathResult.Value,
|
||||
name);
|
||||
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
|
||||
return setStatusResult.IsError ? (ErrorOr<WindowsRootItem>)setStatusResult.Errors : (ErrorOr<WindowsRootItem>)newRoot;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return newRoot;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -81,7 +83,9 @@ public sealed class WindowsRootItem : FileSystemItem
|
||||
id,
|
||||
name);
|
||||
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
|
||||
return setStatusResult.IsError ? (ErrorOr<WindowsRootItem>)setStatusResult.Errors : (ErrorOr<WindowsRootItem>)newFile;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return newFile;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+34
-13
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
@@ -6,6 +6,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -40,21 +41,41 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// Retrieves a list of subdirectory paths from the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to retrieve the subdirectory paths.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of directory paths or an error.</returns>
|
||||
public ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path)
|
||||
public ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false)
|
||||
? (ErrorOr<IEnumerable<FileSystemPathId>>)Errors.Permission.UnauthorizedAccess
|
||||
: ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path)
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path)
|
||||
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
|
||||
.OrderBy(path => path)
|
||||
.Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar)
|
||||
.Select(FileSystemPathId.Create)
|
||||
.Select(path => FileSystemPathId.Create(path))
|
||||
.Where(errorOrPathId => !errorOrPathId.IsError)
|
||||
.Select(errorOrPathId => errorOrPathId.Value)
|
||||
.AsEnumerable());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the attributes of a file system item identified by <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the file system attributes.</param>
|
||||
/// <returns>The retrieved file system attributes.</returns>
|
||||
private FileAttributes GetAttributes(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
// File.GetAttributes is used for both directories and files
|
||||
return _fileSystem.File.GetAttributes(path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a directory with the specified path exists.
|
||||
/// </summary>
|
||||
@@ -85,9 +106,9 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)
|
||||
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
|
||||
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path));
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -98,9 +119,9 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)
|
||||
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
|
||||
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path));
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -302,4 +323,4 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
return Result.Deleted;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+35
-21
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
@@ -41,37 +41,41 @@ public class DirectoryService : IDirectoryService
|
||||
/// Retrieves subdirectories for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path)
|
||||
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError ? (ErrorOr<IEnumerable<Directory>>)fileSystemPathIdResult.Errors : GetSubdirectories(fileSystemPathIdResult.Value);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the given directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(Directory directory)
|
||||
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements)
|
||||
{
|
||||
return GetSubdirectories(directory.Id);
|
||||
return GetSubdirectories(directory.Id, includeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path)
|
||||
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements)
|
||||
{
|
||||
// retrieve the list of subdirectories
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path);
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements);
|
||||
if (subdirectoryPathsResult.IsError)
|
||||
return subdirectoryPathsResult.Errors;
|
||||
List<Directory> result = [];
|
||||
IEnumerable<FileSystemPathId> subdirectoryPaths = subdirectoryPathsResult.Value;
|
||||
foreach (FileSystemPathId subPath in subdirectoryPaths)
|
||||
foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value)
|
||||
{
|
||||
// extract directory details
|
||||
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath);
|
||||
@@ -111,7 +115,9 @@ public class DirectoryService : IDirectoryService
|
||||
public ErrorOr<Directory> CreateDirectory(string path, string name)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError ? (ErrorOr<Directory>)fileSystemPathIdResult.Errors : CreateDirectory(fileSystemPathIdResult.Value, name);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return CreateDirectory(fileSystemPathIdResult.Value, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -149,7 +155,9 @@ public class DirectoryService : IDirectoryService
|
||||
if (errorDirResult.IsError)
|
||||
return errorDirResult.Errors;
|
||||
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
|
||||
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : errorDirResult;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return errorDirResult;
|
||||
}
|
||||
else
|
||||
return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
|
||||
@@ -174,9 +182,9 @@ public class DirectoryService : IDirectoryService
|
||||
if (fileSystemSourcePathIdResult.IsError)
|
||||
return fileSystemSourcePathIdResult.Errors;
|
||||
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
|
||||
return fileSystemDestinationPathIdResult.IsError
|
||||
? (ErrorOr<Directory>)fileSystemDestinationPathIdResult.Errors
|
||||
: CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
if (fileSystemDestinationPathIdResult.IsError)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -220,9 +228,9 @@ public class DirectoryService : IDirectoryService
|
||||
if (fileSystemSourcePathIdResult.IsError)
|
||||
return fileSystemSourcePathIdResult.Errors;
|
||||
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
|
||||
return fileSystemDestinationPathIdResult.IsError
|
||||
? (ErrorOr<Directory>)fileSystemDestinationPathIdResult.Errors
|
||||
: MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
if (fileSystemDestinationPathIdResult.IsError)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -257,7 +265,9 @@ public class DirectoryService : IDirectoryService
|
||||
public ErrorOr<Directory> RenameDirectory(string path, string name)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError ? (ErrorOr<Directory>)fileSystemPathIdResult.Errors : RenameDirectory(fileSystemPathIdResult.Value, name);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return RenameDirectory(fileSystemPathIdResult.Value, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -295,7 +305,9 @@ public class DirectoryService : IDirectoryService
|
||||
if (errorDirResult.IsError)
|
||||
return errorDirResult.Errors;
|
||||
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
|
||||
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : errorDirResult;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return errorDirResult;
|
||||
}
|
||||
else
|
||||
return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
|
||||
@@ -310,7 +322,9 @@ public class DirectoryService : IDirectoryService
|
||||
public ErrorOr<Deleted> DeleteDirectory(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError ? (ErrorOr<Deleted>)fileSystemPathIdResult.Errors : DeleteDirectory(fileSystemPathIdResult.Value);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return DeleteDirectory(fileSystemPathIdResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -323,4 +337,4 @@ public class DirectoryService : IDirectoryService
|
||||
return _environmentContext.DirectoryProviderService.DeleteDirectory(path);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
|
||||
@@ -42,7 +42,9 @@ public class DriveService : IDriveService
|
||||
if (_platformContext.Platform == PlatformType.Unix)
|
||||
{
|
||||
ErrorOr<UnixRootItem> unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible);
|
||||
return unixRootResult.IsError ? (ErrorOr<IEnumerable<FileSystemItem>>)unixRootResult.Errors : (ErrorOr<IEnumerable<FileSystemItem>>)new List<FileSystemItem>() { unixRootResult.Value };
|
||||
if (unixRootResult.IsError)
|
||||
return unixRootResult.Errors;
|
||||
return new List<FileSystemItem>() { unixRootResult.Value };
|
||||
}
|
||||
else
|
||||
return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives()
|
||||
@@ -63,4 +65,4 @@ public class DriveService : IDriveService
|
||||
.AsEnumerable());
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+41
-20
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
@@ -6,6 +6,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -40,20 +41,40 @@ internal class FileProviderService : IFileProviderService
|
||||
/// 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>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of file paths or an error.</returns>
|
||||
public ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path)
|
||||
public ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool includeHiddenElements)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory)
|
||||
? (ErrorOr<IEnumerable<FileSystemPathId>>)Errors.Permission.UnauthorizedAccess
|
||||
: ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path)
|
||||
.OrderBy(p => p)
|
||||
.Select(FileSystemPathId.Create)
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path)
|
||||
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
|
||||
.OrderBy(path => path)
|
||||
.Select(path => FileSystemPathId.Create(path))
|
||||
.Where(errorOrPathId => !errorOrPathId.IsError)
|
||||
.Select(errorOrPathId => errorOrPathId.Value)
|
||||
.AsEnumerable());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the attributes of a file system item identified by <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the file system attributes.</param>
|
||||
/// <returns>The retrieved file system attributes.</returns>
|
||||
private FileAttributes GetAttributes(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
// File.GetAttributes is used for both directories and files
|
||||
return _fileSystem.File.GetAttributes(path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a file with the specified path exists.
|
||||
/// </summary>
|
||||
@@ -82,9 +103,9 @@ internal class FileProviderService : IFileProviderService
|
||||
public ErrorOr<byte[]> GetFileAsync(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)
|
||||
? (ErrorOr<byte[]>)Errors.Permission.UnauthorizedAccess
|
||||
: (ErrorOr<byte[]>)System.IO.File.ReadAllBytes(path.Path);
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return System.IO.File.ReadAllBytes(path.Path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -95,9 +116,9 @@ internal class FileProviderService : IFileProviderService
|
||||
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
|
||||
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
|
||||
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path));
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -108,9 +129,9 @@ internal class FileProviderService : IFileProviderService
|
||||
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
|
||||
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
|
||||
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path));
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -121,9 +142,9 @@ internal class FileProviderService : IFileProviderService
|
||||
public ErrorOr<long?> GetSize(FileSystemPathId path)
|
||||
{
|
||||
// check if the user has access permissions to the provided path
|
||||
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
|
||||
? (ErrorOr<long?>)Errors.Permission.UnauthorizedAccess
|
||||
: (ErrorOr<long?>)(_fileSystem.FileInfo.New(path.Path)?.Length ?? 0);
|
||||
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
|
||||
return Errors.Permission.UnauthorizedAccess;
|
||||
return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -265,4 +286,4 @@ internal class FileProviderService : IFileProviderService
|
||||
return Result.Deleted;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+34
-19
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
@@ -41,32 +41,37 @@ public class FileService : IFileService
|
||||
/// Retrieves files for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public ErrorOr<IEnumerable<File>> GetFiles(string path)
|
||||
public ErrorOr<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError ? (ErrorOr<IEnumerable<File>>)fileSystemPathIdResult.Errors : GetFiles(fileSystemPathIdResult.Value);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files associated with a given file.
|
||||
/// </summary>
|
||||
/// <param name="file">The file object.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public ErrorOr<IEnumerable<File>> GetFiles(File file)
|
||||
public ErrorOr<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements)
|
||||
{
|
||||
return GetFiles(file.Id);
|
||||
return GetFiles(file.Id, includeHiddenElements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files for a specified file path Id.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
public ErrorOr<IEnumerable<File>> GetFiles(FileSystemPathId path)
|
||||
public ErrorOr<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements)
|
||||
{
|
||||
// retrieve the list of files
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path);
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements);
|
||||
if (filePathsResult.IsError)
|
||||
return filePathsResult.Errors;
|
||||
List<File> result = [];
|
||||
@@ -119,9 +124,9 @@ public class FileService : IFileService
|
||||
if (fileSystemSourcePathIdResult.IsError)
|
||||
return fileSystemSourcePathIdResult.Errors;
|
||||
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
|
||||
return fileSystemDestinationPathIdResult.IsError
|
||||
? (ErrorOr<File>)fileSystemDestinationPathIdResult.Errors
|
||||
: CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
if (fileSystemDestinationPathIdResult.IsError)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -158,7 +163,9 @@ public class FileService : IFileService
|
||||
if (errorFileResult.IsError)
|
||||
return errorFileResult.Errors;
|
||||
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
|
||||
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return errorFileResult;
|
||||
}
|
||||
else
|
||||
return File.Create(copyFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
|
||||
@@ -181,9 +188,9 @@ public class FileService : IFileService
|
||||
if (fileSystemSourcePathIdResult.IsError)
|
||||
return fileSystemSourcePathIdResult.Errors;
|
||||
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
|
||||
return fileSystemDestinationPathIdResult.IsError
|
||||
? (ErrorOr<File>)fileSystemDestinationPathIdResult.Errors
|
||||
: MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
if (fileSystemDestinationPathIdResult.IsError)
|
||||
return fileSystemDestinationPathIdResult.Errors;
|
||||
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -220,7 +227,9 @@ public class FileService : IFileService
|
||||
if (errorFileResult.IsError)
|
||||
return errorFileResult.Errors;
|
||||
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
|
||||
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return errorFileResult;
|
||||
}
|
||||
else
|
||||
return File.Create(moveFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
|
||||
@@ -236,7 +245,9 @@ public class FileService : IFileService
|
||||
public ErrorOr<File> RenameFile(string path, string name)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError ? (ErrorOr<File>)fileSystemPathIdResult.Errors : RenameFile(fileSystemPathIdResult.Value, name);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return RenameFile(fileSystemPathIdResult.Value, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -276,7 +287,9 @@ public class FileService : IFileService
|
||||
if (errorFileResult.IsError)
|
||||
return errorFileResult.Errors;
|
||||
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
|
||||
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
|
||||
if (setStatusResult.IsError)
|
||||
return setStatusResult.Errors;
|
||||
return errorFileResult;
|
||||
}
|
||||
else
|
||||
return File.Create(newFilePathResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
|
||||
@@ -291,7 +304,9 @@ public class FileService : IFileService
|
||||
public ErrorOr<Deleted> DeleteFile(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError ? (ErrorOr<Deleted>)fileSystemPathIdResult.Errors : DeleteFile(fileSystemPathIdResult.Value);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return DeleteFile(fileSystemPathIdResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -309,4 +324,4 @@ public class FileService : IFileService
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+8
-5
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Contracts.Enums.PhotoLibrary;
|
||||
@@ -73,9 +73,12 @@ public class FileTypeService : IFileTypeService
|
||||
return type;
|
||||
// no known image header types were found, check other methods
|
||||
string content = Encoding.UTF8.GetString(buffer.ToArray());
|
||||
return IsSvg(content, path.Path)
|
||||
? (ErrorOr<ImageType>)ImageType.SVG
|
||||
: IsTga(buffer.ToArray()) ? (ErrorOr<ImageType>)ImageType.TGA : (ErrorOr<ImageType>)ImageType.None;
|
||||
if (IsSvg(content, path.Path))
|
||||
return ImageType.SVG;
|
||||
else if (IsTga(buffer.ToArray()))
|
||||
return ImageType.TGA;
|
||||
else
|
||||
return ImageType.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -154,4 +157,4 @@ public class FileTypeService : IFileTypeService
|
||||
return ImageType.None;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -18,8 +18,9 @@ public interface IDirectoryProviderService
|
||||
/// Retrieves a list of subdirectory paths from the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path from which to retrieve the subdirectory paths.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of directory paths or an error.</returns>
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path);
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a directory with the specified path exists.
|
||||
@@ -91,4 +92,4 @@ public interface IDirectoryProviderService
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
ErrorOr<Deleted> DeleteDirectory(FileSystemPathId path);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -17,22 +17,25 @@ public interface IDirectoryService
|
||||
/// Retrieves subdirectories for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path);
|
||||
ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the given directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
ErrorOr<IEnumerable<Directory>> GetSubdirectories(Directory directory);
|
||||
ErrorOr<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves subdirectories for the specified file system path.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
|
||||
ErrorOr<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path);
|
||||
ErrorOr<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
|
||||
@@ -75,4 +78,4 @@ public interface IDirectoryService
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
|
||||
ErrorOr<Deleted> DeleteDirectory(string path);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -18,8 +18,9 @@ public interface IFileProviderService
|
||||
/// Retrieves a list of files at the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to retrieve the list of files.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of file paths, or an error.</returns>
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path);
|
||||
ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the contents of a file at the specified path.
|
||||
|
||||
+6
-3
@@ -17,22 +17,25 @@ public interface IFileService
|
||||
/// Retrieves files for the specified string path.
|
||||
/// </summary>
|
||||
/// <param name="path">String representation of the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
ErrorOr<IEnumerable<File>> GetFiles(string path);
|
||||
ErrorOr<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files associated with a given file.
|
||||
/// </summary>
|
||||
/// <param name="file">The file object.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
ErrorOr<IEnumerable<File>> GetFiles(File file);
|
||||
ErrorOr<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves files for a specified file path ID.
|
||||
/// </summary>
|
||||
/// <param name="path">Identifier for the file path.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
|
||||
ErrorOr<IEnumerable<File>> GetFiles(FileSystemPathId path);
|
||||
ErrorOr<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements);
|
||||
|
||||
/// <summary>
|
||||
/// Copies a file located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
|
||||
|
||||
+20
-8
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
@@ -43,7 +43,9 @@ public class PathService : IPathService
|
||||
public bool IsValidPath(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
return !newPathResult.IsError && _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
|
||||
if (newPathResult.IsError)
|
||||
return false;
|
||||
return _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -54,7 +56,9 @@ public class PathService : IPathService
|
||||
public bool Exists(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
return !newPathResult.IsError && _platformContext.PathStrategy.Exists(newPathResult.Value);
|
||||
if (newPathResult.IsError)
|
||||
return false;
|
||||
return _platformContext.PathStrategy.Exists(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -69,7 +73,9 @@ public class PathService : IPathService
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
ErrorOr<FileSystemPathId> combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name);
|
||||
return combinedPathResult.IsError ? (ErrorOr<string>)combinedPathResult.Errors : (ErrorOr<string>)combinedPathResult.Value.Path;
|
||||
if (combinedPathResult.IsError)
|
||||
return combinedPathResult.Errors;
|
||||
return combinedPathResult.Value.Path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -80,7 +86,9 @@ public class PathService : IPathService
|
||||
public ErrorOr<IEnumerable<PathSegment>> ParsePath(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : _platformContext.PathStrategy.ParsePath(newPathResult.Value);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return _platformContext.PathStrategy.ParsePath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -91,7 +99,9 @@ public class PathService : IPathService
|
||||
public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -111,7 +121,9 @@ public class PathService : IPathService
|
||||
public ErrorOr<PathSegment> GetPathRoot(string path)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
|
||||
return newPathResult.IsError ? (ErrorOr<PathSegment>)newPathResult.Errors : _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.PhotoLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
@@ -45,9 +45,9 @@ public class ThumbnailService : IThumbnailService
|
||||
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality)
|
||||
{
|
||||
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
return fileSystemPathIdResult.IsError
|
||||
? (ErrorOr<Thumbnail>)fileSystemPathIdResult.Errors
|
||||
: await GetThumbnailAsync(fileSystemPathIdResult.Value, quality);
|
||||
if (fileSystemPathIdResult.IsError)
|
||||
return fileSystemPathIdResult.Errors;
|
||||
return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -187,4 +187,4 @@ public class ThumbnailService : IThumbnailService
|
||||
return ((value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource)) + fromTarget;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -1,4 +1,6 @@
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
|
||||
|
||||
@@ -38,4 +40,4 @@ internal class EnvironmentContext : IEnvironmentContext
|
||||
DirectoryProviderService = directoryProviderService;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+8
-6
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
@@ -127,7 +127,9 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
return Errors.FileManagement.CannotNavigateUp;
|
||||
// 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]);
|
||||
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : ParsePath(newPathResult.Value);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return ParsePath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -150,9 +152,9 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
return Errors.FileManagement.InvalidPath;
|
||||
|
||||
// On Unix-like systems, the root is always "/"
|
||||
return path.Path.StartsWith(PathSeparator)
|
||||
? (ErrorOr<PathSegment>)new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true)
|
||||
: (ErrorOr<PathSegment>)Errors.FileManagement.InvalidPath;
|
||||
if (path.Path.StartsWith(PathSeparator))
|
||||
return new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true);
|
||||
return Errors.FileManagement.InvalidPath;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+8
-6
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
@@ -89,9 +89,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
public ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
|
||||
{
|
||||
// Windows paths usually start with a drive letter and colon, e.g., "C:"
|
||||
return !path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator
|
||||
? (ErrorOr<IEnumerable<PathSegment>>)Errors.FileManagement.InvalidPath
|
||||
: ErrorOrFactory.From(GetPathSegments());
|
||||
if (!path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator)
|
||||
return Errors.FileManagement.InvalidPath;
|
||||
return ErrorOrFactory.From(GetPathSegments());
|
||||
IEnumerable<PathSegment> GetPathSegments()
|
||||
{
|
||||
// the drive segment
|
||||
@@ -135,7 +135,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
return Errors.FileManagement.CannotNavigateUp;
|
||||
// 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]);
|
||||
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : ParsePath(newPathResult.Value);
|
||||
if (newPathResult.IsError)
|
||||
return newPathResult.Errors;
|
||||
return ParsePath(newPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -181,4 +183,4 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
return Errors.FileManagement.InvalidPath;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
@@ -48,7 +48,9 @@ public sealed class FileSystemPathId : ValueObject
|
||||
/// </returns>
|
||||
public static ErrorOr<FileSystemPathId> Create(string path)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(path) ? (ErrorOr<FileSystemPathId>)Errors.FileManagement.InvalidPath : (ErrorOr<FileSystemPathId>)new FileSystemPathId(path);
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
return Errors.FileManagement.InvalidPath;
|
||||
return new FileSystemPathId(path);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+8
-8
@@ -115,13 +115,13 @@ public class StreamInfo : ValueObject
|
||||
Optional<int> sampleRate,
|
||||
Optional<int> channels)
|
||||
{
|
||||
return streamId is null
|
||||
? (ErrorOr<StreamInfo>)Errors.FileManagement.StreamIdCannotBeEmpty
|
||||
: codec is null
|
||||
? (ErrorOr<StreamInfo>)Errors.FileManagement.CodecCannotBeEmpty
|
||||
: bitrate <= 0
|
||||
? (ErrorOr<StreamInfo>)Errors.FileManagement.BitrateMustBeAPositiveNumber
|
||||
: (ErrorOr<StreamInfo>)new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
|
||||
if (streamId is null)
|
||||
return Errors.FileManagement.StreamIdCannotBeEmpty;
|
||||
if (codec is null)
|
||||
return Errors.FileManagement.CodecCannotBeEmpty;
|
||||
if (bitrate <= 0)
|
||||
return Errors.FileManagement.BitrateMustBeAPositiveNumber;
|
||||
return new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -137,4 +137,4 @@ public class StreamInfo : ValueObject
|
||||
yield return Channels;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -51,9 +51,11 @@ public class BookRating : Rating
|
||||
/// </returns>
|
||||
public static ErrorOr<BookRating> Create(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
|
||||
{
|
||||
return maxValue < 0 || value < 0
|
||||
? (ErrorOr<BookRating>)Errors.Metadata.RatingValueMustBePositive
|
||||
: value > maxValue ? (ErrorOr<BookRating>)Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue : (ErrorOr<BookRating>)new BookRating(value, maxValue, source, voteCount);
|
||||
if (maxValue < 0 || value < 0)
|
||||
return Errors.Metadata.RatingValueMustBePositive;
|
||||
if (value > maxValue)
|
||||
return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue;
|
||||
return new BookRating(value, maxValue, source, voteCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -79,4 +81,4 @@ public class BookRating : Rating
|
||||
return baseString;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -17,8 +17,8 @@ namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggrega
|
||||
public sealed class Isbn : ValueObject
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private static readonly Regex Isbn10Regex = new(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$", RegexOptions.Compiled);
|
||||
private static readonly Regex Isbn13Regex = new(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$", RegexOptions.Compiled);
|
||||
private static readonly Regex _isbn10Regex = new(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$", RegexOptions.Compiled);
|
||||
private static readonly Regex _isbn13Regex = new(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$", RegexOptions.Compiled);
|
||||
#endregion
|
||||
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
@@ -83,7 +83,7 @@ public sealed class Isbn : ValueObject
|
||||
/// <returns><see langword="true"/> if the ISBN-10 is valid, <see langword="false"/> otherwise.</returns>
|
||||
public static bool IsValidIsbn10(string isbn)
|
||||
{
|
||||
if (!Isbn10Regex.IsMatch(isbn))
|
||||
if (!_isbn10Regex.IsMatch(isbn))
|
||||
return false;
|
||||
// remove any hyphens or spaces
|
||||
isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper();
|
||||
@@ -105,7 +105,7 @@ public sealed class Isbn : ValueObject
|
||||
/// <returns><see langword="true"/> if the ISBN-13 is valid, <see langword="false"/> otherwise.</returns>
|
||||
public static bool IsValidIsbn13(string isbn)
|
||||
{
|
||||
if (!Isbn13Regex.IsMatch(isbn))
|
||||
if (!_isbn13Regex.IsMatch(isbn))
|
||||
return false;
|
||||
// remove any hyphens or spaces
|
||||
isbn = isbn.Replace("-", "").Replace(" ", "");
|
||||
@@ -123,4 +123,4 @@ public sealed class Isbn : ValueObject
|
||||
yield return Format;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -88,15 +88,15 @@ public class WrittenContentMetadata : BaseMetadata
|
||||
Optional<string> publisher,
|
||||
Optional<int> pageCount)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(title)
|
||||
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.TitleCannotBeEmpty
|
||||
: releaseInfo is null
|
||||
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.ReleaseInfoCannotBeNull
|
||||
: genres is null
|
||||
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.GenresListCannotBeNull
|
||||
: tags is null
|
||||
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.TagsListCannotBeNull
|
||||
: (ErrorOr<WrittenContentMetadata>)new WrittenContentMetadata(
|
||||
if (string.IsNullOrWhiteSpace(title))
|
||||
return Errors.Metadata.TitleCannotBeEmpty;
|
||||
if (releaseInfo is null)
|
||||
return Errors.Metadata.ReleaseInfoCannotBeNull;
|
||||
if (genres is null)
|
||||
return Errors.Metadata.GenresListCannotBeNull;
|
||||
if (tags is null)
|
||||
return Errors.Metadata.TagsListCannotBeNull;
|
||||
return new WrittenContentMetadata(
|
||||
title,
|
||||
originalTitle,
|
||||
description,
|
||||
@@ -118,4 +118,4 @@ public class WrittenContentMetadata : BaseMetadata
|
||||
yield return PageCount;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -34,13 +34,13 @@ public static class SharedConfiguration
|
||||
|
||||
// bind the common settings section
|
||||
services.AddOptions<CommonSettingsModel>()
|
||||
.Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName))
|
||||
.Bind(configuration.GetRequiredSection(CommonSettingsModel.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
|
||||
// bind the database connection string section
|
||||
services.AddOptions<DatabaseSettingsModel>()
|
||||
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName))
|
||||
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
return services;
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Models.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Model for deserializing shared application configuration settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{SECTION_NAME}")]
|
||||
public class CommonSettingsModel
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
public const string SectionName = "CommonSettings";
|
||||
public const string SECTION_NAME = "CommonSettings";
|
||||
#endregion
|
||||
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
@@ -15,4 +20,4 @@ public class CommonSettingsModel
|
||||
/// </summary>
|
||||
public required string Theme { get; init; }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Models.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Model for deserializing database configuration settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{SECTION_NAME}")]
|
||||
public class DatabaseSettingsModel
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
public const string SectionName = "ConnectionStrings";
|
||||
public const string SECTION_NAME = "ConnectionStrings";
|
||||
#endregion
|
||||
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
@@ -15,4 +20,4 @@ public class DatabaseSettingsModel
|
||||
/// </summary>
|
||||
public required string DefaultConnection { get; init; }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -25,11 +25,14 @@ public static class PresentationApiLayerServices
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddCors(options => options.AddPolicy("AllowAll",
|
||||
services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowAll",
|
||||
builder => builder
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()));
|
||||
.AllowAnyHeader());
|
||||
});
|
||||
|
||||
// add services to the container
|
||||
services.AddControllers().AddJsonOptions(options =>
|
||||
@@ -67,4 +70,4 @@ public static class PresentationApiLayerServices
|
||||
return services;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -116,11 +116,9 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory
|
||||
List<Error>? errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List<Error>;
|
||||
// add any extra custom properties
|
||||
if (errors is not null)
|
||||
{
|
||||
problemDetails.Extensions.Add("errors", errors.Select(error => error.Code));
|
||||
}
|
||||
//problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString()));
|
||||
_configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails });
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+14
-8
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories;
|
||||
using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree;
|
||||
@@ -42,11 +42,13 @@ public class DirectoriesController : ApiController
|
||||
/// Gets the tree of expanded directories leading up to <paramref name="path"/>, with the additional list of drives, and children of the last child directory.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to get the directory tree.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
[HttpGet("get-directory-tree")]
|
||||
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetDirectoryTree([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] bool includeFiles, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetDirectoryTree([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
|
||||
[FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles), cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles, includeHiddenElements), cancellationToken).ConfigureAwait(false);
|
||||
if (!result.IsError && result.Value is not null)
|
||||
{
|
||||
foreach (FileSystemTreeNodeResponse treeNode in result.Value)
|
||||
@@ -62,11 +64,13 @@ public class DirectoriesController : ApiController
|
||||
/// Gets the directories of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to get the directories.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
[HttpGet("get-tree-directories")]
|
||||
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
|
||||
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeDirectoriesQuery(path), cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeDirectoriesQuery(path,includeHiddenElements), cancellationToken).ConfigureAwait(false);
|
||||
if (!result.IsError && result.Value is not null)
|
||||
{
|
||||
foreach (FileSystemTreeNodeResponse directory in result.Value)
|
||||
@@ -82,11 +86,13 @@ public class DirectoriesController : ApiController
|
||||
/// Gets the directories of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to get the directories.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
[HttpGet("get-directories")]
|
||||
public async IAsyncEnumerable<DirectoryResponse> GetDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
public async IAsyncEnumerable<DirectoryResponse> GetDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
|
||||
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<DirectoryResponse>> result = await _mediator.Send(new GetDirectoriesQuery(path), cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<IEnumerable<DirectoryResponse>> result = await _mediator.Send(new GetDirectoriesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
|
||||
if (!result.IsError && result.Value is not null)
|
||||
{
|
||||
foreach (DirectoryResponse directory in result.Value)
|
||||
@@ -98,4 +104,4 @@ public class DirectoriesController : ApiController
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
@@ -43,7 +43,7 @@ public class DrivesController : ApiController
|
||||
public async Task<IActionResult> GetDrives(CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(Ok, Problem);
|
||||
return result.Match(result => Ok(result), errors => Problem(errors));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles;
|
||||
using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles;
|
||||
@@ -31,7 +31,7 @@ public class FilesController : ApiController
|
||||
/// Initializes a new instance of the <see cref="FilesController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediator">Injected service for mediating commands and queries.</param>
|
||||
public FilesController(ISender mediator, IMapper mapper)
|
||||
public FilesController(ISender mediator)
|
||||
{
|
||||
_mediator = mediator;
|
||||
}
|
||||
@@ -42,11 +42,13 @@ public class FilesController : ApiController
|
||||
/// Gets the files of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to get the files.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
[HttpGet("get-tree-files")]
|
||||
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
|
||||
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeFilesQuery(path), cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
|
||||
foreach (FileSystemTreeNodeResponse file in result.Value)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
@@ -59,11 +61,13 @@ public class FilesController : ApiController
|
||||
/// Gets the files of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path for which to get the files.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
[HttpGet("get-files")]
|
||||
public async IAsyncEnumerable<FileResponse> GetFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
public async IAsyncEnumerable<FileResponse> GetFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
|
||||
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileResponse>> result = await _mediator.Send(new GetFilesQuery(path), cancellationToken).ConfigureAwait(false);
|
||||
ErrorOr<IEnumerable<FileResponse>> result = await _mediator.Send(new GetFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
|
||||
if (!result.IsError)
|
||||
{
|
||||
foreach (FileResponse file in result.Value)
|
||||
@@ -75,4 +79,4 @@ public class FilesController : ApiController
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath;
|
||||
using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath;
|
||||
@@ -51,7 +51,7 @@ public class PathController : ApiController
|
||||
public async Task<IActionResult> GetPathRoot([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<PathSegmentResponse> result = await _mediator.Send(new GetPathRootQuery(path), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(Ok, Problem);
|
||||
return result.Match(result => Ok(result), errors => Problem(errors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -74,7 +74,7 @@ public class PathController : ApiController
|
||||
public async Task<IActionResult> GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(Ok, Problem);
|
||||
return result.Match(result => Ok(result), errors => Problem(errors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -87,7 +87,7 @@ public class PathController : ApiController
|
||||
public async Task<IActionResult> CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<PathSegmentResponse> result = await _mediator.Send(new CombinePathCommand(originalPath, newPath), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(Ok, Problem);
|
||||
return result.Match(result => Ok(result), errors => Problem(errors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -99,7 +99,7 @@ public class PathController : ApiController
|
||||
public async Task<IActionResult> SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(Ok, Problem);
|
||||
return result.Match(result => Ok(result), errors => Problem(errors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -126,4 +126,4 @@ public class PathController : ApiController
|
||||
return Ok(result);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -44,7 +44,7 @@ public class BooksController : ApiController
|
||||
public async Task<IActionResult> GetBooks()
|
||||
{
|
||||
ErrorOr.ErrorOr<System.Collections.Generic.IEnumerable<Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Book>> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false);
|
||||
return result.Match(Ok, Problem);
|
||||
return result.Match(result => Ok(result), errors => Problem(errors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -58,4 +58,4 @@ public class BooksController : ApiController
|
||||
return result.Match(result => Created($"/api/v1/books/{result.Id}", result), Problem);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Models.Common;
|
||||
using Lumina.Presentation.Web.Common.Models.Configuration;
|
||||
@@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Components.WebAssembly.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Runtime.CompilerServices;
|
||||
@@ -90,7 +91,7 @@ public class ApiHttpClient : IApiHttpClient
|
||||
// send the request and expect only headers initially - this prevents the client from buffering the entire response
|
||||
using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using System.IO.Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Deserialize the JSON content asynchronously as an enumerable of TResponse items
|
||||
await foreach (TResponse? item in JsonSerializer.DeserializeAsyncEnumerable<TResponse>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
@@ -215,4 +216,4 @@ public class ApiHttpClient : IApiHttpClient
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -37,7 +37,7 @@ internal static class PresentationWebLayerConfiguration
|
||||
internal static IServiceCollection BindConfiguration(this IServiceCollection serviceCollection, IConfiguration configuration)
|
||||
{
|
||||
serviceCollection.AddOptions<ServerConfigurationModel>()
|
||||
.Bind(configuration.GetRequiredSection(ServerConfigurationModel.SectionName))
|
||||
.Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
return serviceCollection;
|
||||
|
||||
+8
-5
@@ -1,10 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Services.UI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Polly;
|
||||
using Polly.CircuitBreaker;
|
||||
using Polly.Retry;
|
||||
using Polly.Wrap;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
@@ -29,7 +32,7 @@ public static class PresentationWebLayerServices
|
||||
services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Singleton);
|
||||
|
||||
// handle transient errors like network timeouts or intermittent failures
|
||||
Polly.Retry.AsyncRetryPolicy<HttpResponseMessage> retryPolicy = Policy
|
||||
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = Policy
|
||||
.Handle<HttpRequestException>()
|
||||
.OrResult<HttpResponseMessage>(r =>
|
||||
!r.IsSuccessStatusCode &&
|
||||
@@ -39,12 +42,12 @@ public static class PresentationWebLayerServices
|
||||
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
|
||||
|
||||
// use a circuit breaker to prevent repeatedly calling a failing service
|
||||
Polly.CircuitBreaker.AsyncCircuitBreakerPolicy<HttpResponseMessage> circuitBreakerPolicy = Policy
|
||||
AsyncCircuitBreakerPolicy<HttpResponseMessage> circuitBreakerPolicy = Policy
|
||||
.Handle<HttpRequestException>()
|
||||
.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError)
|
||||
.CircuitBreakerAsync(3, TimeSpan.FromSeconds(30));
|
||||
|
||||
Polly.Wrap.AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
|
||||
AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
|
||||
|
||||
// register the typed client used for the API interaction
|
||||
services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
|
||||
@@ -57,4 +60,4 @@ public static class PresentationWebLayerServices
|
||||
return services;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,11 @@ namespace Lumina.Presentation.Web.Common.Models.Configuration;
|
||||
/// <summary>
|
||||
/// Model for deserializing server configuration settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{SectionName}")]
|
||||
[DebuggerDisplay("{SECTION_NAME}")]
|
||||
public class ServerConfigurationModel
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
public const string SectionName = "ServerConfiguration";
|
||||
public const string SECTION_NAME = "ServerConfiguration";
|
||||
#endregion
|
||||
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
@@ -30,4 +30,4 @@ public class ServerConfigurationModel
|
||||
/// </summary>
|
||||
public required ushort Port { get; init; }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
@using Lumina.Presentation.Web.Common.Models.Common
|
||||
@using Lumina.Presentation.Web.Common.Models.Common
|
||||
@using Lumina.Presentation.Web.Common.Api
|
||||
@using Lumina.Presentation.Web.Common.Enums.FileSystem
|
||||
@using Lumina.Presentation.Web.Common.Enums.Notifications
|
||||
@@ -39,14 +39,10 @@
|
||||
</div>
|
||||
<img src="images/ui/toggle-tree-view.svg" id="navigator-toggle-tree-view-button" alt="Toggle Tree View" title="Toggle Tree View" class="navigator-icon" />
|
||||
<img src="images/ui/toggle-thumbnails.svg" id="navigator-toggle-thumbnails-button" alt="Toggle Thumbnails" title="Toggle Thumbanils" class="navigator-icon" />
|
||||
<img src="images/ui/toggle-hidden.svg" id="navigator-toggle-hidden-button" alt="Toggle Hidden Files" title="Toggle Hidden Files" class="navigator-icon" />
|
||||
@* <img src="images/ui/toggle-selection.svg" id="navigator-toggle-selection-button" alt="Toggle Selection Mode" title="Toggle Selection Mode" class="navigator-icon" /> *@
|
||||
@* <img src="images/ui/toggle-hidden.svg" id="navigator-toggle-hidden-button" alt="Toggle Hidden Files" title="Toggle Hidden Files" class="navigator-icon" /> *@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<svg @onclick="ToggleSelectionModeAsync" id="navigator-toggle-selection-button" alt="Toggle Selection Mode" title="Toggle Selection Mode" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<svg @onclick="ToggleHiddenElementsModeAsync" id="navigator-toggle-hidden-button" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Toggle Hidden Files</title>
|
||||
<defs>
|
||||
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
|
||||
@@ -60,7 +56,8 @@
|
||||
<feMergeNode in="SourceGraphic" />
|
||||
</feMerge>
|
||||
</filter>
|
||||
<linearGradient id="linearGradient1299" x1="5" x2="195" y1="174.76" y2="174.76" gradientTransform="matrix(.32632 0 0 .095367 -.63187 42.834)" gradientUnits="userSpaceOnUse">
|
||||
|
||||
<linearGradient id="linearGradient" x1="5" x2="195" y1="174.76" y2="174.76" gradientTransform="matrix(.32632 0 0 .095367 -.63187 42.834)" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#039bfc" stop-opacity="0" offset="0" />
|
||||
<stop stop-color="#039bfc" offset=".225" />
|
||||
<stop stop-color="#039bfc" offset=".5" />
|
||||
@@ -70,7 +67,44 @@
|
||||
</defs>
|
||||
|
||||
<g transform="translate(0,-0.5) scale(0.475)">
|
||||
<rect x=".99971" y="59" width="62.001" height="1" ry="0" fill="url(#linearGradient1299)" stroke-width="3.7796" style="mix-blend-mode:normal;paint-order:stroke fill markers" filter="url(#glow)" />
|
||||
<rect x=".99971" y="59" width="62.001" height="1" ry="0" fill="url(#linearGradient)" stroke-width="3.7796" style="mix-blend-mode:normal;paint-order:stroke fill markers" filter="url(#glow)" />
|
||||
</g>
|
||||
<g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.5">
|
||||
<rect x="4.5" y="4.5" width="21" height="21" ry="2.5" fill="none" stroke="#039bfc" style="paint-order:stroke fill markers" filter="url(#glow)" />
|
||||
</g>
|
||||
<g transform="translate(5,5) scale(0.85)">
|
||||
<path xmlns="http://www.w3.org/2000/svg" style="fill:currentColor;" class="navigator-icon-fill @(showHiddenElements ? " enabled" : string.Empty)" filter="url(#glow)" d="M14.3307 7.16929C13.5873 7.05887 12.806 7 12 7C7.02944 7 3 9.23858 3 12C3 13.4401 4.09589 14.738 5.84963 15.6504L8.21192 13.2881C8.07452 12.8839 8 12.4506 8 12C8 9.79086 9.79086 8 12 8C12.4506 8 12.8839 8.07452 13.2881 8.21192L14.3307 7.16929Z" />
|
||||
<path xmlns="http://www.w3.org/2000/svg" style="fill:currentColor;" class="navigator-icon-fill @(showHiddenElements ? " enabled" : string.Empty)" filter="url(#glow)" d="M11.2308 15.9261C11.4797 15.9746 11.7369 16 12 16C14.2091 16 16 14.2091 16 12C16 11.7369 15.9746 11.4797 15.9261 11.2308L18.5726 8.58427C20.0782 9.47809 21 10.6792 21 12C21 14.7614 16.9706 17 12 17C11.4016 17 10.8169 16.9676 10.2512 16.9057L11.2308 15.9261Z" />
|
||||
<path xmlns="http://www.w3.org/2000/svg" style="fill:currentColor;" class="navigator-icon-fill @(showHiddenElements ? " enabled" : string.Empty)" filter="url(#glow)" d="M17.7929 5.20711C18.1834 4.81658 18.8166 4.81658 19.2071 5.20711C19.5976 5.59763 19.5976 6.2308 19.2071 6.62132L6.47919 19.3492C6.08866 19.7398 5.4555 19.7398 5.06497 19.3492C4.67445 18.9587 4.67445 18.3256 5.06497 17.935L17.7929 5.20711Z" />
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
<svg @onclick="ToggleSelectionModeAsync" id="navigator-toggle-selection-button" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Toggle Selection Mode</title>
|
||||
<defs>
|
||||
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
|
||||
<feFuncA type="table" tableValues="0 0.5 1" />
|
||||
</feComponentTransfer>
|
||||
<feGaussianBlur in="adjustedAlpha" stdDeviation="2" result="blur" />
|
||||
<feFlood flood-color="#039bfc" result="color" />
|
||||
<feComposite in="color" in2="blur" operator="in" result="softGlowColored" />
|
||||
<feMerge>
|
||||
<feMergeNode in="softGlowColored" />
|
||||
<feMergeNode in="SourceGraphic" />
|
||||
</feMerge>
|
||||
</filter>
|
||||
<linearGradient id="linearGradient1" x1="5" x2="195" y1="174.76" y2="174.76" gradientTransform="matrix(.32632 0 0 .095367 -.63187 42.834)" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#039bfc" stop-opacity="0" offset="0" />
|
||||
<stop stop-color="#039bfc" offset=".225" />
|
||||
<stop stop-color="#039bfc" offset=".5" />
|
||||
<stop stop-color="#039bfc" offset=".775" />
|
||||
<stop stop-color="#039bfc" stop-opacity="0" offset="1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(0,-0.5) scale(0.475)">
|
||||
<rect x=".99971" y="59" width="62.001" height="1" ry="0" fill="url(#linearGradient)" stroke-width="3.7796" style="mix-blend-mode:normal;paint-order:stroke fill markers" filter="url(#glow)" />
|
||||
</g>
|
||||
<g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.5">
|
||||
<rect x="4.5" y="4.5" width="21" height="21" ry="2.5" fill="none" stroke="#039bfc" style="paint-order:stroke fill markers" filter="url(#glow)" />
|
||||
@@ -229,6 +263,7 @@
|
||||
private string? selectedNodePath;
|
||||
private string? _path;
|
||||
private bool isSelectionMode;
|
||||
private bool showHiddenElements;
|
||||
private bool showPathSegmentDowpDown;
|
||||
private bool isNavigationPathEditMode;
|
||||
private int? expandedPathSegmentIndex;
|
||||
@@ -312,7 +347,7 @@
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"directories/get-tree-directories?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false))
|
||||
await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"directories/get-tree-directories?path={Uri.EscapeDataString(node.Path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false))
|
||||
{
|
||||
if (childNode is not null)
|
||||
{
|
||||
@@ -322,7 +357,7 @@
|
||||
}
|
||||
if (IncludeFiles)
|
||||
{
|
||||
await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"files/get-tree-files?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false))
|
||||
await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"files/get-tree-files?path={Uri.EscapeDataString(node.Path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false))
|
||||
{
|
||||
if (childNode is not null)
|
||||
{
|
||||
@@ -386,7 +421,7 @@
|
||||
// add current and parent directories too
|
||||
List<FileSystemTreeNodeModel> directories = [new() { Path = concatenatedPath, Name = ".", }, new() { Path = parentConcatenatedPath, Name = ".." }];
|
||||
// add the rest of the subdirectories of the expanded path node
|
||||
await foreach (FileSystemTreeNodeModel? directory in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"directories/get-tree-directories?path={Uri.EscapeDataString(concatenatedPath)}").ConfigureAwait(false))
|
||||
await foreach (FileSystemTreeNodeModel? directory in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"directories/get-tree-directories?path={Uri.EscapeDataString(concatenatedPath)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false))
|
||||
if (directory is not null)
|
||||
directories.Add(directory);
|
||||
// store the directories for this segment
|
||||
@@ -622,7 +657,7 @@
|
||||
});
|
||||
}
|
||||
// if there was an initial path saved from a previous session, load the full tree up to that initial path
|
||||
List<FileSystemTreeNodeModel> initialTree = await _apiHttpClient.GetAsync<List<FileSystemTreeNodeModel>>($"directories/get-directory-tree?path={Uri.EscapeDataString(path!)}&includeFiles={IncludeFiles}").ConfigureAwait(false);
|
||||
List<FileSystemTreeNodeModel> initialTree = await _apiHttpClient.GetAsync<List<FileSystemTreeNodeModel>>($"directories/get-directory-tree?path={Uri.EscapeDataString(path!)}&includeFiles={IncludeFiles}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false);
|
||||
if (initialTree is not null && initialTree.Count > 0)
|
||||
{
|
||||
// take the root of the retrieved tree, and try to match it against a drive in the retrieved list of drives, on Windows; on Unix, add it as the unique root path
|
||||
@@ -651,7 +686,7 @@
|
||||
fileSystemItems.Clear();
|
||||
try
|
||||
{
|
||||
await foreach (DirectoryModel? directory in _apiHttpClient.GetAsyncEnumerable<DirectoryModel>($"directories/get-directories?path={Uri.EscapeDataString(path)}").ConfigureAwait(false))
|
||||
await foreach (DirectoryModel? directory in _apiHttpClient.GetAsyncEnumerable<DirectoryModel>($"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false))
|
||||
{
|
||||
if (directory is not null)
|
||||
{
|
||||
@@ -661,7 +696,7 @@
|
||||
}
|
||||
if (IncludeFiles)
|
||||
{
|
||||
await foreach (FileModel? file in _apiHttpClient.GetAsyncEnumerable<FileModel>($"files/get-files?path={Uri.EscapeDataString(path)}").ConfigureAwait(false))
|
||||
await foreach (FileModel? file in _apiHttpClient.GetAsyncEnumerable<FileModel>($"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false))
|
||||
{
|
||||
if (file is not null)
|
||||
{
|
||||
@@ -774,6 +809,20 @@
|
||||
await JSRuntime.InvokeVoidAsync("toggleSelectionMode").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enables or disables the display of hidden file system files and directories.
|
||||
/// </summary>
|
||||
private async Task ToggleHiddenElementsModeAsync()
|
||||
{
|
||||
showHiddenElements = !showHiddenElements;
|
||||
if (Path is not null)
|
||||
{
|
||||
if (!Path.EndsWith(pathSeparator))
|
||||
Path += pathSeparator;
|
||||
await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles API exceptions, presenting standard problem details in a user friendly way.
|
||||
/// </summary>
|
||||
@@ -820,4 +869,4 @@
|
||||
{
|
||||
reference?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,5 +21,10 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
|
||||
<PackageReference Include="Polly" Version="8.4.1" />
|
||||
</ItemGroup>
|
||||
</ItemGroup>
|
||||
|
||||
<!--disable warnings generated by Mediator source generator-->
|
||||
<PropertyGroup>
|
||||
<NoWarn>$(NoWarn);TS6385</NoWarn>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,51 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="64" height="64" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<defs>
|
||||
<style type="text/css" id="current-color-scheme">
|
||||
.ColorScheme-Text {
|
||||
color:#039bfc;
|
||||
}
|
||||
</style>
|
||||
|
||||
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
|
||||
<feFuncA type="table" tableValues="0 0.5 1"/>
|
||||
</feComponentTransfer>
|
||||
<feGaussianBlur in="adjustedAlpha" stdDeviation="2" result="blur"/>
|
||||
<feFlood flood-color="#039bfc" result="color"/>
|
||||
<feComposite in="color" in2="blur" operator="in" result="softGlowColored"/>
|
||||
<feMerge>
|
||||
<feMergeNode in="softGlowColored"/>
|
||||
<feMergeNode in="SourceGraphic"/>
|
||||
</feMerge>
|
||||
</filter>
|
||||
|
||||
<linearGradient id="b" x1="399.57" x2="399.57" y1="545.8" y2="517.8" gradientTransform="matrix(2.1429 0 0 2.1429 -723.44 -1107.5)" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#3889e9" offset="0"/>
|
||||
<stop stop-color="#5ea5fb" offset="1"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="b-3" x1="399.57" x2="399.57" y1="545.8" y2="517.8" gradientTransform="matrix(2.1429 0 0 2.1429 -753.02 -1107.5)" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#3889e9" offset="0"/>
|
||||
<stop stop-color="#5ea5fb" offset="1"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="linearGradient1299" x1="5" x2="195" y1="174.76" y2="174.76" gradientTransform="matrix(.32632 0 0 .095367 -.63187 42.834)" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#039bfc" stop-opacity="0" offset="0"/>
|
||||
<stop stop-color="#039bfc" offset=".225"/>
|
||||
<stop stop-color="#039bfc" offset=".5"/>
|
||||
<stop stop-color="#039bfc" offset=".775"/>
|
||||
<stop stop-color="#039bfc" stop-opacity="0" offset="1"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<circle cx="134.94" cy="32.044" r="0" fill="url(#b)" stroke-width="1.5715"/>
|
||||
<circle cx="105.36" cy="32.044" r="0" fill="url(#b-3)" stroke-width="1.5715"/>
|
||||
<rect x=".99971" y="59" width="62.001" height="1" ry="0" fill="url(#linearGradient1299)" stroke-width="3.7796" style="mix-blend-mode:normal;paint-order:stroke fill markers" filter="url(#glow)"/>
|
||||
<g stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="9.5" y="9.5" width="45" height="45" ry="5" fill="none" stroke="#039bfc" style="paint-order:stroke fill markers" filter="url(#glow)"/>
|
||||
</g>
|
||||
<g transform="translate(8,8) scale(2)">
|
||||
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M14.3307 7.16929C13.5873 7.05887 12.806 7 12 7C7.02944 7 3 9.23858 3 12C3 13.4401 4.09589 14.738 5.84963 15.6504L8.21192 13.2881C8.07452 12.8839 8 12.4506 8 12C8 9.79086 9.79086 8 12 8C12.4506 8 12.8839 8.07452 13.2881 8.21192L14.3307 7.16929Z" class="ColorScheme-Text" filter="url(#glow)"/>
|
||||
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M11.2308 15.9261C11.4797 15.9746 11.7369 16 12 16C14.2091 16 16 14.2091 16 12C16 11.7369 15.9746 11.4797 15.9261 11.2308L18.5726 8.58427C20.0782 9.47809 21 10.6792 21 12C21 14.7614 16.9706 17 12 17C11.4016 17 10.8169 16.9676 10.2512 16.9057L11.2308" class="ColorScheme-Text" filter="url(#glow)"/>
|
||||
<path style="fill:currentColor;fill-opacity:1;stroke:none" d="M17.7929 5.20711C18.1834 4.81658 18.8166 4.81658 19.2071 5.20711C19.5976 5.59763 19.5976 6.2308 19.2071 6.62132L6.47919 19.3492C6.08866 19.7398 5.4555 19.7398 5.06497 19.3492C4.67445 18.9587 4.67445 18.3256 5.06497 17.935L17.7929 5.20711Z" class="ColorScheme-Text" filter="url(#glow)"/>
|
||||
</g>
|
||||
</svg>
|
||||
+14
-14
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Enums.BookLibrary;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
@@ -85,9 +85,9 @@ public class BookJsonConverter : JsonConverter<Book>
|
||||
contributorIds,
|
||||
ratings: ratings
|
||||
);
|
||||
return createBookResult.IsError
|
||||
? throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}")
|
||||
: createBookResult.Value;
|
||||
if (createBookResult.IsError)
|
||||
throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}");
|
||||
return createBookResult.Value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,9 +135,9 @@ public class BookJsonConverter : JsonConverter<Book>
|
||||
Optional<int>.FromNullable(pageCount)
|
||||
);
|
||||
|
||||
return metadataResult.IsError
|
||||
? throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}")
|
||||
: metadataResult.Value;
|
||||
if (metadataResult.IsError)
|
||||
throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}");
|
||||
return metadataResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -169,9 +169,9 @@ public class BookJsonConverter : JsonConverter<Book>
|
||||
Optional<string>.FromNullable(releaseVersion)
|
||||
);
|
||||
|
||||
return releaseInfoResult.IsError
|
||||
? throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}")
|
||||
: releaseInfoResult.Value;
|
||||
if (releaseInfoResult.IsError)
|
||||
throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}");
|
||||
return releaseInfoResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -217,9 +217,9 @@ public class BookJsonConverter : JsonConverter<Book>
|
||||
Optional<string>.FromNullable(nativeName)
|
||||
);
|
||||
|
||||
return languageInfoResult.IsError
|
||||
? throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}")
|
||||
: languageInfoResult.Value;
|
||||
if (languageInfoResult.IsError)
|
||||
throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}");
|
||||
return languageInfoResult.Value;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
@@ -280,4 +280,4 @@ public class BookJsonConverter : JsonConverter<Book>
|
||||
.ToList();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -21,7 +21,9 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
|
||||
if (request is Type type && type == typeof(DateOnly))
|
||||
return DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -21,7 +21,9 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
|
||||
if (request is Type type && type == typeof(DateOnly?))
|
||||
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Enums.BookLibrary;
|
||||
@@ -265,9 +265,9 @@ public class AddBookRequestFixture
|
||||
.RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.GoogleBooksId, f =>
|
||||
{
|
||||
const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(validChars, 12)
|
||||
.Select(s => s[f.Random.Number(validChars.Length - 1)])
|
||||
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(VALID_CHARS, 12)
|
||||
.Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])
|
||||
.ToArray());
|
||||
})
|
||||
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
|
||||
@@ -346,4 +346,4 @@ public class AddBookRequestFixture
|
||||
return input?.Length > maxLength ? input[..maxLength] : input;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -21,7 +21,9 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
|
||||
if (request is Type type && type == typeof(DateOnly))
|
||||
return DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -21,7 +21,9 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
|
||||
if (request is Type type && type == typeof(DateOnly?))
|
||||
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
@@ -263,9 +263,9 @@ public class AddBookCommandFixture
|
||||
.RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.GoogleBooksId, f =>
|
||||
{
|
||||
const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(validChars, 12)
|
||||
.Select(s => s[f.Random.Number(validChars.Length - 1)])
|
||||
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(VALID_CHARS, 12)
|
||||
.Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])
|
||||
.ToArray());
|
||||
})
|
||||
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
|
||||
@@ -344,4 +344,4 @@ public class AddBookCommandFixture
|
||||
return input?.Length > maxLength ? input[..maxLength] : input;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -21,7 +21,9 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
|
||||
if (request is Type type && type == typeof(DateOnly))
|
||||
return DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -21,7 +21,9 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen();
|
||||
if (request is Type type && type == typeof(DateOnly?))
|
||||
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+6
-5
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
@@ -10,6 +10,7 @@ using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -58,7 +59,7 @@ public class BookRepositoryTests
|
||||
result.Value.Should().Be(Result.Created);
|
||||
|
||||
// Check if the book was added to the context's ChangeTracker
|
||||
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
|
||||
EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
|
||||
addedBook.Should().NotBeNull();
|
||||
}
|
||||
@@ -99,7 +100,7 @@ public class BookRepositoryTests
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().Be(Result.Created);
|
||||
|
||||
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
|
||||
EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
|
||||
addedBook.Should().NotBeNull();
|
||||
BookModel addedBookEntity = addedBook!.Entity;
|
||||
@@ -126,7 +127,7 @@ public class BookRepositoryTests
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().Be(Result.Created);
|
||||
|
||||
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
|
||||
EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
|
||||
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
|
||||
addedBook.Should().NotBeNull();
|
||||
BookModel addedBookEntity = addedBook!.Entity;
|
||||
@@ -194,4 +195,4 @@ public class BookRepositoryTests
|
||||
retrievedBook.ISBNs.Should().HaveCount(2);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Enums.BookLibrary;
|
||||
@@ -137,9 +137,9 @@ public class BookModelFixture
|
||||
|
||||
private string CreateGoogleBooksId(Faker f)
|
||||
{
|
||||
const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(validChars, 12)
|
||||
.Select(s => s[f.Random.Number(validChars.Length - 1)])
|
||||
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(VALID_CHARS, 12)
|
||||
.Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
@@ -205,4 +205,4 @@ public class BookModelFixture
|
||||
));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user