Adds editorconfig and refactors to the established rules

This commit is contained in:
BinaryAlley committed 2024-09-23 16:48:48 +03:00
1 parent 712a0f2b27
commit cd44f11d9e
126 files changed
+1449 -1279

No files matched your search

+326
View File
@@ -0,0 +1,326 @@
root = true
#### Core EditorConfig Options ####
[*]
# Indentation and spacing
indent_size = 4
indent_style = space
tab_width = 4
# New line preferences
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_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,}]
charset = utf-8
#### .NET Coding Conventions ####
[*.cs]
# Organize usings
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = false
# this. and Me. preferences
dotnet_style_qualification_for_event = false:silent
dotnet_style_qualification_for_field = false:silent
dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_property = false:silent
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:warning
dotnet_style_predefined_type_for_member_access = true:warning
# Parentheses preferences
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_other_operators = never_if_unnecessary:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning
# Expression-level preferences
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_null_propagation = true:warning
dotnet_style_object_initializer = true:suggestion
dotnet_style_prefer_auto_properties = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
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
# Field preferences
dotnet_style_readonly_field = true:error
# Parameter preferences
dotnet_code_quality_unused_parameters = all:warning
# Strings
csharp_style_prefer_string_interpolation = true:suggestion
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere = false:error # var should only be used with anonymous types, and target-typed new expression is encouraged
csharp_style_var_for_built_in_types = false:error
csharp_style_var_when_type_is_apparent = false:error
# Expression-bodied members
csharp_style_expression_bodied_accessors = false:error
csharp_style_expression_bodied_constructors = false:error
csharp_style_expression_bodied_indexers = false:error
csharp_style_expression_bodied_lambdas = true:suggestion # lamdas don't always require block bodies and explicit return
csharp_style_expression_bodied_local_functions = false:error
csharp_style_expression_bodied_methods = false:error
csharp_style_expression_bodied_operators = false:error
csharp_style_expression_bodied_properties = when_on_single_line:suggestion # domain error properties are allowed to have this style
# Pattern Matching
csharp_style_pattern_matching_over_as_with_null_check = true:warning
csharp_style_pattern_matching_over_is_with_cast_check = true:warning
# "Null" checking preferences
csharp_style_conditional_delegate_call = true:warning
# Modifier preferences
csharp_prefer_static_local_function = true:suggestion
csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async:error
# Code-block preferences
csharp_prefer_braces = false:error # vertical scope space is vital for code readability, single conditional and iterative expressions waste it up
csharp_prefer_simple_using_statement = false:error # explicit using blocks provide clearer scope control and consistent disposal timing in local scope
# Expression-level preferences
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:suggestion
csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_range_operator = true:suggestion
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
csharp_style_unused_value_expression_statement_preference = discard_variable:silent
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:silent
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_catch = true
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = false
#### Naming styles ####
# Naming rules
# Interfaces should begin with an I and be PascalCase
dotnet_naming_rule.interface_should_be_begins_with_i.severity = error
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = interface_style
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_style.interface_style.required_prefix = I
dotnet_naming_style.interface_style.required_suffix =
dotnet_naming_style.interface_style.word_separator =
dotnet_naming_style.interface_style.capitalization = pascal_case
# Types should be PascalCase
dotnet_naming_rule.types_should_be_pascal_case.severity = error
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = non_private_static_field_style
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_style.types_style.capitalization = pascal_case
# Non Field members should be PascalCase
dotnet_naming_rule.non_field_members_should_be_camel_case.severity = error
dotnet_naming_rule.non_field_members_should_be_camel_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_camel_case.style = non_private_static_field_style
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.non_field_members.required_modifiers =
dotnet_naming_style.non_field_members_style.capitalization = pascal_case
# Non-private static fields are camel_case
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = error
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style
dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field
dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected internal, private protected
dotnet_naming_symbols.non_private_static_fields.required_modifiers = static
dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case
# Constants are UPPER_CASE
dotnet_naming_rule.constants_should_be_pascal_case.severity = error
dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants
dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style
dotnet_naming_symbols.constants.applicable_kinds = field, local
dotnet_naming_symbols.constants.required_modifiers = const
dotnet_naming_style.constant_style.capitalization = all_upper
dotnet_naming_style.constant_style.word_separator = _
# Static fields are PascalCase and start with s_
dotnet_naming_rule.static_fields_should_be_pascal_case.severity = error
dotnet_naming_rule.static_fields_should_be_pascal_case.symbols = static_fields
dotnet_naming_rule.static_fields_should_be_pascal_case.style = static_field_style
dotnet_naming_symbols.static_fields.applicable_kinds = field
dotnet_naming_symbols.static_fields.required_modifiers = static
dotnet_naming_style.static_field_style.capitalization = pascal_case
dotnet_naming_style.static_field_style.required_prefix = s_ # static members should immediately distinguish themselves from other members
# Local variables should be camelCase
dotnet_naming_rule.camel_case_for_local_variables.severity = error
dotnet_naming_rule.camel_case_for_local_variables.symbols = local_variables
dotnet_naming_rule.camel_case_for_local_variables.style = parameter_style
dotnet_naming_symbols.local_variables.applicable_kinds = local
dotnet_naming_style.local_variables_style.capitalization = camel_case
# Parameters should be camelCase
dotnet_naming_rule.parameters_should_be_prefixed.severity = error
dotnet_naming_rule.parameters_should_be_prefixed.symbols = parameters
dotnet_naming_rule.parameters_should_be_prefixed.style = parameter_style
dotnet_naming_symbols.parameters.applicable_kinds = parameter
dotnet_naming_style.parameter_style.capitalization = camel_case
# Local functions are PascalCase
dotnet_naming_rule.local_functions_should_be_pascal_case.severity = error
dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions
dotnet_naming_rule.local_functions_should_be_pascal_case.style = non_private_static_field_style
dotnet_naming_symbols.local_functions.applicable_kinds = local_function
dotnet_naming_style.local_function_style.capitalization = pascal_case
# readonly fields are camelCase and they begin with underscore
dotnet_naming_symbols.readonly_fields.applicable_kinds = field
dotnet_naming_symbols.readonly_fields.required_modifiers = readonly
dotnet_naming_style.underscore_camel_case_style.capitalization = camel_case
dotnet_naming_style.underscore_camel_case_style.required_prefix = _
dotnet_naming_rule.readonly_fields_should_be_underscore_camel_case.symbols = readonly_fields
dotnet_naming_rule.readonly_fields_should_be_underscore_camel_case.style = underscore_camel_case_style
dotnet_naming_rule.readonly_fields_should_be_underscore_camel_case.severity = warning
# 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_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
csharp_style_prefer_local_over_anonymous_function = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
csharp_style_prefer_tuple_swap = true:suggestion
csharp_style_prefer_utf8_string_literals = true:suggestion
csharp_prefer_static_anonymous_function = true:suggestion
csharp_style_prefer_readonly_struct = true:suggestion
csharp_style_prefer_readonly_struct_member = true:suggestion
csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent
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
@@ -44,12 +44,12 @@ public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TReques
if (_validator is null) if (_validator is null)
return await next(request, cancellationToken).ConfigureAwait(false); return await next(request, cancellationToken).ConfigureAwait(false);
// before the handler of the command is executed // before the handler of the command is executed
var validationResult = await _validator.ValidateAsync(request, cancellationToken).ConfigureAwait(false); FluentValidation.Results.ValidationResult validationResult = await _validator.ValidateAsync(request, cancellationToken).ConfigureAwait(false);
// if there are no validation errors, invoke the command handler // if there are no validation errors, invoke the command handler
if (validationResult.IsValid) if (validationResult.IsValid)
return await next(request, cancellationToken).ConfigureAwait(false); return await next(request, cancellationToken).ConfigureAwait(false);
// after the command handler is executed // after the command handler is executed
var errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage)); System.Collections.Generic.List<Error> errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage));
// the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic // 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!) // 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; return (dynamic)errors;
@@ -25,7 +25,7 @@ public class OptionalJsonConverter<TValue> : JsonConverter<Optional<TValue>>
{ {
if (reader.TokenType == JsonTokenType.Null) if (reader.TokenType == JsonTokenType.Null)
return Optional<TValue>.None(); return Optional<TValue>.None();
var value = JsonSerializer.Deserialize<TValue>(ref reader, options); TValue? value = JsonSerializer.Deserialize<TValue>(ref reader, options);
return Optional<TValue>.Some(value!); return Optional<TValue>.Some(value!);
} }
@@ -20,9 +20,7 @@ public class OptionalJsonConverterFactory : JsonConverterFactory
/// <returns><see langword="true"/> if the type is <see cref="Optional{TValue}"/>, <see langword="false"/> otherwise.</returns> /// <returns><see langword="true"/> if the type is <see cref="Optional{TValue}"/>, <see langword="false"/> otherwise.</returns>
public override bool CanConvert(Type typeToConvert) public override bool CanConvert(Type typeToConvert)
{ {
if (!typeToConvert.IsGenericType) return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>);
return false;
return typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>);
} }
/// <summary> /// <summary>
@@ -1,10 +1,10 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Behaviors; using Lumina.Application.Common.Behaviors;
using Mapster;
using MapsterMapper;
using Mediator; using Mediator;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using FluentValidation;
using MapsterMapper;
using Mapster;
#endregion #endregion
namespace Lumina.Application.Common.DependencyInjection; namespace Lumina.Application.Common.DependencyInjection;
@@ -23,10 +23,7 @@ public static class ApplicationLayerServices
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services) public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
{ {
// register Mediator // register Mediator
services.AddMediator(options => services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped);
{
options.ServiceLifetime = ServiceLifetime.Scoped;
});
// register the validation behavior // register the validation behavior
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
@@ -35,7 +32,7 @@ public static class ApplicationLayerServices
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly); services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
// register mapster configs in this assembly // register mapster configs in this assembly
var mapsterConfig = TypeAdapterConfig.GlobalSettings; TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(ApplicationLayerServices).Assembly); mapsterConfig.Scan(typeof(ApplicationLayerServices).Assembly);
services.AddSingleton(mapsterConfig); services.AddSingleton(mapsterConfig);
services.AddScoped<IMapper, ServiceMapper>(); services.AddScoped<IMapper, ServiceMapper>();
@@ -4,7 +4,6 @@ using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster; using Mapster;
using MapsterMapper;
using Mediator; using Mediator;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
@@ -44,7 +43,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, E
/// </returns> /// </returns>
public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken) public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
{ {
var result = _directoryService.GetSubdirectories(request.Path); ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<DirectoryResponse>>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<DirectoryResponse>>()), errors => errors));
} }
#endregion #endregion
@@ -56,27 +56,25 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
{ {
List<FileSystemTreeNodeResponse> result = []; List<FileSystemTreeNodeResponse> result = [];
// retrieve the list of drives // retrieve the list of drives
var getDrivesResult = GetDrives(); ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> getDrivesResult = GetDrives();
if (getDrivesResult.IsError) if (getDrivesResult.IsError)
return getDrivesResult.Errors; return getDrivesResult.Errors;
result.AddRange(getDrivesResult.Value); result.AddRange(getDrivesResult.Value);
var pathPartsResults = _pathService.ParsePath(request.Path); ErrorOr<IEnumerable<PathSegment>> pathPartsResults = _pathService.ParsePath(request.Path);
if (pathPartsResults.IsError) if (pathPartsResults.IsError)
return pathPartsResults.Errors; return pathPartsResults.Errors;
var pathParts = pathPartsResults.Value.ToList(); List<PathSegment> pathParts = pathPartsResults.Value.ToList();
var currentPath = pathParts[0].Name; string currentPath = pathParts[0].Name;
var buildDirectoryTreeResult = BuildDirectoryTree(result, pathParts, out var currentNode); ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> buildDirectoryTreeResult = BuildDirectoryTree(result, pathParts, out FileSystemTreeNodeResponse? currentNode);
if (buildDirectoryTreeResult.IsError) if (buildDirectoryTreeResult.IsError)
return buildDirectoryTreeResult.Errors; return buildDirectoryTreeResult.Errors;
// add subdirectories of the last directory node // add subdirectories of the last directory node
var loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles); ErrorOr<Success> loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles);
if (loadChildrenResult.IsError) return loadChildrenResult.IsError ? (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)loadChildrenResult.Errors : (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)await ValueTask.FromResult(result);
return loadChildrenResult.Errors;
return await ValueTask.FromResult(result);
} }
/// <summary> /// <summary>
@@ -87,10 +85,10 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
/// </returns> /// </returns>
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> GetDrives() private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> GetDrives()
{ {
var driveResult = _driveService.GetDrives(); ErrorOr<IEnumerable<FileSystemItem>> driveResult = _driveService.GetDrives();
if (driveResult.IsError) return driveResult.IsError
return driveResult.Errors; ? (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)driveResult.Errors
return ErrorOrFactory.From(driveResult.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()); : ErrorOrFactory.From(driveResult.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>());
} }
/// <summary> /// <summary>
@@ -104,21 +102,21 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> BuildDirectoryTree(List<FileSystemTreeNodeResponse> drives, List<PathSegment> pathParts, out FileSystemTreeNodeResponse currentNode) private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> BuildDirectoryTree(List<FileSystemTreeNodeResponse> drives, List<PathSegment> pathParts, out FileSystemTreeNodeResponse currentNode)
{ {
// find the root drive that matches the first part of the path // find the root drive that matches the first part of the path
var drive = drives.First(d => d.Name.Contains(pathParts[0].Name)); FileSystemTreeNodeResponse drive = drives.First(d => d.Name.Contains(pathParts[0].Name));
drive.IsExpanded = true; drive.IsExpanded = true;
currentNode = drive; currentNode = drive;
var currentPath = pathParts[0].Name; string currentPath = pathParts[0].Name;
// traverse the remaining path parts to build the tree structure // traverse the remaining path parts to build the tree structure
for (var i = 1; i < pathParts.Count; i++) for (int i = 1; i < pathParts.Count; i++)
{ {
var combinedPathResult = _pathService.CombinePath(currentPath, pathParts[i].Name); ErrorOr<string> combinedPathResult = _pathService.CombinePath(currentPath, pathParts[i].Name);
if (combinedPathResult.IsError) if (combinedPathResult.IsError)
return combinedPathResult.Errors; return combinedPathResult.Errors;
currentPath = combinedPathResult.Value; currentPath = combinedPathResult.Value;
// create a new node for the directory and add it as a child of the current node // create a new node for the directory and add it as a child of the current node
var newNode = new FileSystemTreeNodeResponse FileSystemTreeNodeResponse newNode = new()
{ {
Path = currentPath, Path = currentPath,
Name = pathParts[i].Name, Name = pathParts[i].Name,
@@ -140,13 +138,13 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles) private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles)
{ {
// get subdirectories under the current node's path // get subdirectories under the current node's path
var subDirectoriesResult = _directoryService.GetSubdirectories(node.Path); ErrorOr<IEnumerable<Directory>> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path);
if (subDirectoriesResult.IsError) if (subDirectoriesResult.IsError)
return subDirectoriesResult.Errors; return subDirectoriesResult.Errors;
// add each subdirectory as a child node of the current directory // add each subdirectory as a child node of the current directory
foreach (var subDirectory in subDirectoriesResult.Value) foreach (Directory subDirectory in subDirectoriesResult.Value)
{ {
var subDirNode = new FileSystemTreeNodeResponse FileSystemTreeNodeResponse subDirNode = new()
{ {
Name = subDirectory.Name, Name = subDirectory.Name,
Path = subDirectory.Id.Path, Path = subDirectory.Id.Path,
@@ -159,13 +157,13 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
if (includeFiles) if (includeFiles)
{ {
// get files under the current node's path // get files under the current node's path
var filesResult = _fileService.GetFiles(node.Path); ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(node.Path);
if (filesResult.IsError) if (filesResult.IsError)
return filesResult.Errors; return filesResult.Errors;
// add each file as a child node of the current directory // add each file as a child node of the current directory
foreach (var file in filesResult.Value) foreach (File file in filesResult.Value)
{ {
var fileNode = new FileSystemTreeNodeResponse FileSystemTreeNodeResponse fileNode = new()
{ {
Name = file.Name, Name = file.Name,
Path = file.Id.Path, Path = file.Id.Path,
@@ -4,7 +4,6 @@ using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster; using Mapster;
using MapsterMapper;
using Mediator; using Mediator;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
@@ -44,7 +43,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler<GetTreeDirectories
/// </returns> /// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken) public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken)
{ {
var result = _directoryService.GetSubdirectories(request.Path); ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
} }
#endregion #endregion
@@ -43,7 +43,7 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
/// </returns> /// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken) public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken)
{ {
var result = _driveService.GetDrives(); ErrorOr<IEnumerable<FileSystemItem>> result = _driveService.GetDrives();
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
} }
#endregion #endregion
@@ -43,7 +43,7 @@ public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
/// </returns> /// </returns>
public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken) public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
{ {
var result = _fileService.GetFiles(request.Path); ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileResponse>>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileResponse>>()), errors => errors));
} }
#endregion #endregion
@@ -43,7 +43,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, Error
/// </returns> /// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken) public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken)
{ {
var result = _fileService.GetFiles(request.Path); ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
} }
#endregion #endregion
@@ -3,7 +3,6 @@ using ErrorOr;
using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath;
using Lumina.Contracts.Responses.FileManagement; using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster;
using Mediator; using Mediator;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -42,7 +41,7 @@ public class CombinePathCommandHandler : IRequestHandler<CombinePathCommand, Err
/// </returns> /// </returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(CombinePathCommand request, CancellationToken cancellationToken) public ValueTask<ErrorOr<PathSegmentResponse>> Handle(CombinePathCommand request, CancellationToken cancellationToken)
{ {
var result = _pathService.CombinePath(request.OriginalPath, request.NewPath); ErrorOr<string> result = _pathService.CombinePath(request.OriginalPath, request.NewPath);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors));
} }
#endregion #endregion
@@ -43,7 +43,7 @@ public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr
/// </returns> /// </returns>
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken) public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken)
{ {
var result = _pathService.ParsePath(request.Path); ErrorOr<IEnumerable<PathSegment>> result = _pathService.ParsePath(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<PathSegmentResponse>>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<PathSegmentResponse>>()), errors => errors));
} }
#endregion #endregion
@@ -43,7 +43,7 @@ public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, Err
/// </returns> /// </returns>
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(GetPathParentQuery request, CancellationToken cancellationToken) public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(GetPathParentQuery request, CancellationToken cancellationToken)
{ {
var result = _pathService.GoUpOneLevel(request.Path); ErrorOr<IEnumerable<PathSegment>> result = _pathService.GoUpOneLevel(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<PathSegmentResponse>>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<PathSegmentResponse>>()), errors => errors));
} }
#endregion #endregion
@@ -40,7 +40,7 @@ public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr
/// <returns>The root of the specified path.</returns> /// <returns>The root of the specified path.</returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken) public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken)
{ {
var result = _pathService.GetPathRoot(request.Path); ErrorOr<PathSegment> result = _pathService.GetPathRoot(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<PathSegmentResponse>()), errors => errors)); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<PathSegmentResponse>()), errors => errors));
} }
#endregion #endregion
@@ -57,7 +57,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
{ {
// TODO: update Api.Book.md documentation when the functionality is fully implemented // TODO: update Api.Book.md documentation when the functionality is fully implemented
List<MediaContributorId> contributorIds = []; List<MediaContributorId> contributorIds = [];
foreach (var mediaContributor in request.Contributors) foreach (Contracts.Models.MediaContributors.MediaContributorModel mediaContributor in request.Contributors)
{ {
// TODO: add logic to search the media contributors repository for existing contributors, based on the provided names // TODO: add logic to search the media contributors repository for existing contributors, based on the provided names
} }
@@ -67,37 +67,37 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
// TODO: add logic to search the book series repository for existing book series, based on the provided title // TODO: add logic to search the book series repository for existing book series, based on the provided title
// TODO: uncomment integration and unit tests about series // TODO: uncomment integration and unit tests about series
} }
var domainRatingsResult = request.Ratings.ConvertAll(rating => BookRating.Create( List<ErrorOr<BookRating>> domainRatingsResult = request.Ratings.ConvertAll(rating => BookRating.Create(
rating.Value ?? default, rating.Value ?? default,
rating.MaxValue ?? default, rating.MaxValue ?? default,
Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : default), Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : default),
Optional<int>.FromNullable(rating.VoteCount))); Optional<int>.FromNullable(rating.VoteCount)));
// check if any of the results contain errors // check if any of the results contain errors
var errors = domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors).ToList(); List<Error> errors = domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors).ToList();
if (errors.Count != 0) // if there are errors, return them if (errors.Count != 0) // if there are errors, return them
return errors; return errors;
var domainRatings = domainRatingsResult.Select(rating => rating.Value).ToList(); List<BookRating> domainRatings = domainRatingsResult.Select(rating => rating.Value).ToList();
var domainGenresResult = request.Metadata.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); List<ErrorOr<Genre>> domainGenresResult = request.Metadata.Genres!.ConvertAll(genre => Genre.Create(genre.Name!));
errors = domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors).ToList(); errors = domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors).ToList();
if (errors.Count != 0) if (errors.Count != 0)
return errors; return errors;
var domainGenres = domainGenresResult.Select(genre => genre.Value).ToList(); List<Genre> domainGenres = domainGenresResult.Select(genre => genre.Value).ToList();
var domainTagsResult = request.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); List<ErrorOr<Tag>> domainTagsResult = request.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!));
errors = domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors).ToList(); errors = domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors).ToList();
if (errors.Count != 0) if (errors.Count != 0)
return errors; return errors;
var domainTags = domainTagsResult.Select(tag => tag.Value).ToList(); List<Tag> domainTags = domainTagsResult.Select(tag => tag.Value).ToList();
var domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); List<ErrorOr<Isbn>> domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
errors = domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors).ToList(); errors = domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors).ToList();
if (errors.Count != 0) if (errors.Count != 0)
return errors; return errors;
var domainIsbns = domainIsbnsResult.Select(isbn => isbn.Value).ToList(); List<Isbn> domainIsbns = domainIsbnsResult.Select(isbn => isbn.Value).ToList();
var releaseInfoResult = ReleaseInfo.Create( ErrorOr<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo!.OriginalReleaseDate), Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo!.OriginalReleaseDate),
Optional<int>.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear), Optional<int>.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate), Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate),
@@ -107,11 +107,11 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
); );
if (releaseInfoResult.IsError) if (releaseInfoResult.IsError)
return releaseInfoResult.Errors; return releaseInfoResult.Errors;
var releaseInfo = releaseInfoResult.Value; ReleaseInfo releaseInfo = releaseInfoResult.Value;
LanguageInfo? languageInfo = null; LanguageInfo? languageInfo = null;
if (request.Metadata.Language is not null) if (request.Metadata.Language is not null)
{ {
var languageInfoResult = LanguageInfo.Create( ErrorOr<LanguageInfo> languageInfoResult = LanguageInfo.Create(
request.Metadata.Language.LanguageCode!, request.Metadata.Language.LanguageCode!,
request.Metadata.Language.LanguageName!, request.Metadata.Language.LanguageName!,
Optional<string>.FromNullable(request.Metadata.Language.NativeName)); Optional<string>.FromNullable(request.Metadata.Language.NativeName));
@@ -122,7 +122,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
LanguageInfo? originalLanguageInfo = null; LanguageInfo? originalLanguageInfo = null;
if (request.Metadata.OriginalLanguage is not null) if (request.Metadata.OriginalLanguage is not null)
{ {
var originalLanguageInfoResult = LanguageInfo.Create( ErrorOr<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
request.Metadata.OriginalLanguage.LanguageCode!, request.Metadata.OriginalLanguage.LanguageCode!,
request.Metadata.OriginalLanguage.LanguageName!, request.Metadata.OriginalLanguage.LanguageName!,
Optional<string>.FromNullable(request.Metadata.OriginalLanguage.NativeName)); Optional<string>.FromNullable(request.Metadata.OriginalLanguage.NativeName));
@@ -130,7 +130,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
return originalLanguageInfoResult.Errors; return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value; originalLanguageInfo = originalLanguageInfoResult.Value;
} }
var metadataResult = WrittenContentMetadata.Create( ErrorOr<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
request.Metadata.Title!, request.Metadata.Title!,
Optional<string>.FromNullable(request.Metadata.OriginalTitle), Optional<string>.FromNullable(request.Metadata.OriginalTitle),
Optional<string>.FromNullable(request.Metadata.Description), Optional<string>.FromNullable(request.Metadata.Description),
@@ -144,7 +144,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
); );
if (metadataResult.IsError) if (metadataResult.IsError)
return metadataResult.Errors; return metadataResult.Errors;
var createBookResult = Book.Create( ErrorOr<Book> createBookResult = Book.Create(
metadataResult.Value, metadataResult.Value,
Optional<BookFormat>.FromNullable(request.Format), Optional<BookFormat>.FromNullable(request.Format),
Optional<string>.FromNullable(request.Edition), Optional<string>.FromNullable(request.Edition),
@@ -166,9 +166,9 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
if (createBookResult.IsError) if (createBookResult.IsError)
return createBookResult.Errors; return createBookResult.Errors;
var bookRepository = _unitOfWork.GetRepository<IBookRepository>(); IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
var persistenceBook = _mapper.Map<BookModel>(createBookResult.Value); BookModel persistenceBook = _mapper.Map<BookModel>(createBookResult.Value);
var insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); ErrorOr<Created> insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsError) if (insertBookResult.IsError)
return insertBookResult.Errors; return insertBookResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -43,8 +43,8 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
/// </returns> /// </returns>
public async ValueTask<ErrorOr<IEnumerable<Book>>> Handle(GetBooksQuery request, CancellationToken cancellationToken) public async ValueTask<ErrorOr<IEnumerable<Book>>> Handle(GetBooksQuery request, CancellationToken cancellationToken)
{ {
var bookRepository = _unitOfWork.GetRepository<IBookRepository>(); IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
var getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<Contracts.Models.WrittenContentLibrary.BookLibrary.BookModel>> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<Book>>()), errors => errors); return getBooksResult.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<Book>>()), errors => errors);
} }
#endregion #endregion
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath> <BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -1,4 +1,4 @@
namespace Lumina.Contracts.Enums.FileSystem.VideoLibrary; namespace Lumina.Contracts.Enums.VideoLibrary;
/// <summary> /// <summary>
/// Enumeration for the types of video content libraries. /// Enumeration for the types of video content libraries.
+2 -3
View File
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath> <BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -15,5 +15,4 @@
<ItemGroup> <ItemGroup>
<Folder Include="Responses\WrittenContentLibrary\BookLibrary\" /> <Folder Include="Responses\WrittenContentLibrary\BookLibrary\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -1,8 +1,8 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Models.FileManagement;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using Lumina.Contracts.Models.FileManagement;
#endregion #endregion
namespace Lumina.Contracts.Responses.FileManagement; namespace Lumina.Contracts.Responses.FileManagement;
@@ -27,13 +27,10 @@ public static class DataAccessLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns> /// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static void AddDataAccessLayerServices(this IServiceCollection services) public static void AddDataAccessLayerServices(this IServiceCollection services)
{ {
var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(basePath)) if (!Directory.Exists(basePath))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist."); throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
services.AddDbContext<LuminaDbContext>(options => services.AddDbContext<LuminaDbContext>(options => options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}"));
{
options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}");
});
services.AddScoped<IUnitOfWork, UnitOfWork>(); services.AddScoped<IUnitOfWork, UnitOfWork>();
Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes(); Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes();
@@ -1,10 +1,10 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations; using System;
#nullable disable #nullable disable
namespace Lumina.DataAccess.Common.Migrations namespace Lumina.DataAccess.Common.Migrations;
{
/// <inheritdoc /> /// <inheritdoc />
public partial class InitialMigration : Migration public partial class InitialMigration : Migration
{ {
@@ -48,10 +48,7 @@ namespace Lumina.DataAccess.Common.Migrations
Created = table.Column<DateTime>(type: "TEXT", nullable: false), Created = table.Column<DateTime>(type: "TEXT", nullable: false),
Updated = table.Column<DateTime>(type: "TEXT", nullable: true) Updated = table.Column<DateTime>(type: "TEXT", nullable: true)
}, },
constraints: table => constraints: table => table.PrimaryKey("PK_Books", x => x.Id));
{
table.PrimaryKey("PK_Books", x => x.Id);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "Genres", name: "Genres",
@@ -59,10 +56,7 @@ namespace Lumina.DataAccess.Common.Migrations
{ {
Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false) Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false)
}, },
constraints: table => constraints: table => table.PrimaryKey("PK_Genres", x => x.Name));
{
table.PrimaryKey("PK_Genres", x => x.Name);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "Tags", name: "Tags",
@@ -70,10 +64,7 @@ namespace Lumina.DataAccess.Common.Migrations
{ {
Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false) Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false)
}, },
constraints: table => constraints: table => table.PrimaryKey("PK_Tags", x => x.Name));
{
table.PrimaryKey("PK_Tags", x => x.Name);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "BookISBNs", name: "BookISBNs",
@@ -213,4 +204,3 @@ namespace Lumina.DataAccess.Common.Migrations
name: "Tags"); name: "Tags");
} }
} }
}
@@ -43,16 +43,16 @@ internal sealed class BookRepository : IBookRepository
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns> /// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Created>> InsertAsync(BookModel book, CancellationToken cancellationToken) public async Task<ErrorOr<Created>> InsertAsync(BookModel book, CancellationToken cancellationToken)
{ {
var jobExists = await _luminaDbContext.Books.AnyAsync(_book => _book.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); bool jobExists = await _luminaDbContext.Books.AnyAsync(_book => _book.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (jobExists) if (jobExists)
return Errors.WrittenContent.BookAlreadyExists; return Errors.WrittenContent.BookAlreadyExists;
// fetch existing tags and genres // fetch existing tags and genres
var existingTags = await _luminaDbContext.Set<TagModel>() List<TagModel> existingTags = await _luminaDbContext.Set<TagModel>()
.Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name)) .Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false); .ToListAsync(cancellationToken).ConfigureAwait(false);
var existingGenres = await _luminaDbContext.Set<GenreModel>() List<GenreModel> existingGenres = await _luminaDbContext.Set<GenreModel>()
.Where(g => book.Genres.Select(bg => bg.Name).Contains(g.Name)) .Where(g => book.Genres.Select(bg => bg.Name).Contains(g.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false); .ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -20,7 +20,7 @@ public class RepositoryDictionary
/// <summary> /// <summary>
/// Gets the number of added repositories. /// Gets the number of added repositories.
/// </summary> /// </summary>
public int Count { get { return _container.Count; } } public int Count => _container.Count;
#endregion #endregion
#region ===================================================================== METHODS =================================================================================== #region ===================================================================== METHODS ===================================================================================
@@ -53,10 +53,10 @@ public class LuminaDbContext : DbContext
public override int SaveChanges() public override int SaveChanges()
{ {
// get all the entity entries that are either added or modified // get all the entity entries that are either added or modified
var entries = ChangeTracker.Entries() IEnumerable<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry> entries = ChangeTracker.Entries()
.Where(e => e.Entity is IStorageEntity && .Where(e => e.Entity is IStorageEntity &&
(e.State is EntityState.Added or EntityState.Modified)); (e.State is EntityState.Added or EntityState.Modified));
foreach (var entityEntry in entries) foreach (Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry? entityEntry in entries)
{ {
// if the entity is in Added state, set the Created property to the current date and time // if the entity is in Added state, set the Created property to the current date and time
if (entityEntry.State == EntityState.Added) if (entityEntry.State == EntityState.Added)
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath> <BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -30,5 +30,4 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -1,5 +1,4 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
@@ -37,7 +37,7 @@ public abstract class ValueObject : IEquatable<ValueObject>
{ {
if (obj is null || obj.GetType() != GetType()) if (obj is null || obj.GetType() != GetType())
return false; return false;
var valueObject = (ValueObject)obj; ValueObject valueObject = (ValueObject)obj;
return GetEqualityComponents().SequenceEqual(valueObject.GetEqualityComponents()); return GetEqualityComponents().SequenceEqual(valueObject.GetEqualityComponents());
} }
@@ -20,13 +20,7 @@ public readonly struct Optional<TValue>
/// <summary> /// <summary>
/// Gets the value represented by this structure. /// Gets the value represented by this structure.
/// </summary> /// </summary>
public TValue Value public TValue Value => HasValue ? _value! : default!;
{
get
{
return HasValue ? _value! : default!;
}
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -53,18 +53,12 @@ public abstract class BaseMetadata : ValueObject
/// <summary> /// <summary>
/// Gets the list of tags associated with the media item. /// Gets the list of tags associated with the media item.
/// </summary> /// </summary>
public IReadOnlyCollection<Tag> Tags public IReadOnlyCollection<Tag> Tags => _tags.AsReadOnly();
{
get { return _tags.AsReadOnly(); }
}
/// <summary> /// <summary>
/// Gets the list of genres associated with the media item. /// Gets the list of genres associated with the media item.
/// </summary> /// </summary>
public IReadOnlyCollection<Genre> Genres public IReadOnlyCollection<Genre> Genres => _genres.AsReadOnly();
{
get { return _genres.AsReadOnly(); }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -109,9 +103,9 @@ public abstract class BaseMetadata : ValueObject
yield return OriginalTitle; yield return OriginalTitle;
yield return Description; yield return Description;
yield return ReleaseInfo; yield return ReleaseInfo;
foreach (var genre in _genres) foreach (Genre genre in _genres)
yield return genre; yield return genre;
foreach (var tag in _tags) foreach (Tag tag in _tags)
yield return tag; yield return tag;
yield return Language; yield return Language;
yield return OriginalLanguage; yield return OriginalLanguage;
@@ -41,9 +41,7 @@ public class Genre : ValueObject
/// </returns> /// </returns>
public static ErrorOr<Genre> Create(string name) public static ErrorOr<Genre> Create(string name)
{ {
if (string.IsNullOrWhiteSpace(name)) return string.IsNullOrWhiteSpace(name) ? (ErrorOr<Genre>)Errors.Errors.Metadata.GenreNameCannotBeEmpty : (ErrorOr<Genre>)new Genre(name);
return Errors.Errors.Metadata.GenreNameCannotBeEmpty;
return new Genre(name);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -58,13 +58,11 @@ public class LanguageInfo : ValueObject
/// </returns> /// </returns>
public static ErrorOr<LanguageInfo> Create(string languageCode, string languageName, Optional<string> nativeName) public static ErrorOr<LanguageInfo> Create(string languageCode, string languageName, Optional<string> nativeName)
{ {
if (string.IsNullOrWhiteSpace(languageCode)) return string.IsNullOrWhiteSpace(languageCode)
return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty; ? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.LanguageCodeCannotBeEmpty
if (string.IsNullOrWhiteSpace(languageName)) : string.IsNullOrWhiteSpace(languageName)
return Errors.Errors.Metadata.LanguageNameCannotBeEmpty; ? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.LanguageNameCannotBeEmpty
if (languageCode.Length != 2) : languageCode.Length != 2 ? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.InvalidIsoCode : (ErrorOr<LanguageInfo>)new LanguageInfo(languageCode, languageName, nativeName);
return Errors.Errors.Metadata.InvalidIsoCode;
return new LanguageInfo(languageCode, languageName, nativeName);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -51,7 +51,7 @@ public abstract class Rating : ValueObject
/// <returns>The rating value as a percentage of the maximum value.</returns> /// <returns>The rating value as a percentage of the maximum value.</returns>
public decimal AsPercentage() public decimal AsPercentage()
{ {
return (Value / MaxValue) * 100; return Value / MaxValue * 100;
} }
#endregion #endregion
} }
@@ -96,15 +96,15 @@ public class ReleaseInfo : ValueObject
Optional<string> releaseCountry, Optional<string> releaseCountry,
Optional<string> releaseVersion) Optional<string> releaseVersion)
{ {
if (originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value) return originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value
return Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch; ? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch
if (reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value) : reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value
return Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch; ? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch
if (originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value) : originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value
return Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate; ? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate
if (originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value) : originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value
return Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear; ? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear
return new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion); : (ErrorOr<ReleaseInfo>)new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -41,9 +41,7 @@ public class Tag : ValueObject
/// </returns> /// </returns>
public static ErrorOr<Tag> Create(string name) public static ErrorOr<Tag> Create(string name)
{ {
if (string.IsNullOrWhiteSpace(name)) return string.IsNullOrWhiteSpace(name) ? (ErrorOr<Tag>)Errors.Errors.Metadata.TagNameCannotBeEmpty : (ErrorOr<Tag>)new Tag(name);
return Errors.Errors.Metadata.TagNameCannotBeEmpty;
return new Tag(name);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -146,7 +146,7 @@ public class AudioMetadata : BaseMetadata
/// <inheritdoc/> /// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents() public override IEnumerable<object> GetEqualityComponents()
{ {
foreach (var component in base.GetEqualityComponents()) foreach (object component in base.GetEqualityComponents())
yield return component; yield return component;
yield return DurationInSeconds; yield return DurationInSeconds;
yield return SampleRate; yield return SampleRate;
@@ -34,10 +34,7 @@ public sealed class Directory : FileSystemItem
/// <summary> /// <summary>
/// Gets the collection of file system items that are children to the current directory entity. /// Gets the collection of file system items that are children to the current directory entity.
/// </summary> /// </summary>
public IReadOnlyCollection<FileSystemItem> Items public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
{
get { return _items.AsReadOnly(); }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -77,15 +74,13 @@ public sealed class Directory : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError) if (createPathResult.IsError)
return createPathResult.Errors; return createPathResult.Errors;
Directory newDirectory = new Directory( Directory newDirectory = new(
createPathResult.Value, createPathResult.Value,
name, name,
dateCreated, dateCreated,
dateModified); dateModified);
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status); ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : (ErrorOr<Directory>)newDirectory;
return setStatusResult.Errors;
return newDirectory;
} }
/// <summary> /// <summary>
@@ -106,15 +101,13 @@ public sealed class Directory : FileSystemItem
FileSystemItemStatus status = FileSystemItemStatus.Accessible) FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{ {
// TODO: enforce invariants // TODO: enforce invariants
Directory newDirectory = new Directory( Directory newDirectory = new(
id, id,
name, name,
dateCreated, dateCreated,
dateModified); dateModified);
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status); ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : (ErrorOr<Directory>)newDirectory;
return setStatusResult.Errors;
return newDirectory;
} }
/// <summary> /// <summary>
@@ -74,16 +74,14 @@ public sealed class File : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError) if (createPathResult.IsError)
return createPathResult.Errors; return createPathResult.Errors;
File newFile = new File( File newFile = new(
createPathResult.Value, createPathResult.Value,
name, name,
dateCreated, dateCreated,
dateModified, dateModified,
size); size);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status); ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : (ErrorOr<File>)newFile;
return setStatusResult.Errors;
return newFile;
} }
/// <summary> /// <summary>
@@ -107,16 +105,14 @@ public sealed class File : FileSystemItem
FileSystemItemStatus status = FileSystemItemStatus.Accessible) FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{ {
// TODO: enforce invariants // TODO: enforce invariants
File newFile = new File( File newFile = new(
id, id,
name, name,
dateCreated, dateCreated,
dateModified, dateModified,
size); size);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status); ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : (ErrorOr<File>)newFile;
return setStatusResult.Errors;
return newFile;
} }
/// <summary> /// <summary>
@@ -23,10 +23,7 @@ public sealed class UnixRootItem : FileSystemItem
/// <summary> /// <summary>
/// Gets the collection of file system items that are children to the current file system root entity. /// Gets the collection of file system items that are children to the current file system root entity.
/// </summary> /// </summary>
public IReadOnlyCollection<FileSystemItem> Items public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
{
get { return _items.AsReadOnly(); }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -54,13 +51,11 @@ public sealed class UnixRootItem : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(PATH); ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(PATH);
if (createPathResult.IsError) if (createPathResult.IsError)
return createPathResult.Errors; return createPathResult.Errors;
UnixRootItem newRoot = new UnixRootItem( UnixRootItem newRoot = new(
createPathResult.Value, createPathResult.Value,
PATH); PATH);
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status); ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<UnixRootItem>)setStatusResult.Errors : (ErrorOr<UnixRootItem>)newRoot;
return setStatusResult.Errors;
return newRoot;
} }
#endregion #endregion
} }
@@ -22,10 +22,7 @@ public sealed class WindowsRootItem : FileSystemItem
/// <summary> /// <summary>
/// Gets the collection of file system items that are children to the current file system root entity. /// Gets the collection of file system items that are children to the current file system root entity.
/// </summary> /// </summary>
public IReadOnlyCollection<FileSystemItem> Items public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
{
get { return _items.AsReadOnly(); }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -58,13 +55,11 @@ public sealed class WindowsRootItem : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError) if (createPathResult.IsError)
return createPathResult.Errors; return createPathResult.Errors;
WindowsRootItem newRoot = new WindowsRootItem( WindowsRootItem newRoot = new(
createPathResult.Value, createPathResult.Value,
name); name);
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status); ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<WindowsRootItem>)setStatusResult.Errors : (ErrorOr<WindowsRootItem>)newRoot;
return setStatusResult.Errors;
return newRoot;
} }
/// <summary> /// <summary>
@@ -82,13 +77,11 @@ public sealed class WindowsRootItem : FileSystemItem
FileSystemItemStatus status = FileSystemItemStatus.Accessible) FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{ {
// TODO: enforce invariants // TODO: enforce invariants
WindowsRootItem newFile = new WindowsRootItem( WindowsRootItem newFile = new(
id, id,
name); name);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status); ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<WindowsRootItem>)setStatusResult.Errors : (ErrorOr<WindowsRootItem>)newFile;
return setStatusResult.Errors;
return newFile;
} }
#endregion #endregion
} }
@@ -44,12 +44,12 @@ internal class DirectoryProviderService : IDirectoryProviderService
public ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path) public ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<IEnumerable<FileSystemPathId>>)Errors.Permission.UnauthorizedAccess
return ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path) : ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path)
.OrderBy(path => path) .OrderBy(path => path)
.Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar) .Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar)
.Select(path => FileSystemPathId.Create(path)) .Select(FileSystemPathId.Create)
.Where(errorOrPathId => !errorOrPathId.IsError) .Where(errorOrPathId => !errorOrPathId.IsError)
.Select(errorOrPathId => errorOrPathId.Value) .Select(errorOrPathId => errorOrPathId.Value)
.AsEnumerable()); .AsEnumerable());
@@ -85,9 +85,9 @@ internal class DirectoryProviderService : IDirectoryProviderService
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path) public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path)); : (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path));
} }
/// <summary> /// <summary>
@@ -98,9 +98,9 @@ internal class DirectoryProviderService : IDirectoryProviderService
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path) public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path)); : (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path));
} }
/// <summary> /// <summary>
@@ -270,7 +270,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name); string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name);
if (!string.IsNullOrEmpty(newDirectory)) if (!string.IsNullOrEmpty(newDirectory))
{ {
var newDirectoryPathResult = FileSystemPathId.Create(newDirectory); ErrorOr<FileSystemPathId> newDirectoryPathResult = FileSystemPathId.Create(newDirectory);
if (newDirectoryPathResult.IsError) if (newDirectoryPathResult.IsError)
return newDirectoryPathResult.Errors; return newDirectoryPathResult.Errors;
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false)) if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false))
@@ -45,9 +45,7 @@ public class DirectoryService : IDirectoryService
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path) public ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path)
{ {
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError ? (ErrorOr<IEnumerable<Directory>>)fileSystemPathIdResult.Errors : GetSubdirectories(fileSystemPathIdResult.Value);
return fileSystemPathIdResult.Errors;
return GetSubdirectories(fileSystemPathIdResult.Value);
} }
/// <summary> /// <summary>
@@ -113,9 +111,7 @@ public class DirectoryService : IDirectoryService
public ErrorOr<Directory> CreateDirectory(string path, string name) public ErrorOr<Directory> CreateDirectory(string path, string name)
{ {
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError ? (ErrorOr<Directory>)fileSystemPathIdResult.Errors : CreateDirectory(fileSystemPathIdResult.Value, name);
return fileSystemPathIdResult.Errors;
return CreateDirectory(fileSystemPathIdResult.Value, name);
} }
/// <summary> /// <summary>
@@ -153,9 +149,7 @@ public class DirectoryService : IDirectoryService
if (errorDirResult.IsError) if (errorDirResult.IsError)
return errorDirResult.Errors; return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : errorDirResult;
return setStatusResult.Errors;
return errorDirResult;
} }
else else
return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
@@ -180,9 +174,9 @@ public class DirectoryService : IDirectoryService
if (fileSystemSourcePathIdResult.IsError) if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors; return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsError) return fileSystemDestinationPathIdResult.IsError
return fileSystemDestinationPathIdResult.Errors; ? (ErrorOr<Directory>)fileSystemDestinationPathIdResult.Errors
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); : CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
} }
/// <summary> /// <summary>
@@ -226,9 +220,9 @@ public class DirectoryService : IDirectoryService
if (fileSystemSourcePathIdResult.IsError) if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors; return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsError) return fileSystemDestinationPathIdResult.IsError
return fileSystemDestinationPathIdResult.Errors; ? (ErrorOr<Directory>)fileSystemDestinationPathIdResult.Errors
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); : MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
} }
/// <summary> /// <summary>
@@ -263,9 +257,7 @@ public class DirectoryService : IDirectoryService
public ErrorOr<Directory> RenameDirectory(string path, string name) public ErrorOr<Directory> RenameDirectory(string path, string name)
{ {
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError ? (ErrorOr<Directory>)fileSystemPathIdResult.Errors : RenameDirectory(fileSystemPathIdResult.Value, name);
return fileSystemPathIdResult.Errors;
return RenameDirectory(fileSystemPathIdResult.Value, name);
} }
/// <summary> /// <summary>
@@ -303,9 +295,7 @@ public class DirectoryService : IDirectoryService
if (errorDirResult.IsError) if (errorDirResult.IsError)
return errorDirResult.Errors; return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : errorDirResult;
return setStatusResult.Errors;
return errorDirResult;
} }
else else
return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
@@ -320,9 +310,7 @@ public class DirectoryService : IDirectoryService
public ErrorOr<Deleted> DeleteDirectory(string path) public ErrorOr<Deleted> DeleteDirectory(string path)
{ {
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError ? (ErrorOr<Deleted>)fileSystemPathIdResult.Errors : DeleteDirectory(fileSystemPathIdResult.Value);
return fileSystemPathIdResult.Errors;
return DeleteDirectory(fileSystemPathIdResult.Value);
} }
/// <summary> /// <summary>
@@ -41,10 +41,8 @@ public class DriveService : IDriveService
{ {
if (_platformContext.Platform == PlatformType.Unix) if (_platformContext.Platform == PlatformType.Unix)
{ {
var unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible); ErrorOr<UnixRootItem> unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible);
if (unixRootResult.IsError) return unixRootResult.IsError ? (ErrorOr<IEnumerable<FileSystemItem>>)unixRootResult.Errors : (ErrorOr<IEnumerable<FileSystemItem>>)new List<FileSystemItem>() { unixRootResult.Value };
return unixRootResult.Errors;
return new List<FileSystemItem>() { unixRootResult.Value };
} }
else else
return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives() return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives()
@@ -53,7 +51,7 @@ public class DriveService : IDriveService
.Select(driveInfo => .Select(driveInfo =>
{ {
ErrorOr<FileSystemItem> root; ErrorOr<FileSystemItem> root;
var windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name); ErrorOr<WindowsRootItem> windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name);
if (windowsRootResult.IsError) if (windowsRootResult.IsError)
return windowsRootResult.Errors; return windowsRootResult.Errors;
else else
@@ -44,11 +44,11 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path) public ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<IEnumerable<FileSystemPathId>>)Errors.Permission.UnauthorizedAccess
return ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path) : ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path)
.OrderBy(p => p) .OrderBy(p => p)
.Select(p => FileSystemPathId.Create(p)) .Select(FileSystemPathId.Create)
.Where(errorOrPathId => !errorOrPathId.IsError) .Where(errorOrPathId => !errorOrPathId.IsError)
.Select(errorOrPathId => errorOrPathId.Value) .Select(errorOrPathId => errorOrPathId.Value)
.AsEnumerable()); .AsEnumerable());
@@ -82,9 +82,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<byte[]> GetFileAsync(FileSystemPathId path) public ErrorOr<byte[]> GetFileAsync(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<byte[]>)Errors.Permission.UnauthorizedAccess
return System.IO.File.ReadAllBytes(path.Path); : (ErrorOr<byte[]>)System.IO.File.ReadAllBytes(path.Path);
} }
/// <summary> /// <summary>
@@ -95,9 +95,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path) public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
return Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path)); : (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path));
} }
/// <summary> /// <summary>
@@ -108,9 +108,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path) public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
return Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path)); : (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path));
} }
/// <summary> /// <summary>
@@ -121,9 +121,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<long?> GetSize(FileSystemPathId path) public ErrorOr<long?> GetSize(FileSystemPathId path)
{ {
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
return Errors.Permission.UnauthorizedAccess; ? (ErrorOr<long?>)Errors.Permission.UnauthorizedAccess
return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0; : (ErrorOr<long?>)(_fileSystem.FileInfo.New(path.Path)?.Length ?? 0);
} }
/// <summary> /// <summary>
@@ -233,7 +233,7 @@ internal class FileProviderService : IFileProviderService
string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name); string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name);
if (!string.IsNullOrEmpty(newFile)) if (!string.IsNullOrEmpty(newFile))
{ {
var newFilePathResult = FileSystemPathId.Create(newFile); ErrorOr<FileSystemPathId> newFilePathResult = FileSystemPathId.Create(newFile);
if (newFilePathResult.IsError) if (newFilePathResult.IsError)
return newFilePathResult.Errors; return newFilePathResult.Errors;
// check if the user has access permissions to the provided path // check if the user has access permissions to the provided path
@@ -44,10 +44,8 @@ public class FileService : IFileService
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns> /// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
public ErrorOr<IEnumerable<File>> GetFiles(string path) public ErrorOr<IEnumerable<File>> GetFiles(string path)
{ {
var fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError ? (ErrorOr<IEnumerable<File>>)fileSystemPathIdResult.Errors : GetFiles(fileSystemPathIdResult.Value);
return fileSystemPathIdResult.Errors;
return GetFiles(fileSystemPathIdResult.Value);
} }
/// <summary> /// <summary>
@@ -71,7 +69,7 @@ public class FileService : IFileService
ErrorOr<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path); ErrorOr<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path);
if (filePathsResult.IsError) if (filePathsResult.IsError)
return filePathsResult.Errors; return filePathsResult.Errors;
List<File> result = new(); List<File> result = [];
IEnumerable<FileSystemPathId> filePaths = filePathsResult.Value; IEnumerable<FileSystemPathId> filePaths = filePathsResult.Value;
foreach (FileSystemPathId filePath in filePaths) foreach (FileSystemPathId filePath in filePaths)
{ {
@@ -96,7 +94,7 @@ public class FileService : IFileService
} }
else else
{ {
var fileResult = File.Create(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); ErrorOr<File> fileResult = File.Create(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
if (fileResult.IsError) if (fileResult.IsError)
return fileResult.Errors; return fileResult.Errors;
result.Add(fileResult.Value); result.Add(fileResult.Value);
@@ -117,13 +115,13 @@ public class FileService : IFileService
// make sure the paths are in the expected format // make sure the paths are in the expected format
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
if (fileSystemSourcePathIdResult.IsError) if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors; return fileSystemSourcePathIdResult.Errors;
var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsError) return fileSystemDestinationPathIdResult.IsError
return fileSystemDestinationPathIdResult.Errors; ? (ErrorOr<File>)fileSystemDestinationPathIdResult.Errors
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); : CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
} }
/// <summary> /// <summary>
@@ -135,7 +133,7 @@ public class FileService : IFileService
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns> /// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns>
public ErrorOr<File> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) public ErrorOr<File> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
{ {
var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsError) if (fileExists.IsError)
return fileExists.Errors; return fileExists.Errors;
else if (fileExists.Value == false) else if (fileExists.Value == false)
@@ -160,9 +158,7 @@ public class FileService : IFileService
if (errorFileResult.IsError) if (errorFileResult.IsError)
return errorFileResult.Errors; return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
return setStatusResult.Errors;
return errorFileResult;
} }
else else
return File.Create(copyFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); return File.Create(copyFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
@@ -181,13 +177,13 @@ public class FileService : IFileService
// make sure the paths are in the expected format // make sure the paths are in the expected format
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
if (fileSystemSourcePathIdResult.IsError) if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors; return fileSystemSourcePathIdResult.Errors;
var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsError) return fileSystemDestinationPathIdResult.IsError
return fileSystemDestinationPathIdResult.Errors; ? (ErrorOr<File>)fileSystemDestinationPathIdResult.Errors
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); : MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
} }
/// <summary> /// <summary>
@@ -199,7 +195,7 @@ public class FileService : IFileService
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the moved file, or an error.</returns> /// <returns>An <see cref="ErrorOr{TValue}"/> containing either the moved file, or an error.</returns>
public ErrorOr<File> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) public ErrorOr<File> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
{ {
var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsError) if (fileExists.IsError)
return fileExists.Errors; return fileExists.Errors;
else if (fileExists.Value == false) else if (fileExists.Value == false)
@@ -224,9 +220,7 @@ public class FileService : IFileService
if (errorFileResult.IsError) if (errorFileResult.IsError)
return errorFileResult.Errors; return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
return setStatusResult.Errors;
return errorFileResult;
} }
else else
return File.Create(moveFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); return File.Create(moveFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
@@ -241,10 +235,8 @@ public class FileService : IFileService
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed file, or an error.</returns> /// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed file, or an error.</returns>
public ErrorOr<File> RenameFile(string path, string name) public ErrorOr<File> RenameFile(string path, string name)
{ {
var fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError ? (ErrorOr<File>)fileSystemPathIdResult.Errors : RenameFile(fileSystemPathIdResult.Value, name);
return fileSystemPathIdResult.Errors;
return RenameFile(fileSystemPathIdResult.Value, name);
} }
/// <summary> /// <summary>
@@ -256,10 +248,10 @@ public class FileService : IFileService
public ErrorOr<File> RenameFile(FileSystemPathId path, string name) public ErrorOr<File> RenameFile(FileSystemPathId path, string name)
{ {
// first, check if the directory about to be created does not already exist // first, check if the directory about to be created does not already exist
var combinedPath = _platformContext.PathStrategy.CombinePath(path, name); ErrorOr<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
if (combinedPath.IsError) if (combinedPath.IsError)
return combinedPath.Errors; return combinedPath.Errors;
var fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value); ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value);
if (fileExists.IsError) if (fileExists.IsError)
return fileExists.Errors; return fileExists.Errors;
else if (fileExists.Value == true) else if (fileExists.Value == true)
@@ -284,9 +276,7 @@ public class FileService : IFileService
if (errorFileResult.IsError) if (errorFileResult.IsError)
return errorFileResult.Errors; return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError) return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
return setStatusResult.Errors;
return errorFileResult;
} }
else else
return File.Create(newFilePathResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); return File.Create(newFilePathResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
@@ -300,10 +290,8 @@ public class FileService : IFileService
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns> /// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
public ErrorOr<Deleted> DeleteFile(string path) public ErrorOr<Deleted> DeleteFile(string path)
{ {
var fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError ? (ErrorOr<Deleted>)fileSystemPathIdResult.Errors : DeleteFile(fileSystemPathIdResult.Value);
return fileSystemPathIdResult.Errors;
return DeleteFile(fileSystemPathIdResult.Value);
} }
/// <summary> /// <summary>
@@ -147,7 +147,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
_ = fileSystemInfo.CreationTime; // trigger potential access denial _ = fileSystemInfo.CreationTime; // trigger potential access denial
break; break;
case FileAccessMode.ReadContents: case FileAccessMode.ReadContents:
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
stream.Close(); stream.Close();
break; break;
} }
@@ -60,7 +60,7 @@ public class FileTypeService : IFileTypeService
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess; return Errors.Permission.UnauthorizedAccess;
Memory<byte> buffer = new byte[BUFFER_SIZE]; Memory<byte> buffer = new byte[BUFFER_SIZE];
using var stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); using FileSystemStream stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
// check if the file's length is less than the buffer size // check if the file's length is less than the buffer size
if (stream.Length < BUFFER_SIZE) if (stream.Length < BUFFER_SIZE)
return ImageType.None; return ImageType.None;
@@ -73,12 +73,9 @@ public class FileTypeService : IFileTypeService
return type; return type;
// no known image header types were found, check other methods // no known image header types were found, check other methods
string content = Encoding.UTF8.GetString(buffer.ToArray()); string content = Encoding.UTF8.GetString(buffer.ToArray());
if (IsSvg(content, path.Path)) return IsSvg(content, path.Path)
return ImageType.SVG; ? (ErrorOr<ImageType>)ImageType.SVG
else if (IsTga(buffer.ToArray())) : IsTga(buffer.ToArray()) ? (ErrorOr<ImageType>)ImageType.TGA : (ErrorOr<ImageType>)ImageType.None;
return ImageType.TGA;
else
return ImageType.None;
} }
/// <summary> /// <summary>
@@ -96,7 +93,7 @@ public class FileTypeService : IFileTypeService
if (initialContent.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase)) if (initialContent.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase))
{ {
// Read more content from the file // Read more content from the file
using var stream = _fileSystem.FileStream.New(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); using FileSystemStream stream = _fileSystem.FileStream.New(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
byte[] svgBuffer = new byte[1000]; byte[] svgBuffer = new byte[1000];
stream.Read(svgBuffer, 0, 1000); stream.Read(svgBuffer, 0, 1000);
string extendedContent = Encoding.UTF8.GetString(svgBuffer); string extendedContent = Encoding.UTF8.GetString(svgBuffer);
@@ -116,7 +113,7 @@ public class FileTypeService : IFileTypeService
if (buffer.Length < 18) if (buffer.Length < 18)
return false; return false;
byte imageType = buffer[2]; byte imageType = buffer[2];
return imageType == 1 || imageType == 2 || imageType == 10; return imageType is 1 or 2 or 10;
} }
/// <summary> /// <summary>
@@ -1,7 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using ErrorOr; using ErrorOr;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
#endregion #endregion
@@ -20,10 +20,7 @@ public class PathService : IPathService
/// <summary> /// <summary>
/// Gets the character used to separate path segments. /// Gets the character used to separate path segments.
/// </summary> /// </summary>
public char PathSeparator public char PathSeparator => _platformContext.PathStrategy.PathSeparator;
{
get { return _platformContext.PathStrategy.PathSeparator; }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -46,9 +43,7 @@ public class PathService : IPathService
public bool IsValidPath(string path) public bool IsValidPath(string path)
{ {
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError) return !newPathResult.IsError && _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
return false;
return _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
} }
/// <summary> /// <summary>
@@ -59,9 +54,7 @@ public class PathService : IPathService
public bool Exists(string path) public bool Exists(string path)
{ {
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError) return !newPathResult.IsError && _platformContext.PathStrategy.Exists(newPathResult.Value);
return false;
return _platformContext.PathStrategy.Exists(newPathResult.Value);
} }
/// <summary> /// <summary>
@@ -76,9 +69,7 @@ public class PathService : IPathService
if (newPathResult.IsError) if (newPathResult.IsError)
return newPathResult.Errors; return newPathResult.Errors;
ErrorOr<FileSystemPathId> combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name); ErrorOr<FileSystemPathId> combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name);
if (combinedPathResult.IsError) return combinedPathResult.IsError ? (ErrorOr<string>)combinedPathResult.Errors : (ErrorOr<string>)combinedPathResult.Value.Path;
return combinedPathResult.Errors;
return combinedPathResult.Value.Path;
} }
/// <summary> /// <summary>
@@ -89,9 +80,7 @@ public class PathService : IPathService
public ErrorOr<IEnumerable<PathSegment>> ParsePath(string path) public ErrorOr<IEnumerable<PathSegment>> ParsePath(string path)
{ {
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError) return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : _platformContext.PathStrategy.ParsePath(newPathResult.Value);
return newPathResult.Errors;
return _platformContext.PathStrategy.ParsePath(newPathResult.Value);
} }
/// <summary> /// <summary>
@@ -102,9 +91,7 @@ public class PathService : IPathService
public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path) public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path)
{ {
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError) return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
return newPathResult.Errors;
return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
} }
/// <summary> /// <summary>
@@ -124,9 +111,7 @@ public class PathService : IPathService
public ErrorOr<PathSegment> GetPathRoot(string path) public ErrorOr<PathSegment> GetPathRoot(string path)
{ {
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError) return newPathResult.IsError ? (ErrorOr<PathSegment>)newPathResult.Errors : _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
return newPathResult.Errors;
return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
} }
#endregion #endregion
} }
@@ -44,10 +44,10 @@ public class ThumbnailService : IThumbnailService
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns> /// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality) public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality)
{ {
var fileSystemPathIdResult = FileSystemPathId.Create(path); ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.IsError
return fileSystemPathIdResult.Errors; ? (ErrorOr<Thumbnail>)fileSystemPathIdResult.Errors
return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality); : await GetThumbnailAsync(fileSystemPathIdResult.Value, quality);
} }
/// <summary> /// <summary>
@@ -59,21 +59,21 @@ public class ThumbnailService : IThumbnailService
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(FileSystemPathId path, int quality) public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(FileSystemPathId path, int quality)
{ {
// first, get the type of the image file // first, get the type of the image file
var imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path); ErrorOr<ImageType> imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path);
if (imageTypeResult.IsError) if (imageTypeResult.IsError)
return imageTypeResult.Errors; return imageTypeResult.Errors;
if (imageTypeResult.Value != ImageType.None) if (imageTypeResult.Value != ImageType.None)
{ {
// then, get its bytes // then, get its bytes
var resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); ErrorOr<byte[]> resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path);
if (resultFileContents.IsError) if (resultFileContents.IsError)
return resultFileContents.Errors; return resultFileContents.Errors;
byte[] fileContents = resultFileContents.Value; byte[] fileContents = resultFileContents.Value;
// finally, resize or adjust quality based on image type // finally, resize or adjust quality based on image type
byte[]? adjustedImage = null; byte[]? adjustedImage = null;
if (imageTypeResult.Value == ImageType.JPEG || imageTypeResult.Value == ImageType.JPEG_CANON || imageTypeResult.Value == ImageType.JPEG2000 if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000
|| imageTypeResult.Value == ImageType.JPEG_UNKNOWN || imageTypeResult.Value == ImageType.PNG || imageTypeResult.Value == ImageType.BMP or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP
|| imageTypeResult.Value == ImageType.WEBP || imageTypeResult.Value == ImageType.GIF || imageTypeResult.Value == ImageType.TIFF || imageTypeResult.Value == ImageType.TGA) or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA)
adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality); adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality);
return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents); return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents);
} }
@@ -90,8 +90,8 @@ public class ThumbnailService : IThumbnailService
/// <returns>A byte array representing the processed image.</returns> /// <returns>A byte array representing the processed image.</returns>
private static async Task<byte[]> AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality) private static async Task<byte[]> AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality)
{ {
using var inputMemoryStream = new MemoryStream(imageBytes); using MemoryStream inputMemoryStream = new(imageBytes);
using var outputMemoryStream = new MemoryStream(); using MemoryStream outputMemoryStream = new();
switch (imageType) switch (imageType)
{ {
case ImageType.JPEG: case ImageType.JPEG:
@@ -99,22 +99,23 @@ public class ThumbnailService : IThumbnailService
case ImageType.JPEG_CANON: case ImageType.JPEG_CANON:
case ImageType.JPEG_UNKNOWN: case ImageType.JPEG_UNKNOWN:
{ {
using var image = await Image.LoadAsync(inputMemoryStream); using Image image = await Image.LoadAsync(inputMemoryStream);
await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality }); await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality });
break; break;
} }
case ImageType.PNG: case ImageType.PNG:
{ {
using var image = await Image.LoadAsync(inputMemoryStream); using Image image = await Image.LoadAsync(inputMemoryStream);
// PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression // PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression
int compressionLevel = MapRange(quality, 1, 100, 1, 9); int compressionLevel = MapRange(quality, 1, 100, 1, 9);
var encoder = new PngEncoder { CompressionLevel = (PngCompressionLevel)compressionLevel }; PngEncoder encoder = new()
{ CompressionLevel = (PngCompressionLevel)compressionLevel };
await image.SaveAsync(outputMemoryStream, encoder); await image.SaveAsync(outputMemoryStream, encoder);
break; break;
} }
case ImageType.BMP: case ImageType.BMP:
{ {
using var image = await Image.LoadAsync(inputMemoryStream); using Image image = await Image.LoadAsync(inputMemoryStream);
await image.SaveAsync(outputMemoryStream, new PngEncoder()); // convert BMP to PNG for compression await image.SaveAsync(outputMemoryStream, new PngEncoder()); // convert BMP to PNG for compression
break; break;
} }
@@ -133,8 +134,8 @@ public class ThumbnailService : IThumbnailService
/// <returns>The bytes of the adjusted image.</returns> /// <returns>The bytes of the adjusted image.</returns>
private static async Task<byte[]> AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality) private static async Task<byte[]> AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality)
{ {
using var inputMemoryStream = new MemoryStream(imageBytes); using MemoryStream inputMemoryStream = new(imageBytes);
using var outputMemoryStream = new MemoryStream(); using MemoryStream outputMemoryStream = new();
Image image = await Image.LoadAsync(inputMemoryStream); Image image = await Image.LoadAsync(inputMemoryStream);
double ratio = quality / 100.0; double ratio = quality / 100.0;
int newWidth = (int)(image.Width * ratio); int newWidth = (int)(image.Width * ratio);
@@ -142,7 +143,7 @@ public class ThumbnailService : IThumbnailService
// ensure new dimensions are not zero // ensure new dimensions are not zero
newWidth = Math.Max(1, newWidth); newWidth = Math.Max(1, newWidth);
newHeight = Math.Max(1, newHeight); newHeight = Math.Max(1, newHeight);
var options = new ResizeOptions ResizeOptions options = new()
{ {
Size = new Size(newWidth, newHeight), Size = new Size(newWidth, newHeight),
Mode = ResizeMode.Max Mode = ResizeMode.Max
@@ -183,7 +184,7 @@ public class ThumbnailService : IThumbnailService
/// </returns> /// </returns>
private static int MapRange(int value, int fromSource, int toSource, int fromTarget, int toTarget) private static int MapRange(int value, int fromSource, int toSource, int fromTarget, int toTarget)
{ {
return (value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource) + fromTarget; return ((value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource)) + fromTarget;
} }
#endregion #endregion
} }
@@ -1,5 +1,4 @@
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
@@ -1,6 +1,5 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
#endregion #endregion
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
@@ -21,10 +21,7 @@ public class UnixPathStrategy : IUnixPathStrategy
#endregion #endregion
#region ==================================================================== PROPERTIES ================================================================================= #region ==================================================================== PROPERTIES =================================================================================
public char PathSeparator public char PathSeparator => '/';
{
get { return '/'; }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -47,13 +44,13 @@ public class UnixPathStrategy : IUnixPathStrategy
public bool IsValidPath(FileSystemPathId path) public bool IsValidPath(FileSystemPathId path)
{ {
// check for invalid path characters // check for invalid path characters
var invalidChars = GetInvalidPathCharsForPlatform(); char[] invalidChars = GetInvalidPathCharsForPlatform();
if (path.Path.IndexOfAny(invalidChars) >= 0) if (path.Path.IndexOfAny(invalidChars) >= 0)
return false; return false;
// check for relative paths // check for relative paths
if (path.Path.StartsWith("./") || path.Path.StartsWith("../")) if (path.Path.StartsWith("./") || path.Path.StartsWith("../"))
return false; return false;
var pathPattern = @"^\/([\w\-\.\~!$&'()*+,;=:@ ]+(\/[\w\-\.\~!$&'()*+,;=:@ ]+)*)?\/?$"; string pathPattern = @"^\/([\w\-\.\~!$&'()*+,;=:@ ]+(\/[\w\-\.\~!$&'()*+,;=:@ ]+)*)?\/?$";
return Regex.IsMatch(path.Path, pathPattern); return Regex.IsMatch(path.Path, pathPattern);
} }
@@ -124,15 +121,13 @@ public class UnixPathStrategy : IUnixPathStrategy
if (tempPath.EndsWith('/')) if (tempPath.EndsWith('/'))
tempPath = tempPath.TrimEnd(PathSeparator); tempPath = tempPath.TrimEnd(PathSeparator);
// find the last occurrence of a slash // find the last occurrence of a slash
var lastIndex = tempPath.LastIndexOf(PathSeparator); int lastIndex = tempPath.LastIndexOf(PathSeparator);
// if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error
if (lastIndex < 0) if (lastIndex < 0)
return Errors.FileManagement.CannotNavigateUp; return Errors.FileManagement.CannotNavigateUp;
// return the path up to the last slash, or, if there's only the root slash, return that one instead // return the path up to the last slash, or, if there's only the root slash, return that one instead
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]);
if (newPathResult.IsError) return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : ParsePath(newPathResult.Value);
return newPathResult.Errors;
return ParsePath(newPathResult.Value);
} }
/// <summary> /// <summary>
@@ -155,9 +150,9 @@ public class UnixPathStrategy : IUnixPathStrategy
return Errors.FileManagement.InvalidPath; return Errors.FileManagement.InvalidPath;
// On Unix-like systems, the root is always "/" // On Unix-like systems, the root is always "/"
if (path.Path.StartsWith(PathSeparator)) return path.Path.StartsWith(PathSeparator)
return new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true); ? (ErrorOr<PathSegment>)new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true)
return Errors.FileManagement.InvalidPath; : (ErrorOr<PathSegment>)Errors.FileManagement.InvalidPath;
} }
#endregion #endregion
} }
@@ -1,12 +1,12 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using System;
using ErrorOr; using ErrorOr;
using System.Collections.Generic;
using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Errors;
using System.Text.RegularExpressions;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System.Linq; using System;
using System.Collections.Generic;
using System.IO.Abstractions; using System.IO.Abstractions;
using System.Linq;
using System.Text.RegularExpressions;
#endregion #endregion
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
@@ -21,10 +21,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
#endregion #endregion
#region ==================================================================== PROPERTIES ================================================================================= #region ==================================================================== PROPERTIES =================================================================================
public char PathSeparator public char PathSeparator => '\\';
{
get { return '\\'; }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -47,12 +44,12 @@ public class WindowsPathStrategy : IWindowsPathStrategy
public bool IsValidPath(FileSystemPathId path) public bool IsValidPath(FileSystemPathId path)
{ {
// check for invalid path characters // check for invalid path characters
var invalidChars = GetInvalidPathCharsForPlatform(); char[] invalidChars = GetInvalidPathCharsForPlatform();
if (path.Path.IndexOfAny(invalidChars) >= 0) if (path.Path.IndexOfAny(invalidChars) >= 0)
return false; return false;
// regular expression to match valid absolute paths // regular expression to match valid absolute paths
// this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share) // this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share)
var pathPattern = @"^[a-zA-Z]:\\(?:[a-zA-Z0-9\s()._-]+\\)*[a-zA-Z0-9\s()._-]*\\?$"; string pathPattern = @"^[a-zA-Z]:\\(?:[a-zA-Z0-9\s()._-]+\\)*[a-zA-Z0-9\s()._-]*\\?$";
return Regex.IsMatch(path.Path, pathPattern); return Regex.IsMatch(path.Path, pathPattern);
} }
@@ -92,18 +89,18 @@ public class WindowsPathStrategy : IWindowsPathStrategy
public ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path) public ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
{ {
// Windows paths usually start with a drive letter and colon, e.g., "C:" // Windows paths usually start with a drive letter and colon, e.g., "C:"
if (!path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator) return !path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator
return Errors.FileManagement.InvalidPath; ? (ErrorOr<IEnumerable<PathSegment>>)Errors.FileManagement.InvalidPath
return ErrorOrFactory.From(GetPathSegments()); : ErrorOrFactory.From(GetPathSegments());
IEnumerable<PathSegment> GetPathSegments() IEnumerable<PathSegment> GetPathSegments()
{ {
// the drive segment // the drive segment
yield return new PathSegment(path.Path[..2], isDirectory: false, isDrive: true); yield return new PathSegment(path.Path[..2], isDirectory: false, isDrive: true);
// extract the other segments // extract the other segments
var segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < segments.Length; i++) for (int i = 0; i < segments.Length; i++)
{ {
var segment = segments[i]; string segment = segments[i];
bool isDirectory; bool isDirectory;
if (segment.Contains('.')) if (segment.Contains('.'))
isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter
@@ -132,15 +129,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy
if (tempPath.EndsWith('\\')) if (tempPath.EndsWith('\\'))
tempPath = tempPath.TrimEnd(PathSeparator); tempPath = tempPath.TrimEnd(PathSeparator);
// find the last occurrence of a slash // find the last occurrence of a slash
var lastIndex = tempPath.LastIndexOf(PathSeparator); int lastIndex = tempPath.LastIndexOf(PathSeparator);
// if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error
if (lastIndex < 0) if (lastIndex < 0)
return Errors.FileManagement.CannotNavigateUp; 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 // if we are at the drive root level after trimming, return drive root, otherwise, return the path up to the last slash
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]); ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]);
if (newPathResult.IsError) return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : ParsePath(newPathResult.Value);
return newPathResult.Errors;
return ParsePath(newPathResult.Value);
} }
/// <summary> /// <summary>
@@ -172,11 +167,11 @@ public class WindowsPathStrategy : IWindowsPathStrategy
// check for UNC paths (e.g., "\\server\share") // check for UNC paths (e.g., "\\server\share")
if (path.Path.StartsWith('\\')) if (path.Path.StartsWith('\\'))
{ {
var parseResult = ParsePath(path); ErrorOr<IEnumerable<PathSegment>> parseResult = ParsePath(path);
if (parseResult.IsError) if (parseResult.IsError)
return parseResult.Errors; return parseResult.Errors;
var segments = parseResult.Value.ToList(); List<PathSegment> segments = parseResult.Value.ToList();
if (segments.Count >= 2) if (segments.Count >= 2)
{ {
string root = $@"\\{segments[0].Name}\{segments[1].Name}\"; string root = $@"\\{segments[0].Name}\{segments[1].Name}\";
@@ -48,9 +48,7 @@ public sealed class FileSystemPathId : ValueObject
/// </returns> /// </returns>
public static ErrorOr<FileSystemPathId> Create(string path) public static ErrorOr<FileSystemPathId> Create(string path)
{ {
if (string.IsNullOrWhiteSpace(path)) return string.IsNullOrWhiteSpace(path) ? (ErrorOr<FileSystemPathId>)Errors.FileManagement.InvalidPath : (ErrorOr<FileSystemPathId>)new FileSystemPathId(path);
return Errors.FileManagement.InvalidPath;
return new FileSystemPathId(path);
} }
#endregion #endregion
} }
@@ -115,13 +115,13 @@ public class StreamInfo : ValueObject
Optional<int> sampleRate, Optional<int> sampleRate,
Optional<int> channels) Optional<int> channels)
{ {
if (streamId is null) return streamId is null
return Errors.FileManagement.StreamIdCannotBeEmpty; ? (ErrorOr<StreamInfo>)Errors.FileManagement.StreamIdCannotBeEmpty
if (codec is null) : codec is null
return Errors.FileManagement.CodecCannotBeEmpty; ? (ErrorOr<StreamInfo>)Errors.FileManagement.CodecCannotBeEmpty
if (bitrate <= 0) : bitrate <= 0
return Errors.FileManagement.BitrateMustBeAPositiveNumber; ? (ErrorOr<StreamInfo>)Errors.FileManagement.BitrateMustBeAPositiveNumber
return new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels); : (ErrorOr<StreamInfo>)new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -30,18 +30,12 @@ public sealed class Movie : Entity<MovieId>
/// <summary> /// <summary>
/// Gets the list of ratings for this movie. /// Gets the list of ratings for this movie.
/// </summary> /// </summary>
public IReadOnlyCollection<Rating> Ratings public IReadOnlyCollection<Rating> Ratings => _ratings.AsReadOnly();
{
get { return _ratings.AsReadOnly(); }
}
/// <summary> /// <summary>
/// Gets the list of media contributors (actors, directors, etc) starring in this movie. /// Gets the list of media contributors (actors, directors, etc) starring in this movie.
/// </summary> /// </summary>
public IReadOnlyCollection<MediaContributorId> Contributors public IReadOnlyCollection<MediaContributorId> Contributors => _contributors.AsReadOnly();
{
get { return _contributors.AsReadOnly(); }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -14,9 +14,6 @@ public sealed class MovieLibraryService : IMovieLibraryService
/// <summary> /// <summary>
/// Gets the collection of movies in the library. /// Gets the collection of movies in the library.
/// </summary> /// </summary>
public ICollection<Movie> Movies public ICollection<Movie> Movies => throw new NotImplementedException();
{
get { throw new NotImplementedException(); }
}
#endregion #endregion
} }
@@ -125,7 +125,7 @@ public class VideoMetadata : BaseMetadata
/// <inheritdoc/> /// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents() public override IEnumerable<object> GetEqualityComponents()
{ {
foreach (var component in base.GetEqualityComponents()) foreach (object component in base.GetEqualityComponents())
yield return component; yield return component;
yield return DurationInSeconds; yield return DurationInSeconds;
yield return Resolution; yield return Resolution;
@@ -1,7 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion #endregion
namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities; namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities;
@@ -1,7 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion #endregion
namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities; namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities;
@@ -14,9 +14,6 @@ public class TvShowLibraryService : ITvShowLibraryService
/// <summary> /// <summary>
/// Gets the collection of TV shows in the library. /// Gets the collection of TV shows in the library.
/// </summary> /// </summary>
public ICollection<TvShow> TvShows public ICollection<TvShow> TvShows => throw new NotImplementedException();
{
get { throw new NotImplementedException(); }
}
#endregion #endregion
} }
@@ -1,7 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion #endregion
namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate; namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate;
@@ -99,26 +99,17 @@ public sealed class Book : AggregateRoot<BookId>
/// <summary> /// <summary>
/// Gets the list of ISBN (International Standard Book Number) of the book. /// Gets the list of ISBN (International Standard Book Number) of the book.
/// </summary> /// </summary>
public IReadOnlyCollection<Isbn> ISBNs public IReadOnlyCollection<Isbn> ISBNs => _isbns.AsReadOnly();
{
get { return _isbns.AsReadOnly(); }
}
/// <summary> /// <summary>
/// Gets the list of media contributors (actors, directors, etc) starring in this book. /// Gets the list of media contributors (actors, directors, etc) starring in this book.
/// </summary> /// </summary>
public IReadOnlyCollection<MediaContributorId> Contributors public IReadOnlyCollection<MediaContributorId> Contributors => _contributors.AsReadOnly();
{
get { return _contributors.AsReadOnly(); }
}
/// <summary> /// <summary>
/// Gets the list of ratings for this book. /// Gets the list of ratings for this book.
/// </summary> /// </summary>
public IReadOnlyCollection<BookRating> Ratings public IReadOnlyCollection<BookRating> Ratings => _ratings.AsReadOnly();
{
get { return _ratings.AsReadOnly(); }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -33,10 +33,7 @@ public sealed class BookSeries : Entity<BookSeriesId>
/// <summary> /// <summary>
/// Gets the collection of books in the series. /// Gets the collection of books in the series.
/// </summary> /// </summary>
public IReadOnlyCollection<Book> Books public IReadOnlyCollection<Book> Books => _books.AsReadOnly();
{
get { return _books.AsReadOnly(); }
}
#endregion #endregion
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
@@ -14,9 +14,6 @@ public sealed class BookLibraryService : IBookLibraryService
/// <summary> /// <summary>
/// Gets the collection of books in the library. /// Gets the collection of books in the library.
/// </summary> /// </summary>
public ICollection<Book> Books public ICollection<Book> Books => throw new NotImplementedException();
{
get { throw new NotImplementedException(); }
}
#endregion #endregion
} }
@@ -51,11 +51,9 @@ public class BookRating : Rating
/// </returns> /// </returns>
public static ErrorOr<BookRating> Create(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount) public static ErrorOr<BookRating> Create(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
{ {
if (maxValue < 0 || value < 0) return maxValue < 0 || value < 0
return Errors.Metadata.RatingValueMustBePositive; ? (ErrorOr<BookRating>)Errors.Metadata.RatingValueMustBePositive
if (value > maxValue) : value > maxValue ? (ErrorOr<BookRating>)Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue : (ErrorOr<BookRating>)new BookRating(value, maxValue, source, voteCount);
return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue;
return new BookRating(value, maxValue, source, voteCount);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -88,15 +88,15 @@ public class WrittenContentMetadata : BaseMetadata
Optional<string> publisher, Optional<string> publisher,
Optional<int> pageCount) Optional<int> pageCount)
{ {
if (string.IsNullOrWhiteSpace(title)) return string.IsNullOrWhiteSpace(title)
return Errors.Metadata.TitleCannotBeEmpty; ? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.TitleCannotBeEmpty
if (releaseInfo is null) : releaseInfo is null
return Errors.Metadata.ReleaseInfoCannotBeNull; ? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.ReleaseInfoCannotBeNull
if (genres is null) : genres is null
return Errors.Metadata.GenresListCannotBeNull; ? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.GenresListCannotBeNull
if (tags is null) : tags is null
return Errors.Metadata.TagsListCannotBeNull; ? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.TagsListCannotBeNull
return new WrittenContentMetadata( : (ErrorOr<WrittenContentMetadata>)new WrittenContentMetadata(
title, title,
originalTitle, originalTitle,
description, description,
@@ -112,7 +112,7 @@ public class WrittenContentMetadata : BaseMetadata
/// <inheritdoc/> /// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents() public override IEnumerable<object> GetEqualityComponents()
{ {
foreach (var component in base.GetEqualityComponents()) foreach (object component in base.GetEqualityComponents())
yield return component; yield return component;
yield return Publisher; yield return Publisher;
yield return PageCount; yield return PageCount;
+2 -3
View File
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath> <BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -24,5 +24,4 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" /> <ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -1,7 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using System.Reflection;
using FluentValidation; using FluentValidation;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
#endregion #endregion
namespace Lumina.Infrastructure.Common.DependencyInjection; namespace Lumina.Infrastructure.Common.DependencyInjection;
@@ -24,7 +24,7 @@ public static class SharedConfiguration
/// <exception cref="DirectoryNotFoundException">Thrown when the base path where the configuration files should be located, does not exist.</exception> /// <exception cref="DirectoryNotFoundException">Thrown when the base path where the configuration files should be located, does not exist.</exception>
public static IServiceCollection BindSharedConfiguration(this IServiceCollection services, IConfigurationManager configuration) public static IServiceCollection BindSharedConfiguration(this IServiceCollection services, IConfigurationManager configuration)
{ {
var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(basePath)) if (!Directory.Exists(basePath))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist."); throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
configuration.SetBasePath(basePath); configuration.SetBasePath(basePath);
@@ -52,7 +52,7 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> wher
ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null
var validationResult = _validator.Validate(options); // validate the options using the validator FluentValidation.Results.ValidationResult validationResult = _validator.Validate(options); // validate the options using the validator
// return a response based on the validation result // return a response based on the validation result
if (validationResult.IsValid) if (validationResult.IsValid)
@@ -60,7 +60,7 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> wher
// if the validation fails, collect the error messages // if the validation fails, collect the error messages
// TODO: add translation support for the error messages // TODO: add translation support for the error messages
var errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'")
.ToArray(); .ToArray();
// and return them with a failure result // and return them with a failure result
@@ -1,18 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath> <BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Include="..\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" /> <Compile Include="..\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FluentValidation" Version="11.9.2" /> <PackageReference Include="FluentValidation" Version="11.9.2" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" /> <PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
@@ -35,5 +34,4 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" /> <ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -36,7 +36,7 @@ public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
public void Configure(SwaggerGenOptions options) public void Configure(SwaggerGenOptions options)
{ {
// add swagger document for every API version discovered // add swagger document for every API version discovered
foreach (var description in _provider.ApiVersionDescriptions) foreach (ApiVersionDescription description in _provider.ApiVersionDescriptions)
options.SwaggerDoc(description.GroupName, CreateVersionInfo(description)); options.SwaggerDoc(description.GroupName, CreateVersionInfo(description));
} }
@@ -57,7 +57,7 @@ public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
/// <returns>The created <see cref="OpenApiInfo"/> instance.</returns> /// <returns>The created <see cref="OpenApiInfo"/> instance.</returns>
private OpenApiInfo CreateVersionInfo(ApiVersionDescription description) private OpenApiInfo CreateVersionInfo(ApiVersionDescription description)
{ {
var info = new OpenApiInfo() OpenApiInfo info = new()
{ {
Title = "Lumina API", Title = "Lumina API",
Version = description.ApiVersion.ToString() Version = description.ApiVersion.ToString()
@@ -22,7 +22,7 @@ internal static class PresentationApiLayerConfiguration
/// <exception cref="DirectoryNotFoundException">Thrown when the base path where the configuration files should be located, does not exist.</exception> /// <exception cref="DirectoryNotFoundException">Thrown when the base path where the configuration files should be located, does not exist.</exception>
public static IServiceCollection BindPresentationApiLayerConfiguration(this IServiceCollection services, IConfigurationManager configuration) public static IServiceCollection BindPresentationApiLayerConfiguration(this IServiceCollection services, IConfigurationManager configuration)
{ {
var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(basePath)) if (!Directory.Exists(basePath))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist."); throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
configuration.SetBasePath(basePath); configuration.SetBasePath(basePath);
@@ -25,14 +25,11 @@ public static class PresentationApiLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns> /// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
{ {
services.AddCors(options => services.AddCors(options => options.AddPolicy("AllowAll",
{
options.AddPolicy("AllowAll",
builder => builder builder => builder
.AllowAnyOrigin() .AllowAnyOrigin()
.AllowAnyMethod() .AllowAnyMethod()
.AllowAnyHeader()); .AllowAnyHeader()));
});
// add services to the container // add services to the container
services.AddControllers().AddJsonOptions(options => services.AddControllers().AddJsonOptions(options =>
@@ -62,7 +59,7 @@ public static class PresentationApiLayerServices
services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>(); services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();
// register mapster configs // register mapster configs
var mapsterConfig = TypeAdapterConfig.GlobalSettings; TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly); mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly);
services.AddSingleton(mapsterConfig); services.AddSingleton(mapsterConfig);
services.AddScoped<IMapper, ServiceMapper>(); services.AddScoped<IMapper, ServiceMapper>();
@@ -53,7 +53,7 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory
string? detail = null, string? instance = null) string? detail = null, string? instance = null)
{ {
statusCode ??= 500; statusCode ??= 500;
var problemDetails = new ProblemDetails ProblemDetails problemDetails = new()
{ {
Status = statusCode, Status = statusCode,
Title = title, Title = title,
@@ -81,7 +81,7 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory
{ {
ArgumentNullException.ThrowIfNull(modelStateDictionary); ArgumentNullException.ThrowIfNull(modelStateDictionary);
statusCode ??= 400; statusCode ??= 400;
var problemDetails = new ValidationProblemDetails(modelStateDictionary) ValidationProblemDetails problemDetails = new(modelStateDictionary)
{ {
Status = statusCode, Status = statusCode,
Type = type, Type = type,
@@ -104,23 +104,20 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory
private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int statusCode) private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int statusCode)
{ {
problemDetails.Status ??= statusCode; problemDetails.Status ??= statusCode;
if (_options.ClientErrorMapping.TryGetValue(statusCode, out var clientErrorData)) if (_options.ClientErrorMapping.TryGetValue(statusCode, out ClientErrorData? clientErrorData))
{ {
problemDetails.Title ??= clientErrorData.Title; problemDetails.Title ??= clientErrorData.Title;
problemDetails.Type ??= clientErrorData.Link; problemDetails.Type ??= clientErrorData.Link;
} }
var traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier; string? traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier;
if (traceId != null) if (traceId != null)
problemDetails.Extensions["traceId"] = traceId; problemDetails.Extensions["traceId"] = traceId;
// get any errors that might be sent by ApiController base class' Problem() method // get any errors that might be sent by ApiController base class' Problem() method
var errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List<Error>; List<Error>? errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List<Error>;
// add any extra custom properties // add any extra custom properties
if (errors is not null) if (errors is not null)
{ {
problemDetails.Extensions.Add("errors", errors.Select(error => problemDetails.Extensions.Add("errors", errors.Select(error => error.Code));
{
return error.Code;
}));
} }
//problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString())); //problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString()));
_configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails }); _configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails });
@@ -23,7 +23,7 @@ public class UrlStringBinder : IModelBinder
throw new ArgumentNullException(nameof(bindingContext)); throw new ArgumentNullException(nameof(bindingContext));
string modelName = bindingContext.ModelName; string modelName = bindingContext.ModelName;
// try to fetch the value of the argument by name // try to fetch the value of the argument by name
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None) if (valueProviderResult == ValueProviderResult.None)
return Task.CompletedTask; return Task.CompletedTask;
string? value = valueProviderResult.FirstValue; string? value = valueProviderResult.FirstValue;
@@ -43,7 +43,7 @@ public abstract class ApiController : ControllerBase
/// <param name="error">The error to convert.</param> /// <param name="error">The error to convert.</param>
protected internal IActionResult Problem(Error error) protected internal IActionResult Problem(Error error)
{ {
var statusCode = error.Type switch int statusCode = error.Type switch
{ {
ErrorType.Conflict => StatusCodes.Status409Conflict, ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.NotFound => StatusCodes.Status404NotFound, ErrorType.NotFound => StatusCodes.Status404NotFound,
@@ -62,8 +62,8 @@ public abstract class ApiController : ControllerBase
/// <param name="errors">The list of errors to convert.</param> /// <param name="errors">The list of errors to convert.</param>
protected internal IActionResult ValidationProblem(List<Error> errors) protected internal IActionResult ValidationProblem(List<Error> errors)
{ {
var modelStateDictionary = new ModelStateDictionary(); ModelStateDictionary modelStateDictionary = new();
foreach (var error in errors) foreach (Error error in errors)
modelStateDictionary.AddModelError(error.Code, error.Description); modelStateDictionary.AddModelError(error.Code, error.Description);
return ValidationProblem(modelStateDictionary: modelStateDictionary, title: "One or more validation errors occurred."); return ValidationProblem(modelStateDictionary: modelStateDictionary, title: "One or more validation errors occurred.");
} }
@@ -49,7 +49,7 @@ public class DirectoriesController : ApiController
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles), cancellationToken).ConfigureAwait(false);
if (!result.IsError && result.Value is not null) if (!result.IsError && result.Value is not null)
{ {
foreach (var treeNode in result.Value) foreach (FileSystemTreeNodeResponse treeNode in result.Value)
{ {
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
yield break; yield break;
@@ -69,7 +69,7 @@ public class DirectoriesController : ApiController
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeDirectoriesQuery(path), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeDirectoriesQuery(path), cancellationToken).ConfigureAwait(false);
if (!result.IsError && result.Value is not null) if (!result.IsError && result.Value is not null)
{ {
foreach (var directory in result.Value) foreach (FileSystemTreeNodeResponse directory in result.Value)
{ {
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
yield break; yield break;
@@ -89,7 +89,7 @@ public class DirectoriesController : ApiController
ErrorOr<IEnumerable<DirectoryResponse>> result = await _mediator.Send(new GetDirectoriesQuery(path), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<DirectoryResponse>> result = await _mediator.Send(new GetDirectoriesQuery(path), cancellationToken).ConfigureAwait(false);
if (!result.IsError && result.Value is not null) if (!result.IsError && result.Value is not null)
{ {
foreach (var directory in result.Value) foreach (DirectoryResponse directory in result.Value)
{ {
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
yield break; yield break;
@@ -43,7 +43,7 @@ public class DrivesController : ApiController
public async Task<IActionResult> GetDrives(CancellationToken cancellationToken) public async Task<IActionResult> GetDrives(CancellationToken cancellationToken)
{ {
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors)); return result.Match(Ok, Problem);
} }
#endregion #endregion
} }
@@ -1,5 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSysem; using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSysem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Core.Controllers.Common; using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator; using Mediator;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -39,7 +40,7 @@ public class FileSystemController : ApiController
[HttpGet("get-type")] [HttpGet("get-type")]
public async Task<IActionResult> GetType(CancellationToken cancellationToken) public async Task<IActionResult> GetType(CancellationToken cancellationToken)
{ {
var platformType = await _mediator.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false); FileSystemTypeResponse platformType = await _mediator.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false);
return Ok(platformType); return Ok(platformType);
} }
#endregion #endregion
@@ -47,7 +47,7 @@ public class FilesController : ApiController
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken) public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken)
{ {
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeFilesQuery(path), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeFilesQuery(path), cancellationToken).ConfigureAwait(false);
foreach (var file in result.Value) foreach (FileSystemTreeNodeResponse file in result.Value)
{ {
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
yield break; yield break;
@@ -66,7 +66,7 @@ public class FilesController : ApiController
ErrorOr<IEnumerable<FileResponse>> result = await _mediator.Send(new GetFilesQuery(path), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<FileResponse>> result = await _mediator.Send(new GetFilesQuery(path), cancellationToken).ConfigureAwait(false);
if (!result.IsError) if (!result.IsError)
{ {
foreach (var file in result.Value) foreach (FileResponse file in result.Value)
{ {
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
yield break; yield break;
@@ -51,7 +51,7 @@ public class PathController : ApiController
public async Task<IActionResult> GetPathRoot([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) public async Task<IActionResult> GetPathRoot([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{ {
ErrorOr<PathSegmentResponse> result = await _mediator.Send(new GetPathRootQuery(path), cancellationToken).ConfigureAwait(false); ErrorOr<PathSegmentResponse> result = await _mediator.Send(new GetPathRootQuery(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors)); return result.Match(Ok, Problem);
} }
/// <summary> /// <summary>
@@ -74,7 +74,7 @@ public class PathController : ApiController
public async Task<IActionResult> GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) public async Task<IActionResult> GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{ {
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors)); return result.Match(Ok, Problem);
} }
/// <summary> /// <summary>
@@ -87,7 +87,7 @@ public class PathController : ApiController
public async Task<IActionResult> CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken) public async Task<IActionResult> CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken)
{ {
ErrorOr<PathSegmentResponse> result = await _mediator.Send(new CombinePathCommand(originalPath, newPath), cancellationToken).ConfigureAwait(false); ErrorOr<PathSegmentResponse> result = await _mediator.Send(new CombinePathCommand(originalPath, newPath), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors)); return result.Match(Ok, Problem);
} }
/// <summary> /// <summary>
@@ -99,7 +99,7 @@ public class PathController : ApiController
public async Task<IActionResult> SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) public async Task<IActionResult> SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{ {
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false); ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors)); return result.Match(Ok, Problem);
} }
/// <summary> /// <summary>
@@ -1,4 +1,4 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Controllers.Common; using Lumina.Presentation.Api.Core.Controllers.Common;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -20,7 +20,7 @@ public class HealthController : ApiController
public async Task<IActionResult> CheckHealth() public async Task<IActionResult> CheckHealth()
{ {
// TODO: to be implemented // TODO: to be implemented
return Ok(); return await Task.FromResult(Ok());
} }
#endregion #endregion
} }
@@ -43,8 +43,8 @@ public class BooksController : ApiController
[HttpGet()] [HttpGet()]
public async Task<IActionResult> GetBooks() public async Task<IActionResult> GetBooks()
{ {
var result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false); ErrorOr.ErrorOr<System.Collections.Generic.IEnumerable<Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Book>> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors)); return result.Match(Ok, Problem);
} }
/// <summary> /// <summary>
@@ -54,8 +54,8 @@ public class BooksController : ApiController
[HttpPost()] [HttpPost()]
public async Task<IActionResult> AddBook(AddBookRequest request) public async Task<IActionResult> AddBook(AddBookRequest request)
{ {
var result = await _mediator.Send(_mapper.Map<AddBookCommand>(request)).ConfigureAwait(false); ErrorOr.ErrorOr<Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Book> result = await _mediator.Send(_mapper.Map<AddBookCommand>(request)).ConfigureAwait(false);
return result.Match(result => Created($"/api/v1/books/{result.Id}", result), errors => Problem(errors)); return result.Match(result => Created($"/api/v1/books/{result.Id}", result), Problem);
} }
#endregion #endregion
} }
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath> <BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<UserSecretsId>37d55c87-4374-4971-82e9-012fcaad1853</UserSecretsId> <UserSecretsId>37d55c87-4374-4971-82e9-012fcaad1853</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<ContainerRepository>lumina-server</ContainerRepository> <ContainerRepository>lumina-server</ContainerRepository>
@@ -17,7 +17,6 @@
<Compile Include="..\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" /> <Compile Include="..\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Mapster" Version="7.4.0" /> <PackageReference Include="Mapster" Version="7.4.0" />
<PackageReference Include="Mapster.DependencyInjection" Version="1.0.1" /> <PackageReference Include="Mapster.DependencyInjection" Version="1.0.1" />
@@ -55,4 +54,8 @@
<ProjectReference Include="..\Lumina.DataAccess\Lumina.DataAccess.csproj" /> <ProjectReference Include="..\Lumina.DataAccess\Lumina.DataAccess.csproj" />
</ItemGroup> </ItemGroup>
<!--disable warnings generated by Mediator source generator-->
<PropertyGroup>
<NoWarn>$(NoWarn);CS0436</NoWarn>
</PropertyGroup>
</Project> </Project>
+3 -3
View File
@@ -1,9 +1,9 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DependencyInjection; using Lumina.Application.Common.DependencyInjection;
using Lumina.DataAccess.Common.DependencyInjection; using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.Domain.Common.DependencyInjection;
using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.DependencyInjection;
using Lumina.Domain.Common.DependencyInjection;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -23,7 +23,7 @@ public class Program
/// <param name="args">Optional command line arguments.</param> /// <param name="args">Optional command line arguments.</param>
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
var builder = WebApplication.CreateBuilder(args); WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.BindSharedConfiguration(builder.Configuration); builder.Services.BindSharedConfiguration(builder.Configuration);
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration); builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
@@ -34,7 +34,7 @@ public class Program
builder.Services.AddDataAccessLayerServices(); builder.Services.AddDataAccessLayerServices();
builder.Services.AddDomainLayerServices(); builder.Services.AddDomainLayerServices();
var app = builder.Build(); WebApplication app = builder.Build();
app.UseCors("AllowAll"); app.UseCors("AllowAll");
@@ -39,7 +39,7 @@ public class ApiHttpClient : IApiHttpClient
{ {
_httpClient = httpClient; _httpClient = httpClient;
// read the API server configuration values from the configuration, and assign them to the injected client // read the API server configuration values from the configuration, and assign them to the injected client
var serverConfigurationModel = serverConfigurationOptions.Value; ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value;
httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/"); httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/");
_jsonOptions = new JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
@@ -62,7 +62,7 @@ public class ApiHttpClient : IApiHttpClient
/// <returns>The deserialized response containing the result of the GET request.</returns> /// <returns>The deserialized response containing the result of the GET request.</returns>
public async Task<TResponse> GetAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default) public async Task<TResponse> GetAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default)
{ {
using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
if (!string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false); return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
@@ -78,7 +78,7 @@ public class ApiHttpClient : IApiHttpClient
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns> /// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{ {
using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
// HttpClient is implemented differently in Blazor WASM, because there are no sockets in the browser, so its BrowserHttpHandler is implemented on top of Fetch API, // HttpClient is implemented differently in Blazor WASM, because there are no sockets in the browser, so its BrowserHttpHandler is implemented on top of Fetch API,
// which can provide response content in one of two forms: BrowserHttpContent, which is based on arrayBuffer method (this means that it will always read the response stream to its completion, // which can provide response content in one of two forms: BrowserHttpContent, which is based on arrayBuffer method (this means that it will always read the response stream to its completion,
// before making the content available), and StreamContent that is wrapping WasmHttpReadStream, which is based on readable streams (this one allows for reading response as it comes). // before making the content available), and StreamContent that is wrapping WasmHttpReadStream, which is based on readable streams (this one allows for reading response as it comes).
@@ -88,11 +88,11 @@ public class ApiHttpClient : IApiHttpClient
if (!string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
// send the request and expect only headers initially - this prevents the client from buffering the entire response // send the request and expect only headers initially - this prevents the client from buffering the entire response
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await using System.IO.Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
// Deserialize the JSON content asynchronously as an enumerable of TResponse items // Deserialize the JSON content asynchronously as an enumerable of TResponse items
await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<TResponse>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false)) await foreach (TResponse? item in JsonSerializer.DeserializeAsyncEnumerable<TResponse>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false))
{ {
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
yield break; yield break;
@@ -109,14 +109,14 @@ public class ApiHttpClient : IApiHttpClient
/// <returns>A model containing the deserialized blob.</returns> /// <returns>A model containing the deserialized blob.</returns>
public async Task<BlobDataModel> GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) public async Task<BlobDataModel> GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default)
{ {
using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
if (!string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode) if (!response.IsSuccessStatusCode)
{ {
// read the content as a string, for error messages // read the content as a string, for error messages
var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
ProblemDetailsModel? problemDetails = null; ProblemDetailsModel? problemDetails = null;
try try
{ {
@@ -141,7 +141,7 @@ public class ApiHttpClient : IApiHttpClient
/// <returns>The deserialized response containing the result of the DELETE request.</returns> /// <returns>The deserialized response containing the result of the DELETE request.</returns>
public async Task<TResponse> DeleteAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default) public async Task<TResponse> DeleteAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default)
{ {
using var request = new HttpRequestMessage(HttpMethod.Delete, endpoint); using HttpRequestMessage request = new(HttpMethod.Delete, endpoint);
if (!string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false); return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
@@ -159,7 +159,7 @@ public class ApiHttpClient : IApiHttpClient
/// <returns>The deserialized response containing the result of the PUT request.</returns> /// <returns>The deserialized response containing the result of the PUT request.</returns>
public async Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) public async Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default)
{ {
using var request = new HttpRequestMessage(HttpMethod.Put, endpoint); using HttpRequestMessage request = new(HttpMethod.Put, endpoint);
if (!string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
@@ -178,7 +178,7 @@ public class ApiHttpClient : IApiHttpClient
/// <returns>The deserialized response containing the result of the POST request.</returns> /// <returns>The deserialized response containing the result of the POST request.</returns>
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default)
{ {
using var request = new HttpRequestMessage(HttpMethod.Post, endpoint); using HttpRequestMessage request = new(HttpMethod.Post, endpoint);
if (!string.IsNullOrEmpty(token)) if (!string.IsNullOrEmpty(token))
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
@@ -197,8 +197,8 @@ public class ApiHttpClient : IApiHttpClient
private async Task<TResponse> SendRequestAsync<TResponse>(HttpRequestMessage request, CancellationToken cancellationToken) private async Task<TResponse> SendRequestAsync<TResponse>(HttpRequestMessage request, CancellationToken cancellationToken)
{ {
// send the HTTP request and read the response // send the HTTP request and read the response
var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// if the response is successful, deserialize the content to TResponse and return it // if the response is successful, deserialize the content to TResponse and return it
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
return JsonSerializer.Deserialize<TResponse>(content, _jsonOptions)!; return JsonSerializer.Deserialize<TResponse>(content, _jsonOptions)!;
@@ -29,7 +29,7 @@ public static class PresentationWebLayerServices
services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Singleton); services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Singleton);
// handle transient errors like network timeouts or intermittent failures // handle transient errors like network timeouts or intermittent failures
var retryPolicy = Policy Polly.Retry.AsyncRetryPolicy<HttpResponseMessage> retryPolicy = Policy
.Handle<HttpRequestException>() .Handle<HttpRequestException>()
.OrResult<HttpResponseMessage>(r => .OrResult<HttpResponseMessage>(r =>
!r.IsSuccessStatusCode && !r.IsSuccessStatusCode &&
@@ -39,12 +39,12 @@ public static class PresentationWebLayerServices
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
// use a circuit breaker to prevent repeatedly calling a failing service // use a circuit breaker to prevent repeatedly calling a failing service
var circuitBreakerPolicy = Policy Polly.CircuitBreaker.AsyncCircuitBreakerPolicy<HttpResponseMessage> circuitBreakerPolicy = Policy
.Handle<HttpRequestException>() .Handle<HttpRequestException>()
.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError) .OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError)
.CircuitBreakerAsync(3, TimeSpan.FromSeconds(30)); .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30));
var policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); Polly.Wrap.AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
// register the typed client used for the API interaction // register the typed client used for the API interaction
services.AddHttpClient<IApiHttpClient, ApiHttpClient>() services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
@@ -1,5 +1,4 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.FileSystem;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
#endregion #endregion
@@ -52,7 +52,7 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> wher
ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null
var validationResult = _validator.Validate(options); // validate the options using the validator FluentValidation.Results.ValidationResult validationResult = _validator.Validate(options); // validate the options using the validator
// return a response based on the validation result // return a response based on the validation result
if (validationResult.IsValid) if (validationResult.IsValid)
@@ -60,7 +60,7 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> wher
// if the validation fails, collect the error messages // if the validation fails, collect the error messages
// TODO: add translation support for the error messages // TODO: add translation support for the error messages
var errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'")
.ToArray(); .ToArray();
// and return them with a failure result // and return them with a failure result
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"> <Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<BaseOutputPath>$(SolutionDir)..\bin\client\</BaseOutputPath> <BaseOutputPath>$(SolutionDir)..\bin\client\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -22,5 +22,4 @@
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Polly" Version="8.4.1" /> <PackageReference Include="Polly" Version="8.4.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -1,4 +1,4 @@
@page "/library/manage/item" @page "/library/manage/item"
@page "/library/manage/item/{id:guid}" @page "/library/manage/item/{id:guid}"
@using Lumina.Presentation.Web.Common.Enums.AudioLibrary @using Lumina.Presentation.Web.Common.Enums.AudioLibrary
@@ -51,7 +51,7 @@
<td>@item.Column1</td> <td>@item.Column1</td>
<td>@item.Column2</td> <td>@item.Column2</td>
<td> <td>
<MultiDirectorySelector /> @* <MultiDirectorySelector /> *@
</td> </td>
</tr> </tr>
} }
@@ -165,14 +165,19 @@
// Perform save operation // Perform save operation
isSaving = false; isSaving = false;
Console.WriteLine("saved"); Console.WriteLine("saved");
await Task.CompletedTask;
} }
private async Task CancelOperation() private async Task CancelOperation()
{ {
isCancelling = true; isCancelling = true;
// Perform cancel operation // Perform cancel operation
if (!isCancelling)
isCancelling = false; isCancelling = false;
selectedValue2 = new ComboboxItem<string>();
if (selectedValue2 is not null)
Console.WriteLine("cancelled"); Console.WriteLine("cancelled");
await Task.CompletedTask;
} }
private List<TableItem> tableData = new List<TableItem> private List<TableItem> tableData = new List<TableItem>
@@ -183,8 +188,8 @@
public class TableItem public class TableItem
{ {
public string Column1 { get; set; } public string? Column1 { get; set; }
public string Column2 { get; set; } public string? Column2 { get; set; }
public List<string> Directories { get; set; } public List<string>? Directories { get; set; }
} }
} }
@@ -1,4 +1,4 @@
@page "/library/written-content-library/books-library/books/item/{id:guid}" @page "/library/written-content-library/books-library/books/item/{id:guid}"
@using Lumina.Presentation.Web.Common.Enums.BookLibrary @using Lumina.Presentation.Web.Common.Enums.BookLibrary
@using Lumina.Presentation.Web.Common.Models.Common @using Lumina.Presentation.Web.Common.Models.Common
@@ -17,7 +17,7 @@
<div class="form-group"> <div class="form-group">
<label for="title">Title<span class="mandatory-field">*</span>:</label> <label for="title">Title<span class="mandatory-field">*</span>:</label>
<InputText id="title" @bind-Value="bookRequest.Metadata.Title" class="form-control" /> <InputText id="title" @bind-Value="bookRequest.Metadata!.Title" class="form-control" />
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -33,7 +33,7 @@
<h3>Release Information</h3> <h3>Release Information</h3>
<div class="form-group"> <div class="form-group">
<label for="originalReleaseDate">Original Release Date:</label> <label for="originalReleaseDate">Original Release Date:</label>
<InputDate id="originalReleaseDate" @bind-Value="bookRequest.Metadata.ReleaseInfo.OriginalReleaseDate" class="form-control" /> <InputDate id="originalReleaseDate" @bind-Value="bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate" class="form-control" />
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -42,7 +42,7 @@
</div> </div>
<h3>Genres</h3> <h3>Genres</h3>
@foreach (var genre in bookRequest.Metadata.Genres) @foreach (var genre in bookRequest.Metadata.Genres!)
{ {
<div class="form-group"> <div class="form-group">
<InputText @bind-Value="genre.Name" class="form-control" /> <InputText @bind-Value="genre.Name" class="form-control" />
@@ -53,7 +53,7 @@
<h3>Language</h3> <h3>Language</h3>
<div class="form-group"> <div class="form-group">
<label for="languageCode">Language Code:</label> <label for="languageCode">Language Code:</label>
<InputText id="languageCode" @bind-Value="bookRequest.Metadata.Language.LanguageCode" class="form-control" /> <InputText id="languageCode" @bind-Value="bookRequest.Metadata.Language!.LanguageCode" class="form-control" />
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -80,7 +80,7 @@
<h3>Identifiers</h3> <h3>Identifiers</h3>
<div class="form-group"> <div class="form-group">
<label for="isbn">ISBN:</label> <label for="isbn">ISBN:</label>
<InputText id="isbn" @bind-Value="bookRequest.ISBNs[0].Value" class="form-control" /> <InputText id="isbn" @bind-Value="bookRequest.ISBNs![0].Value" class="form-control" />
<InputSelect @bind-Value="bookRequest.ISBNs[0].Format" class="form-control"> <InputSelect @bind-Value="bookRequest.ISBNs[0].Format" class="form-control">
@foreach (var format in Enum.GetValues(typeof(IsbnFormat))) @foreach (var format in Enum.GetValues(typeof(IsbnFormat)))
{ {
@@ -90,11 +90,11 @@
</div> </div>
<h3>Contributors</h3> <h3>Contributors</h3>
@foreach (var contributor in bookRequest.Contributors) @foreach (var contributor in bookRequest.Contributors!)
{ {
<div class="form-group"> <div class="form-group">
@* <InputText @bind-Value="contributor.Name" placeholder="Name" class="form-control" /> *@ @* <InputText @bind-Value="contributor.Name" placeholder="Name" class="form-control" /> *@
<InputText @bind-Value="contributor.Role.Name" placeholder="Role" class="form-control" /> <InputText @bind-Value="contributor.Role!.Name" placeholder="Role" class="form-control" />
</div> </div>
} }
<button type="button" class="btn btn-secondary" @onclick="AddContributor">Add Contributor</button> <button type="button" class="btn btn-secondary" @onclick="AddContributor">Add Contributor</button>
@@ -117,12 +117,12 @@
private void AddGenre() private void AddGenre()
{ {
bookRequest.Metadata.Genres.Add(new GenreModel()); bookRequest.Metadata!.Genres!.Add(new GenreModel());
} }
private void AddContributor() private void AddContributor()
{ {
bookRequest.Contributors.Add(new MediaContributorModel { Role = new MediaContributorRoleModel() }); bookRequest.Contributors!.Add(new MediaContributorModel { Role = new MediaContributorRoleModel() });
} }
private async Task HandleValidSubmit() private async Task HandleValidSubmit()
+2 -2
View File
@@ -19,7 +19,7 @@ public class Program
/// <param name="args">Optional command line arguments.</param> /// <param name="args">Optional command line arguments.</param>
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
var builder = WebAssemblyHostBuilder.CreateDefault(args); WebAssemblyHostBuilder builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app"); builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after"); builder.RootComponents.Add<HeadOutlet>("head::after");
@@ -29,7 +29,7 @@ public class Program
//builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); //builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
var webAssemblyHost = builder.Build(); WebAssemblyHost webAssemblyHost = builder.Build();
await webAssemblyHost.RunAsync().ConfigureAwait(false); await webAssemblyHost.RunAsync().ConfigureAwait(false);
} }
+5
View File
@@ -73,6 +73,11 @@ Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-co
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Contracts", "Lumina.Contracts\Lumina.Contracts.csproj", "{6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Contracts", "Lumina.Contracts\Lumina.Contracts.csproj", "{6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5DD47F82-699B-4E71-A10A-238E80EA5814}"
ProjectSection(SolutionItems) = preProject
..\.editorconfig = ..\.editorconfig
EndProjectSection
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -16,7 +16,7 @@ public class RepositoryFactoryTests
public void RepositoryFactoryImplementsRepositoryFactoryInterface_InterfaceIsImplemented_ReturnsTrue() public void RepositoryFactoryImplementsRepositoryFactoryInterface_InterfaceIsImplemented_ReturnsTrue()
{ {
// Arrange // Arrange
var repositoryFactory = new RepositoryFactory(null!); RepositoryFactory repositoryFactory = new(null!);
// Assert // Assert
Assert.True(repositoryFactory is IRepositoryFactory); Assert.True(repositoryFactory is IRepositoryFactory);
@@ -20,10 +20,10 @@ public class UnitOfWorkTests
public void UnitOfWorkImplementsUnitOfWorkInterface_InterfaceIsImplemented_ReturnsTrue() public void UnitOfWorkImplementsUnitOfWorkInterface_InterfaceIsImplemented_ReturnsTrue()
{ {
// Arrange // Arrange
var services = new ServiceCollection(); ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services); DataAccessLayerServices.AddDataAccessLayerServices(services);
var serviceProvider = services.BuildServiceProvider(); ServiceProvider serviceProvider = services.BuildServiceProvider();
var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>(); UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
// Assert // Assert
Assert.True(unitOfWork is IUnitOfWork); Assert.True(unitOfWork is IUnitOfWork);
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more