diff --git a/.editorconfig b/.editorconfig index f50a0b25..b45eeb55 100644 --- a/.editorconfig +++ b/.editorconfig @@ -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 diff --git a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs index fb0d4e04..6f907331 100644 --- a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs +++ b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs @@ -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 : IPipelineBehavior errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage)); + List 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; diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index da1246f3..2c2b3de4 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -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<,>)); diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs index 86c64c3e..b303fec9 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs @@ -11,4 +11,5 @@ namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirector /// Query for retrieving the list of directories at a path. /// /// The path for which to retrieve the list of directories. -public record GetDirectoriesQuery(string Path) : IRequest>>; \ No newline at end of file +/// Whether to include hidden directories or not. +public record GetDirectoriesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index 5c8dec99..4c5c3360 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -43,7 +43,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _directoryService.GetSubdirectories(request.Path); + ErrorOr> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs index 436e035f..2142c2d6 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs @@ -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 /// /// The path for which to retrieve the tree of directories. /// Whether to include files in the directory tree or not. -public record GetDirectoryTreeQuery(string Path, bool IncludeFiles) : IRequest>>; \ No newline at end of file +/// Whether to include hidden files and directories or not. +public record GetDirectoryTreeQuery(string Path, bool IncludeFiles, bool IncludeHiddenElements) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs index d4c041f5..732c071a 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs @@ -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 pathParts = pathPartsResults.Value.ToList(); - string currentPath = pathParts[0].Name; ErrorOr> buildDirectoryTreeResult = BuildDirectoryTree(result, pathParts, out FileSystemTreeNodeResponse? currentNode); if (buildDirectoryTreeResult.IsError) return buildDirectoryTreeResult.Errors; // add subdirectories of the last directory node - ErrorOr loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles); - return loadChildrenResult.IsError ? (ErrorOr>)loadChildrenResult.Errors : (ErrorOr>)await ValueTask.FromResult(result); + ErrorOr loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles, request.IncludeHiddenElements); + if (loadChildrenResult.IsError) + return loadChildrenResult.Errors; + return await ValueTask.FromResult(result); } /// @@ -86,9 +87,9 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler> GetDrives() { ErrorOr> driveResult = _driveService.GetDrives(); - return driveResult.IsError - ? (ErrorOr>)driveResult.Errors - : ErrorOrFactory.From(driveResult.Value.Adapt>()); + if (driveResult.IsError) + return driveResult.Errors; + return ErrorOrFactory.From(driveResult.Value.Adapt>()); } /// @@ -102,7 +103,7 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler> BuildDirectoryTree(List drives, List 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 : IRequestHandlerThe directory node to load children for. /// Whether to include files in the directories or not. /// A result indicating a successful operation, or an error message. - private ErrorOr LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles) + private ErrorOr LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles, bool includeHiddenElements) { // get subdirectories under the current node's path - ErrorOr> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path); + ErrorOr> 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> filesResult = _fileService.GetFiles(node.Path); + ErrorOr> 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 /// The path for which to retrieve the list of directories. -public record GetTreeDirectoriesQuery(string Path) : IRequest>>; \ No newline at end of file +/// Whether to include hidden directories or not. +public record GetTreeDirectoriesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs index 39ab2617..9b63122a 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs @@ -43,7 +43,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _directoryService.GetSubdirectories(request.Path); + ErrorOr> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs index 89053ad0..8393d753 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs +++ b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs @@ -11,4 +11,5 @@ namespace Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; /// Query for retrieving the list of files at a path. /// /// The path for which to retrieve the list of files. -public record GetFilesQuery(string Path) : IRequest>>; \ No newline at end of file +/// Whether to include hidden files and directories or not. +public record GetFilesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs index cddf9b7d..2936b9aa 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs @@ -43,7 +43,7 @@ public class GetFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetFilesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _fileService.GetFiles(request.Path); + ErrorOr> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs index 1ecf8a65..7b9c7bc7 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs +++ b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs @@ -11,4 +11,5 @@ namespace Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; /// Query for retrieving the list of files at a path. /// /// The path for which to retrieve the list of files. -public record GetTreeFilesQuery(string Path) : IRequest>>; \ No newline at end of file +/// Whether to include hidden files and directories or not. +public record GetTreeFilesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index 3a7c9242..7d822f64 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -43,7 +43,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _fileService.GetFiles(request.Path); + ErrorOr> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index 8da44021..199eece2 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -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 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>> Handle(GetBooksQuery request, CancellationToken cancellationToken) { IBookRepository bookRepository = _unitOfWork.GetRepository(); - ErrorOr> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + ErrorOr> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); return getBooksResult.Match(values => ErrorOrFactory.From(values.Adapt>()), errors => errors); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index 30e80c26..4259b942 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -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(options => options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}")); + services.AddDbContext(options => + { + options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}"); + }); services.AddScoped(); Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes(); @@ -55,4 +58,4 @@ public static class DataAccessLayerServices } } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index bd7a110e..6d95f703 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -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 /// An representing either a successfull operation, or an error. public async Task> 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 -} \ No newline at end of file +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index e063843f..a5c321df 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -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>() - .ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly); + modelBuilder.Ignore>() + .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 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 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 -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs index 4ae81afd..bf950822 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs @@ -41,7 +41,9 @@ public class Genre : ValueObject /// public static ErrorOr Create(string name) { - return string.IsNullOrWhiteSpace(name) ? (ErrorOr)Errors.Errors.Metadata.GenreNameCannotBeEmpty : (ErrorOr)new Genre(name); + if (string.IsNullOrWhiteSpace(name)) + return Errors.Errors.Metadata.GenreNameCannotBeEmpty; + return new Genre(name); } /// @@ -59,4 +61,4 @@ public class Genre : ValueObject return Name; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs index a8808543..7f08462c 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs @@ -58,11 +58,13 @@ public class LanguageInfo : ValueObject /// public static ErrorOr Create(string languageCode, string languageName, Optional nativeName) { - return string.IsNullOrWhiteSpace(languageCode) - ? (ErrorOr)Errors.Errors.Metadata.LanguageCodeCannotBeEmpty - : string.IsNullOrWhiteSpace(languageName) - ? (ErrorOr)Errors.Errors.Metadata.LanguageNameCannotBeEmpty - : languageCode.Length != 2 ? (ErrorOr)Errors.Errors.Metadata.InvalidIsoCode : (ErrorOr)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); } /// @@ -82,4 +84,4 @@ public class LanguageInfo : ValueObject return $"{LanguageCode} - {LanguageName}"; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs index b7151d90..075f15c1 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs @@ -96,15 +96,15 @@ public class ReleaseInfo : ValueObject Optional releaseCountry, Optional releaseVersion) { - return originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value - ? (ErrorOr)Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch - : reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value - ? (ErrorOr)Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch - : originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value - ? (ErrorOr)Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate - : originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value - ? (ErrorOr)Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear - : (ErrorOr)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); } /// @@ -118,4 +118,4 @@ public class ReleaseInfo : ValueObject yield return ReleaseVersion; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs index 67cb76ea..bdc734cf 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs @@ -41,7 +41,9 @@ public class Tag : ValueObject /// public static ErrorOr Create(string name) { - return string.IsNullOrWhiteSpace(name) ? (ErrorOr)Errors.Errors.Metadata.TagNameCannotBeEmpty : (ErrorOr)new Tag(name); + if (string.IsNullOrWhiteSpace(name)) + return Errors.Errors.Metadata.TagNameCannotBeEmpty; + return new Tag(name); } /// @@ -59,4 +61,4 @@ public class Tag : ValueObject return Name; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs index ac7de505..80f8fc71 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs @@ -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 setStatusResult = newDirectory.SetStatus(status); - return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newDirectory; + if (setStatusResult.IsError) + return setStatusResult.Errors; + return newDirectory; } /// @@ -107,7 +109,9 @@ public sealed class Directory : FileSystemItem dateCreated, dateModified); ErrorOr setStatusResult = newDirectory.SetStatus(status); - return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newDirectory; + if (setStatusResult.IsError) + return setStatusResult.Errors; + return newDirectory; } /// @@ -143,4 +147,4 @@ public sealed class Directory : FileSystemItem return Result.Updated; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs index df9ce2b1..1be10f2f 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs @@ -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 setStatusResult = newFile.SetStatus(status); - return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newFile; + if (setStatusResult.IsError) + return setStatusResult.Errors; + return newFile; } /// @@ -112,7 +114,9 @@ public sealed class File : FileSystemItem dateModified, size); ErrorOr setStatusResult = newFile.SetStatus(status); - return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newFile; + if (setStatusResult.IsError) + return setStatusResult.Errors; + return newFile; } /// @@ -150,4 +154,4 @@ public sealed class File : FileSystemItem return Result.Updated; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs index 8054bbbc..7a2216c1 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs @@ -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 setStatusResult = newRoot.SetStatus(status); - return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newRoot; + if (setStatusResult.IsError) + return setStatusResult.Errors; + return newRoot; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs index 2dbdc9cf..f862ebca 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs @@ -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 setStatusResult = newRoot.SetStatus(status); - return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newRoot; + if (setStatusResult.IsError) + return setStatusResult.Errors; + return newRoot; } /// @@ -81,7 +83,9 @@ public sealed class WindowsRootItem : FileSystemItem id, name); ErrorOr setStatusResult = newFile.SetStatus(status); - return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newFile; + if (setStatusResult.IsError) + return setStatusResult.Errors; + return newFile; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs index 0d08904d..5d02fcb5 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs @@ -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. /// /// The path from which to retrieve the subdirectory paths. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of directory paths or an error. - public ErrorOr> GetSubdirectoryPaths(FileSystemPathId path) + public ErrorOr> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false) - ? (ErrorOr>)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()); } + /// + /// Gets the attributes of a file system item identified by . + /// + /// The path for which to retrieve the file system attributes. + /// The retrieved file system attributes. + private FileAttributes GetAttributes(string path) + { + try + { + // File.GetAttributes is used for both directories and files + return _fileSystem.File.GetAttributes(path); + } + catch + { + return default; + } + } + /// /// Checks if a directory with the specified path exists. /// @@ -85,9 +106,9 @@ internal class DirectoryProviderService : IDirectoryProviderService public ErrorOr> GetLastWriteTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false) - ? (ErrorOr>)Errors.Permission.UnauthorizedAccess - : (ErrorOr>)Optional.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path)); + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) + return Errors.Permission.UnauthorizedAccess; + return Optional.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path)); } /// @@ -98,9 +119,9 @@ internal class DirectoryProviderService : IDirectoryProviderService public ErrorOr> GetCreationTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false) - ? (ErrorOr>)Errors.Permission.UnauthorizedAccess - : (ErrorOr>)Optional.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path)); + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) + return Errors.Permission.UnauthorizedAccess; + return Optional.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path)); } /// @@ -302,4 +323,4 @@ internal class DirectoryProviderService : IDirectoryProviderService return Result.Deleted; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs index 472e291c..5582c26b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs @@ -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. /// /// String representation of the file path. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public ErrorOr> GetSubdirectories(string path) + public ErrorOr> GetSubdirectories(string path, bool includeHiddenElements) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError ? (ErrorOr>)fileSystemPathIdResult.Errors : GetSubdirectories(fileSystemPathIdResult.Value); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements); } /// /// Retrieves subdirectories for the given directory. /// /// Directory object to retrieve subdirectories for. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public ErrorOr> GetSubdirectories(Directory directory) + public ErrorOr> GetSubdirectories(Directory directory, bool includeHiddenElements) { - return GetSubdirectories(directory.Id); + return GetSubdirectories(directory.Id, includeHiddenElements); } /// /// Retrieves subdirectories for the specified file system path. /// /// Identifier for the file path. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public ErrorOr> GetSubdirectories(FileSystemPathId path) + public ErrorOr> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements) { // retrieve the list of subdirectories - ErrorOr> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path); + ErrorOr> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements); if (subdirectoryPathsResult.IsError) return subdirectoryPathsResult.Errors; List result = []; - IEnumerable subdirectoryPaths = subdirectoryPathsResult.Value; - foreach (FileSystemPathId subPath in subdirectoryPaths) + foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value) { // extract directory details ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath); @@ -111,7 +115,9 @@ public class DirectoryService : IDirectoryService public ErrorOr CreateDirectory(string path, string name) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : CreateDirectory(fileSystemPathIdResult.Value, name); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return CreateDirectory(fileSystemPathIdResult.Value, name); } /// @@ -149,7 +155,9 @@ public class DirectoryService : IDirectoryService if (errorDirResult.IsError) return errorDirResult.Errors; ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - return setStatusResult.IsError ? (ErrorOr)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 fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); - return fileSystemDestinationPathIdResult.IsError - ? (ErrorOr)fileSystemDestinationPathIdResult.Errors - : CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -220,9 +228,9 @@ public class DirectoryService : IDirectoryService if (fileSystemSourcePathIdResult.IsError) return fileSystemSourcePathIdResult.Errors; ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); - return fileSystemDestinationPathIdResult.IsError - ? (ErrorOr)fileSystemDestinationPathIdResult.Errors - : MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -257,7 +265,9 @@ public class DirectoryService : IDirectoryService public ErrorOr RenameDirectory(string path, string name) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : RenameDirectory(fileSystemPathIdResult.Value, name); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return RenameDirectory(fileSystemPathIdResult.Value, name); } /// @@ -295,7 +305,9 @@ public class DirectoryService : IDirectoryService if (errorDirResult.IsError) return errorDirResult.Errors; ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - return setStatusResult.IsError ? (ErrorOr)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 DeleteDirectory(string path) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : DeleteDirectory(fileSystemPathIdResult.Value); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return DeleteDirectory(fileSystemPathIdResult.Value); } /// @@ -323,4 +337,4 @@ public class DirectoryService : IDirectoryService return _environmentContext.DirectoryProviderService.DeleteDirectory(path); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs index dc66ad92..76bc457b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs @@ -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 unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible); - return unixRootResult.IsError ? (ErrorOr>)unixRootResult.Errors : (ErrorOr>)new List() { unixRootResult.Value }; + if (unixRootResult.IsError) + return unixRootResult.Errors; + return new List() { unixRootResult.Value }; } else return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives() @@ -63,4 +65,4 @@ public class DriveService : IDriveService .AsEnumerable()); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs index 3f5f0182..c8f96aff 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs @@ -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. /// /// The path for which to retrieve the list of files. + /// Whether to include hidden files or not. /// An containing either a collection of file paths or an error. - public ErrorOr> GetFilePaths(FileSystemPathId path) + public ErrorOr> GetFilePaths(FileSystemPathId path, bool includeHiddenElements) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory) - ? (ErrorOr>)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()); } + /// + /// Gets the attributes of a file system item identified by . + /// + /// The path for which to retrieve the file system attributes. + /// The retrieved file system attributes. + private FileAttributes GetAttributes(string path) + { + try + { + // File.GetAttributes is used for both directories and files + return _fileSystem.File.GetAttributes(path); + } + catch + { + return default; + } + } + /// /// Checks if a file with the specified path exists. /// @@ -82,9 +103,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr GetFileAsync(FileSystemPathId path) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents) - ? (ErrorOr)Errors.Permission.UnauthorizedAccess - : (ErrorOr)System.IO.File.ReadAllBytes(path.Path); + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) + return Errors.Permission.UnauthorizedAccess; + return System.IO.File.ReadAllBytes(path.Path); } /// @@ -95,9 +116,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr> GetLastWriteTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties) - ? (ErrorOr>)Errors.Permission.UnauthorizedAccess - : (ErrorOr>)Optional.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path)); + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) + return Errors.Permission.UnauthorizedAccess; + return Optional.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path)); } /// @@ -108,9 +129,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr> GetCreationTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties) - ? (ErrorOr>)Errors.Permission.UnauthorizedAccess - : (ErrorOr>)Optional.FromNullable(_fileSystem.File.GetCreationTime(path.Path)); + if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) + return Errors.Permission.UnauthorizedAccess; + return Optional.FromNullable(_fileSystem.File.GetCreationTime(path.Path)); } /// @@ -121,9 +142,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr GetSize(FileSystemPathId path) { // check if the user has access permissions to the provided path - return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties) - ? (ErrorOr)Errors.Permission.UnauthorizedAccess - : (ErrorOr)(_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; } /// @@ -265,4 +286,4 @@ internal class FileProviderService : IFileProviderService return Result.Deleted; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs index 24670a41..82b66d63 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs @@ -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. /// /// String representation of the file path. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public ErrorOr> GetFiles(string path) + public ErrorOr> GetFiles(string path, bool includeHiddenElements) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError ? (ErrorOr>)fileSystemPathIdResult.Errors : GetFiles(fileSystemPathIdResult.Value); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements); } /// /// Retrieves files associated with a given file. /// /// The file object. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public ErrorOr> GetFiles(File file) + public ErrorOr> GetFiles(File file, bool includeHiddenElements) { - return GetFiles(file.Id); + return GetFiles(file.Id, includeHiddenElements); } /// /// Retrieves files for a specified file path Id. /// /// Identifier for the file path. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public ErrorOr> GetFiles(FileSystemPathId path) + public ErrorOr> GetFiles(FileSystemPathId path, bool includeHiddenElements) { // retrieve the list of files - ErrorOr> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path); + ErrorOr> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements); if (filePathsResult.IsError) return filePathsResult.Errors; List result = []; @@ -119,9 +124,9 @@ public class FileService : IFileService if (fileSystemSourcePathIdResult.IsError) return fileSystemSourcePathIdResult.Errors; ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); - return fileSystemDestinationPathIdResult.IsError - ? (ErrorOr)fileSystemDestinationPathIdResult.Errors - : CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -158,7 +163,9 @@ public class FileService : IFileService if (errorFileResult.IsError) return errorFileResult.Errors; ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - return setStatusResult.IsError ? (ErrorOr)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 fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); - return fileSystemDestinationPathIdResult.IsError - ? (ErrorOr)fileSystemDestinationPathIdResult.Errors - : MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + if (fileSystemDestinationPathIdResult.IsError) + return fileSystemDestinationPathIdResult.Errors; + return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -220,7 +227,9 @@ public class FileService : IFileService if (errorFileResult.IsError) return errorFileResult.Errors; ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - return setStatusResult.IsError ? (ErrorOr)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 RenameFile(string path, string name) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : RenameFile(fileSystemPathIdResult.Value, name); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return RenameFile(fileSystemPathIdResult.Value, name); } /// @@ -276,7 +287,9 @@ public class FileService : IFileService if (errorFileResult.IsError) return errorFileResult.Errors; ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - return setStatusResult.IsError ? (ErrorOr)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 DeleteFile(string path) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : DeleteFile(fileSystemPathIdResult.Value); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return DeleteFile(fileSystemPathIdResult.Value); } /// @@ -309,4 +324,4 @@ public class FileService : IFileService return true; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs index 249643bf..4e2309d8 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs @@ -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.SVG - : IsTga(buffer.ToArray()) ? (ErrorOr)ImageType.TGA : (ErrorOr)ImageType.None; + if (IsSvg(content, path.Path)) + return ImageType.SVG; + else if (IsTga(buffer.ToArray())) + return ImageType.TGA; + else + return ImageType.None; } /// @@ -154,4 +157,4 @@ public class FileTypeService : IFileTypeService return ImageType.None; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs index c9b72796..a59d5e7e 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs @@ -18,8 +18,9 @@ public interface IDirectoryProviderService /// Retrieves a list of subdirectory paths from the specified path. /// /// The path from which to retrieve the subdirectory paths. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of directory paths or an error. - ErrorOr> GetSubdirectoryPaths(FileSystemPathId path); + ErrorOr> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements); /// /// Checks if a directory with the specified path exists. @@ -91,4 +92,4 @@ public interface IDirectoryProviderService /// An containing either the result of deleting a directory, or an error. ErrorOr DeleteDirectory(FileSystemPathId path); #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs index dff966f3..b8451191 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs @@ -17,22 +17,25 @@ public interface IDirectoryService /// Retrieves subdirectories for the specified string path. /// /// String representation of the file path. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - ErrorOr> GetSubdirectories(string path); + ErrorOr> GetSubdirectories(string path, bool includeHiddenElements); /// /// Retrieves subdirectories for the given directory. /// /// Directory object to retrieve subdirectories for. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - ErrorOr> GetSubdirectories(Directory directory); + ErrorOr> GetSubdirectories(Directory directory, bool includeHiddenElements); /// /// Retrieves subdirectories for the specified file system path. /// /// Identifier for the file path. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - ErrorOr> GetSubdirectories(FileSystemPathId path); + ErrorOr> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements); /// /// Creates a directory with the specified , at the specified . @@ -75,4 +78,4 @@ public interface IDirectoryService /// An containing either the result of deleting a directory, or an error. ErrorOr DeleteDirectory(string path); #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs index 1dee213d..328b037b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs @@ -18,8 +18,9 @@ public interface IFileProviderService /// Retrieves a list of files at the specified path. /// /// The path for which to retrieve the list of files. + /// Whether to include hidden files or not. /// An containing either a collection of file paths, or an error. - ErrorOr> GetFilePaths(FileSystemPathId path); + ErrorOr> GetFilePaths(FileSystemPathId path, bool includeHiddenElements); /// /// Retrieves the contents of a file at the specified path. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs index b54932f0..cc7dd765 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs @@ -17,22 +17,25 @@ public interface IFileService /// Retrieves files for the specified string path. /// /// String representation of the file path. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - ErrorOr> GetFiles(string path); + ErrorOr> GetFiles(string path, bool includeHiddenElements); /// /// Retrieves files associated with a given file. /// /// The file object. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - ErrorOr> GetFiles(File file); + ErrorOr> GetFiles(File file, bool includeHiddenElements); /// /// Retrieves files for a specified file path ID. /// /// Identifier for the file path. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - ErrorOr> GetFiles(FileSystemPathId path); + ErrorOr> GetFiles(FileSystemPathId path, bool includeHiddenElements); /// /// Copies a file located at to . diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs index cb017401..b3507eec 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs @@ -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 newPathResult = FileSystemPathId.Create(path); - return !newPathResult.IsError && _platformContext.PathStrategy.IsValidPath(newPathResult.Value); + if (newPathResult.IsError) + return false; + return _platformContext.PathStrategy.IsValidPath(newPathResult.Value); } /// @@ -54,7 +56,9 @@ public class PathService : IPathService public bool Exists(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - return !newPathResult.IsError && _platformContext.PathStrategy.Exists(newPathResult.Value); + if (newPathResult.IsError) + return false; + return _platformContext.PathStrategy.Exists(newPathResult.Value); } /// @@ -69,7 +73,9 @@ public class PathService : IPathService if (newPathResult.IsError) return newPathResult.Errors; ErrorOr combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name); - return combinedPathResult.IsError ? (ErrorOr)combinedPathResult.Errors : (ErrorOr)combinedPathResult.Value.Path; + if (combinedPathResult.IsError) + return combinedPathResult.Errors; + return combinedPathResult.Value.Path; } /// @@ -80,7 +86,9 @@ public class PathService : IPathService public ErrorOr> ParsePath(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : _platformContext.PathStrategy.ParsePath(newPathResult.Value); + if (newPathResult.IsError) + return newPathResult.Errors; + return _platformContext.PathStrategy.ParsePath(newPathResult.Value); } /// @@ -91,7 +99,9 @@ public class PathService : IPathService public ErrorOr> GoUpOneLevel(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value); + if (newPathResult.IsError) + return newPathResult.Errors; + return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value); } /// @@ -111,7 +121,9 @@ public class PathService : IPathService public ErrorOr GetPathRoot(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - return newPathResult.IsError ? (ErrorOr)newPathResult.Errors : _platformContext.PathStrategy.GetPathRoot(newPathResult.Value); + if (newPathResult.IsError) + return newPathResult.Errors; + return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs index bfacbd7c..adf18776 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs @@ -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> GetThumbnailAsync(string path, int quality) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - return fileSystemPathIdResult.IsError - ? (ErrorOr)fileSystemPathIdResult.Errors - : await GetThumbnailAsync(fileSystemPathIdResult.Value, quality); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality); } /// @@ -187,4 +187,4 @@ public class ThumbnailService : IThumbnailService return ((value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource)) + fromTarget; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs index fe6568cc..b79b8028 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs @@ -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 -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs index 187d5856..b69d2e2a 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -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 newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); - return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : ParsePath(newPathResult.Value); + if (newPathResult.IsError) + return newPathResult.Errors; + return ParsePath(newPathResult.Value); } /// @@ -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)new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true) - : (ErrorOr)Errors.FileManagement.InvalidPath; + if (path.Path.StartsWith(PathSeparator)) + return new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true); + return Errors.FileManagement.InvalidPath; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index e6237684..78981aeb 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -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> 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>)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 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 newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]); - return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : ParsePath(newPathResult.Value); + if (newPathResult.IsError) + return newPathResult.Errors; + return ParsePath(newPathResult.Value); } /// @@ -181,4 +183,4 @@ public class WindowsPathStrategy : IWindowsPathStrategy return Errors.FileManagement.InvalidPath; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs index 0b418a1d..4df03714 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs @@ -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 /// public static ErrorOr Create(string path) { - return string.IsNullOrWhiteSpace(path) ? (ErrorOr)Errors.FileManagement.InvalidPath : (ErrorOr)new FileSystemPathId(path); + if (string.IsNullOrWhiteSpace(path)) + return Errors.FileManagement.InvalidPath; + return new FileSystemPathId(path); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs index c4aa295f..681258ca 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs @@ -115,13 +115,13 @@ public class StreamInfo : ValueObject Optional sampleRate, Optional channels) { - return streamId is null - ? (ErrorOr)Errors.FileManagement.StreamIdCannotBeEmpty - : codec is null - ? (ErrorOr)Errors.FileManagement.CodecCannotBeEmpty - : bitrate <= 0 - ? (ErrorOr)Errors.FileManagement.BitrateMustBeAPositiveNumber - : (ErrorOr)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); } /// @@ -137,4 +137,4 @@ public class StreamInfo : ValueObject yield return Channels; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs index 6b54dc6f..fa45b84d 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs @@ -51,9 +51,11 @@ public class BookRating : Rating /// public static ErrorOr Create(decimal value, decimal maxValue, Optional source, Optional voteCount) { - return maxValue < 0 || value < 0 - ? (ErrorOr)Errors.Metadata.RatingValueMustBePositive - : value > maxValue ? (ErrorOr)Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue : (ErrorOr)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); } /// @@ -79,4 +81,4 @@ public class BookRating : Rating return baseString; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs index 95a6f82f..a2203d4b 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs @@ -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 /// if the ISBN-10 is valid, otherwise. 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 /// if the ISBN-13 is valid, otherwise. 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 -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs index e489b82f..2adec962 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs @@ -88,15 +88,15 @@ public class WrittenContentMetadata : BaseMetadata Optional publisher, Optional pageCount) { - return string.IsNullOrWhiteSpace(title) - ? (ErrorOr)Errors.Metadata.TitleCannotBeEmpty - : releaseInfo is null - ? (ErrorOr)Errors.Metadata.ReleaseInfoCannotBeNull - : genres is null - ? (ErrorOr)Errors.Metadata.GenresListCannotBeNull - : tags is null - ? (ErrorOr)Errors.Metadata.TagsListCannotBeNull - : (ErrorOr)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 -} \ No newline at end of file +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index 82df2fde..ff0fe09d 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -34,13 +34,13 @@ public static class SharedConfiguration // bind the common settings section services.AddOptions() - .Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName)) + .Bind(configuration.GetRequiredSection(CommonSettingsModel.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); // bind the database connection string section services.AddOptions() - .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName)) + .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); return services; diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/CommonSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/CommonSettingsModel.cs index c19ec636..deb90bcd 100644 --- a/src/Lumina.Infrastructure/Common/Models/Configuration/CommonSettingsModel.cs +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/CommonSettingsModel.cs @@ -1,12 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + namespace Lumina.Infrastructure.Common.Models.Configuration; /// /// Model for deserializing shared application configuration settings. /// +[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 /// public required string Theme { get; init; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/DatabaseSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/DatabaseSettingsModel.cs index 8fe6022d..7b68b6a5 100644 --- a/src/Lumina.Infrastructure/Common/Models/Configuration/DatabaseSettingsModel.cs +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/DatabaseSettingsModel.cs @@ -1,12 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + namespace Lumina.Infrastructure.Common.Models.Configuration; /// /// Model for deserializing database configuration settings. /// +[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 /// public required string DefaultConnection { get; init; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index ea78865b..e2f35781 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -25,11 +25,14 @@ public static class PresentationApiLayerServices /// The updated . 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 -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs index ed715fb9..6831a32d 100644 --- a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs +++ b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs @@ -116,11 +116,9 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory List? errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List; // 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 -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs index 167b6b2e..c9cbc22b 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs @@ -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 , with the additional list of drives, and children of the last child directory. /// /// The path for which to get the directory tree. + /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. [HttpGet("get-directory-tree")] - public async IAsyncEnumerable GetDirectoryTree([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] bool includeFiles, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable GetDirectoryTree([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, + [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { - ErrorOr> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles), cancellationToken).ConfigureAwait(false); + ErrorOr> 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 . /// /// The path for which to get the directories. + /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. [HttpGet("get-tree-directories")] - public async IAsyncEnumerable GetTreeDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable GetTreeDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, + [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { - ErrorOr> result = await _mediator.Send(new GetTreeDirectoriesQuery(path), cancellationToken).ConfigureAwait(false); + ErrorOr> 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 . /// /// The path for which to get the directories. + /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. [HttpGet("get-directories")] - public async IAsyncEnumerable GetDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable GetDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, + [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { - ErrorOr> result = await _mediator.Send(new GetDirectoriesQuery(path), cancellationToken).ConfigureAwait(false); + ErrorOr> 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 -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs index fc3551c3..e6fb4c7a 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs @@ -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 GetDrives(CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); - return result.Match(Ok, Problem); + return result.Match(result => Ok(result), errors => Problem(errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs index 73a02faf..fbeb2a0b 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs @@ -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 class. /// /// Injected service for mediating commands and queries. - public FilesController(ISender mediator, IMapper mapper) + public FilesController(ISender mediator) { _mediator = mediator; } @@ -42,11 +42,13 @@ public class FilesController : ApiController /// Gets the files of . /// /// The path for which to get the files. + /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. [HttpGet("get-tree-files")] - public async IAsyncEnumerable GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, + [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { - ErrorOr> result = await _mediator.Send(new GetTreeFilesQuery(path), cancellationToken).ConfigureAwait(false); + ErrorOr> 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 . /// /// The path for which to get the files. + /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. [HttpGet("get-files")] - public async IAsyncEnumerable GetFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken) + public async IAsyncEnumerable GetFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, + [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { - ErrorOr> result = await _mediator.Send(new GetFilesQuery(path), cancellationToken).ConfigureAwait(false); + ErrorOr> 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 -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs index ee7a8858..5e61f9ca 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs @@ -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 GetPathRoot([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) { ErrorOr result = await _mediator.Send(new GetPathRootQuery(path), cancellationToken).ConfigureAwait(false); - return result.Match(Ok, Problem); + return result.Match(result => Ok(result), errors => Problem(errors)); } /// @@ -74,7 +74,7 @@ public class PathController : ApiController public async Task GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false); - return result.Match(Ok, Problem); + return result.Match(result => Ok(result), errors => Problem(errors)); } /// @@ -87,7 +87,7 @@ public class PathController : ApiController public async Task CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken) { ErrorOr 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)); } /// @@ -99,7 +99,7 @@ public class PathController : ApiController public async Task SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false); - return result.Match(Ok, Problem); + return result.Match(result => Ok(result), errors => Problem(errors)); } /// @@ -126,4 +126,4 @@ public class PathController : ApiController return Ok(result); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs b/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs index 105ca527..76f64894 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs @@ -44,7 +44,7 @@ public class BooksController : ApiController public async Task GetBooks() { ErrorOr.ErrorOr> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false); - return result.Match(Ok, Problem); + return result.Match(result => Ok(result), errors => Problem(errors)); } /// @@ -58,4 +58,4 @@ public class BooksController : ApiController return result.Match(result => Created($"/api/v1/books/{result.Id}", result), Problem); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index c545cec5..eb7095fa 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -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(stream, _jsonOptions, cancellationToken).ConfigureAwait(false)) { @@ -215,4 +216,4 @@ public class ApiHttpClient : IApiHttpClient } } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs index fc07f3d9..73e4a8bb 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -37,7 +37,7 @@ internal static class PresentationWebLayerConfiguration internal static IServiceCollection BindConfiguration(this IServiceCollection serviceCollection, IConfiguration configuration) { serviceCollection.AddOptions() - .Bind(configuration.GetRequiredSection(ServerConfigurationModel.SectionName)) + .Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); return serviceCollection; diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 0b854e36..569cde7c 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -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(ServiceLifetime.Singleton); // handle transient errors like network timeouts or intermittent failures - Polly.Retry.AsyncRetryPolicy retryPolicy = Policy + AsyncRetryPolicy retryPolicy = Policy .Handle() .OrResult(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 circuitBreakerPolicy = Policy + AsyncCircuitBreakerPolicy circuitBreakerPolicy = Policy .Handle() .OrResult(r => r.StatusCode == HttpStatusCode.InternalServerError) .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30)); - Polly.Wrap.AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); + AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); // register the typed client used for the API interaction services.AddHttpClient() @@ -57,4 +60,4 @@ public static class PresentationWebLayerServices return services; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Configuration/ServerConfigurationModel.cs b/src/Lumina.Presentation.Web/Common/Models/Configuration/ServerConfigurationModel.cs index 1602a3ef..9256e530 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Configuration/ServerConfigurationModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Configuration/ServerConfigurationModel.cs @@ -7,11 +7,11 @@ namespace Lumina.Presentation.Web.Common.Models.Configuration; /// /// Model for deserializing server configuration settings. /// -[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 /// public required ushort Port { get; init; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor index 0b3c702b..1d7e63b7 100644 --- a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor +++ b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor @@ -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 @@ Toggle Tree View Toggle Thumbnails - Toggle Hidden Files - @* Toggle Selection Mode *@ + @* Toggle Hidden Files *@ - - - - - + + Toggle Hidden Files @@ -60,7 +56,8 @@ - + + @@ -70,7 +67,44 @@ - + + + + + + + + + + + + + + Toggle Selection Mode + + + + + + + + + + + + + + + + + + + + + + + + @@ -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($"directories/get-tree-directories?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false)) + await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"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($"files/get-tree-files?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false)) + await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"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 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($"directories/get-tree-directories?path={Uri.EscapeDataString(concatenatedPath)}").ConfigureAwait(false)) + await foreach (FileSystemTreeNodeModel? directory in _apiHttpClient.GetAsyncEnumerable($"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 initialTree = await _apiHttpClient.GetAsync>($"directories/get-directory-tree?path={Uri.EscapeDataString(path!)}&includeFiles={IncludeFiles}").ConfigureAwait(false); + List initialTree = await _apiHttpClient.GetAsync>($"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($"directories/get-directories?path={Uri.EscapeDataString(path)}").ConfigureAwait(false)) + await foreach (DirectoryModel? directory in _apiHttpClient.GetAsyncEnumerable($"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($"files/get-files?path={Uri.EscapeDataString(path)}").ConfigureAwait(false)) + await foreach (FileModel? file in _apiHttpClient.GetAsyncEnumerable($"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); } + /// + /// Enables or disables the display of hidden file system files and directories. + /// + 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); + } + } + /// /// Handles API exceptions, presenting standard problem details in a user friendly way. /// @@ -820,4 +869,4 @@ { reference?.Dispose(); } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index 4e026534..8b67e9a3 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -21,5 +21,10 @@ - + + + + + $(NoWarn);TS6385 + diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/toggle-hidden.svg b/src/Lumina.Presentation.Web/wwwroot/images/ui/toggle-hidden.svg deleted file mode 100644 index 807c69db..00000000 --- a/src/Lumina.Presentation.Web/wwwroot/images/ui/toggle-hidden.svg +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs index a72a7818..75b1d169 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs @@ -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 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 Optional.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; } /// @@ -169,9 +169,9 @@ public class BookJsonConverter : JsonConverter Optional.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; } /// @@ -217,9 +217,9 @@ public class BookJsonConverter : JsonConverter Optional.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 .ToList(); } #endregion -} \ No newline at end of file +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs index 39cd2e8e..2b65a9c8 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs @@ -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 /// A specimen based on the request. 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 -} \ No newline at end of file +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs index 5fbe4bf7..e30282ea 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -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 /// A specimen based on the request. 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 -} \ No newline at end of file +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs index a3f28c9a..74cbe17b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs @@ -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 -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs index 50721b0b..161dedb1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs @@ -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 /// A specimen based on the request. 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 -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs index c754ba23..3d66c55f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -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 /// A specimen based on the request. 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 -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs index b6d47f58..ff53ffba 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs @@ -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 -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs index 948aae55..7295612e 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs @@ -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 /// A specimen based on the request. 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 -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs index e83daf4f..bd0813c5 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -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 /// A specimen based on the request. 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 -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index 3402e242..9fcd67fc 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -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? addedBook = _mockContext.ChangeTracker.Entries() + EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .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? addedBook = _mockContext.ChangeTracker.Entries() + EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .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? addedBook = _mockContext.ChangeTracker.Entries() + EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .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 -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs index 422ea5fa..f95c404e 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs @@ -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 -} \ No newline at end of file +}