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
138 files changed
+1799 -1629

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>();
@@ -108,7 +108,7 @@ public class BookMappingConfig : IRegister
Optional<BookFormat>.FromNullable(!string.IsNullOrWhiteSpace(src.Format) ? Enum.Parse<BookFormat>(src.Format) : default), Optional<BookFormat>.FromNullable(!string.IsNullOrWhiteSpace(src.Format) ? Enum.Parse<BookFormat>(src.Format) : default),
Optional<string>.FromNullable(src.Edition), Optional<string>.FromNullable(src.Edition),
Optional<int>.FromNullable(src.VolumeNumber), Optional<int>.FromNullable(src.VolumeNumber),
Optional<BookSeries>.None(), Optional<BookSeries>.None(),
Optional<string>.FromNullable(src.ASIN), Optional<string>.FromNullable(src.ASIN),
Optional<string>.FromNullable(src.GoodreadsId), Optional<string>.FromNullable(src.GoodreadsId),
Optional<string>.FromNullable(src.LCCN), Optional<string>.FromNullable(src.LCCN),
@@ -121,7 +121,7 @@ public class BookMappingConfig : IRegister
src.Created, src.Created,
Optional<DateTime>.FromNullable(src.Updated), Optional<DateTime>.FromNullable(src.Updated),
src.ISBNs.Select(i => Isbn.Create(i.Value!, i.Format ?? default).Value).ToList(), src.ISBNs.Select(i => Isbn.Create(i.Value!, i.Format ?? default).Value).ToList(),
new List<MediaContributorId>(), new List<MediaContributorId>(),
src.Ratings.Select(r => BookRating.Create( src.Ratings.Select(r => BookRating.Create(
r.Value ?? default, r.Value ?? default,
r.MaxValue ?? default, r.MaxValue ?? default,
@@ -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;
@@ -126,7 +126,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookModel>
ratingBuilder.Property(rating => rating.Source) ratingBuilder.Property(rating => rating.Source)
.HasConversion<string>() .HasConversion<string>()
.HasMaxLength(50) .HasMaxLength(50)
.IsRequired(); .IsRequired();
}); });
@@ -139,12 +139,12 @@ public class BookConfiguration : IEntityTypeConfiguration<BookModel>
isbnBuilder.Property(isbn => isbn.Value) isbnBuilder.Property(isbn => isbn.Value)
.HasColumnName("ISBN") .HasColumnName("ISBN")
.HasMaxLength(13) .HasMaxLength(13)
.IsRequired(); .IsRequired();
isbnBuilder.Property(isbn => isbn.Format) isbnBuilder.Property(isbn => isbn.Format)
.HasConversion<string>() .HasConversion<string>()
.HasMaxLength(6) .HasMaxLength(6)
.IsRequired(); .IsRequired();
}); });
} }
@@ -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,216 +1,206 @@
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 />
public partial class InitialMigration : Migration
{ {
/// <inheritdoc /> /// <inheritdoc />
public partial class InitialMigration : Migration protected override void Up(MigrationBuilder migrationBuilder)
{ {
/// <inheritdoc /> migrationBuilder.CreateTable(
protected override void Up(MigrationBuilder migrationBuilder) name: "Books",
{ columns: table => new
migrationBuilder.CreateTable( {
name: "Books", Id = table.Column<Guid>(type: "TEXT", nullable: false),
columns: table => new Title = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
{ OriginalTitle = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true),
Id = table.Column<Guid>(type: "TEXT", nullable: false), Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
Title = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false), OriginalReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
OriginalTitle = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true), OriginalReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true), ReReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
OriginalReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true), ReReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
OriginalReleaseYear = table.Column<int>(type: "INTEGER", nullable: true), ReleaseCountry = table.Column<string>(type: "TEXT", nullable: true),
ReReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true), ReleaseVersion = table.Column<string>(type: "TEXT", nullable: true),
ReReleaseYear = table.Column<int>(type: "INTEGER", nullable: true), LanguageCode = table.Column<string>(type: "TEXT", nullable: true),
ReleaseCountry = table.Column<string>(type: "TEXT", nullable: true), LanguageName = table.Column<string>(type: "TEXT", nullable: true),
ReleaseVersion = table.Column<string>(type: "TEXT", nullable: true), LanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
LanguageCode = table.Column<string>(type: "TEXT", nullable: true), OriginalLanguageCode = table.Column<string>(type: "TEXT", nullable: true),
LanguageName = table.Column<string>(type: "TEXT", nullable: true), OriginalLanguageName = table.Column<string>(type: "TEXT", nullable: true),
LanguageNativeName = table.Column<string>(type: "TEXT", nullable: true), OriginalLanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageCode = table.Column<string>(type: "TEXT", nullable: true), Publisher = table.Column<string>(type: "TEXT", maxLength: 100, nullable: true),
OriginalLanguageName = table.Column<string>(type: "TEXT", nullable: true), PageCount = table.Column<int>(type: "INTEGER", nullable: true),
OriginalLanguageNativeName = table.Column<string>(type: "TEXT", nullable: true), Format = table.Column<string>(type: "TEXT", nullable: false),
Publisher = table.Column<string>(type: "TEXT", maxLength: 100, nullable: true), Edition = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
PageCount = table.Column<int>(type: "INTEGER", nullable: true), VolumeNumber = table.Column<int>(type: "INTEGER", nullable: true),
Format = table.Column<string>(type: "TEXT", nullable: false), ASIN = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true),
Edition = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true), GoodreadsId = table.Column<string>(type: "TEXT", nullable: true),
VolumeNumber = table.Column<int>(type: "INTEGER", nullable: true), LCCN = table.Column<string>(type: "TEXT", nullable: true),
ASIN = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true), OCLCNumber = table.Column<string>(type: "TEXT", nullable: true),
GoodreadsId = table.Column<string>(type: "TEXT", nullable: true), OpenLibraryId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
LCCN = table.Column<string>(type: "TEXT", nullable: true), LibraryThingId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
OCLCNumber = table.Column<string>(type: "TEXT", nullable: true), GoogleBooksId = table.Column<string>(type: "TEXT", maxLength: 12, nullable: true),
OpenLibraryId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true), BarnesAndNobleId = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true),
LibraryThingId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true), AppleBooksId = table.Column<string>(type: "TEXT", nullable: true),
GoogleBooksId = table.Column<string>(type: "TEXT", maxLength: 12, nullable: true), Created = table.Column<DateTime>(type: "TEXT", nullable: false),
BarnesAndNobleId = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true), Updated = table.Column<DateTime>(type: "TEXT", nullable: true)
AppleBooksId = table.Column<string>(type: "TEXT", nullable: true), },
Created = table.Column<DateTime>(type: "TEXT", nullable: false), constraints: table => table.PrimaryKey("PK_Books", x => x.Id));
Updated = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Books", x => x.Id);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "Genres", name: "Genres",
columns: table => new columns: table => new
{ {
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",
columns: table => new columns: table => new
{ {
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",
columns: table => new columns: table => new
{ {
Id = table.Column<int>(type: "INTEGER", nullable: false) Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true), .Annotation("Sqlite:Autoincrement", true),
ISBN = table.Column<string>(type: "TEXT", maxLength: 13, nullable: false), ISBN = table.Column<string>(type: "TEXT", maxLength: 13, nullable: false),
Format = table.Column<string>(type: "TEXT", maxLength: 6, nullable: false), Format = table.Column<string>(type: "TEXT", maxLength: 6, nullable: false),
BookId = table.Column<Guid>(type: "TEXT", nullable: false) BookId = table.Column<Guid>(type: "TEXT", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_BookISBNs", x => x.Id); table.PrimaryKey("PK_BookISBNs", x => x.Id);
table.ForeignKey( table.ForeignKey(
name: "FK_BookISBNs_Books_BookId", name: "FK_BookISBNs_Books_BookId",
column: x => x.BookId, column: x => x.BookId,
principalTable: "Books", principalTable: "Books",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "BookRatings", name: "BookRatings",
columns: table => new columns: table => new
{ {
Id = table.Column<int>(type: "INTEGER", nullable: false) Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true), .Annotation("Sqlite:Autoincrement", true),
Source = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false), Source = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
BookId = table.Column<Guid>(type: "TEXT", nullable: false), BookId = table.Column<Guid>(type: "TEXT", nullable: false),
Value = table.Column<decimal>(type: "decimal(3,2)", nullable: false), Value = table.Column<decimal>(type: "decimal(3,2)", nullable: false),
MaxValue = table.Column<decimal>(type: "decimal(3,2)", nullable: false), MaxValue = table.Column<decimal>(type: "decimal(3,2)", nullable: false),
VoteCount = table.Column<int>(type: "INTEGER", nullable: true) VoteCount = table.Column<int>(type: "INTEGER", nullable: true)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_BookRatings", x => x.Id); table.PrimaryKey("PK_BookRatings", x => x.Id);
table.ForeignKey( table.ForeignKey(
name: "FK_BookRatings_Books_BookId", name: "FK_BookRatings_Books_BookId",
column: x => x.BookId, column: x => x.BookId,
principalTable: "Books", principalTable: "Books",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "BookGenres", name: "BookGenres",
columns: table => new columns: table => new
{ {
BookId = table.Column<Guid>(type: "TEXT", nullable: false), BookId = table.Column<Guid>(type: "TEXT", nullable: false),
GenreId = table.Column<string>(type: "TEXT", nullable: false) GenreId = table.Column<string>(type: "TEXT", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_BookGenres", x => new { x.BookId, x.GenreId }); table.PrimaryKey("PK_BookGenres", x => new { x.BookId, x.GenreId });
table.ForeignKey( table.ForeignKey(
name: "FK_BookGenres_Books_BookId", name: "FK_BookGenres_Books_BookId",
column: x => x.BookId, column: x => x.BookId,
principalTable: "Books", principalTable: "Books",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
table.ForeignKey( table.ForeignKey(
name: "FK_BookGenres_Genres_GenreId", name: "FK_BookGenres_Genres_GenreId",
column: x => x.GenreId, column: x => x.GenreId,
principalTable: "Genres", principalTable: "Genres",
principalColumn: "Name", principalColumn: "Name",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "BookTags", name: "BookTags",
columns: table => new columns: table => new
{ {
BookId = table.Column<Guid>(type: "TEXT", nullable: false), BookId = table.Column<Guid>(type: "TEXT", nullable: false),
TagId = table.Column<string>(type: "TEXT", nullable: false) TagId = table.Column<string>(type: "TEXT", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_BookTags", x => new { x.BookId, x.TagId }); table.PrimaryKey("PK_BookTags", x => new { x.BookId, x.TagId });
table.ForeignKey( table.ForeignKey(
name: "FK_BookTags_Books_BookId", name: "FK_BookTags_Books_BookId",
column: x => x.BookId, column: x => x.BookId,
principalTable: "Books", principalTable: "Books",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
table.ForeignKey( table.ForeignKey(
name: "FK_BookTags_Tags_TagId", name: "FK_BookTags_Tags_TagId",
column: x => x.TagId, column: x => x.TagId,
principalTable: "Tags", principalTable: "Tags",
principalColumn: "Name", principalColumn: "Name",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_BookGenres_GenreId", name: "IX_BookGenres_GenreId",
table: "BookGenres", table: "BookGenres",
column: "GenreId"); column: "GenreId");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_BookISBNs_BookId", name: "IX_BookISBNs_BookId",
table: "BookISBNs", table: "BookISBNs",
column: "BookId"); column: "BookId");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_BookRatings_BookId", name: "IX_BookRatings_BookId",
table: "BookRatings", table: "BookRatings",
column: "BookId"); column: "BookId");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_BookTags_TagId", name: "IX_BookTags_TagId",
table: "BookTags", table: "BookTags",
column: "TagId"); column: "TagId");
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "BookGenres"); name: "BookGenres");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "BookISBNs"); name: "BookISBNs");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "BookRatings"); name: "BookRatings");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "BookTags"); name: "BookTags");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Genres"); name: "Genres");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Books"); name: "Books");
migrationBuilder.DropTable( migrationBuilder.DropTable(
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;
@@ -13,7 +13,7 @@ public static partial class Errors
{ {
#region ==================================================================== PROPERTIES ================================================================================= #region ==================================================================== PROPERTIES =================================================================================
public static Error ContributorsListCannotBeNull => Error.Validation(nameof(ContributorsListCannotBeNull)); public static Error ContributorsListCannotBeNull => Error.Validation(nameof(ContributorsListCannotBeNull));
public static Error ContributorNameCannotBeEmpty => Error.Validation(nameof(ContributorNameCannotBeEmpty)); public static Error ContributorNameCannotBeEmpty => Error.Validation(nameof(ContributorNameCannotBeEmpty));
public static Error ContributorDisplayNameCannotBeEmpty => Error.Validation(nameof(ContributorDisplayNameCannotBeEmpty)); public static Error ContributorDisplayNameCannotBeEmpty => Error.Validation(nameof(ContributorDisplayNameCannotBeEmpty));
public static Error ContributorDisplayNameMustBeMaximum100CharactersLong => Error.Validation(nameof(ContributorDisplayNameMustBeMaximum100CharactersLong)); public static Error ContributorDisplayNameMustBeMaximum100CharactersLong => Error.Validation(nameof(ContributorDisplayNameMustBeMaximum100CharactersLong));
@@ -21,8 +21,8 @@ public abstract class AggregateRoot<TId> : Entity<TId> where TId : notnull
/// Initializes a new instance of the <see cref="AggregateRoot{TId}"/> class. /// Initializes a new instance of the <see cref="AggregateRoot{TId}"/> class.
/// </summary> /// </summary>
protected AggregateRoot() // only needed during reflection protected AggregateRoot() // only needed during reflection
{ {
} }
#pragma warning restore CS8618 #pragma warning restore CS8618
#endregion #endregion
@@ -42,8 +42,8 @@ public abstract class Entity<TId> : IEquatable<Entity<TId>> where TId : notnull
/// Initializes a new instance of the <see cref="Entity{TId}"/> class. /// Initializes a new instance of the <see cref="Entity{TId}"/> class.
/// </summary> /// </summary>
protected Entity() // only needed during reflection protected Entity() // only needed during reflection
{ {
} }
#pragma warning restore CS8618 #pragma warning restore CS8618
#endregion #endregion
@@ -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());
} }
@@ -16,17 +16,11 @@ public readonly struct Optional<TValue>
/// Gets a value indicating whether this structure has a value. /// Gets a value indicating whether this structure has a value.
/// </summary> /// </summary>
public bool HasValue { get; } public bool HasValue { get; }
/// <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 =====================================================================================
@@ -18,12 +18,12 @@ public abstract class BaseMetadata : ValueObject
private readonly List<Tag> _tags; private readonly List<Tag> _tags;
private readonly List<Genre> _genres; private readonly List<Genre> _genres;
#endregion #endregion
#region ==================================================================== PROPERTIES ================================================================================= #region ==================================================================== PROPERTIES =================================================================================
/// <summary> /// <summary>
/// Gets the title of the media item. /// Gets the title of the media item.
/// </summary> /// </summary>
public string Title { get; private set;} public string Title { get; private set; }
/// <summary> /// <summary>
/// Gets the original title of the media item. /// Gets the original title of the media item.
@@ -44,7 +44,7 @@ public abstract class BaseMetadata : ValueObject
/// Gets the optional language of the media item. /// Gets the optional language of the media item.
/// </summary> /// </summary>
public Optional<LanguageInfo> Language { get; private set; } public Optional<LanguageInfo> Language { get; private set; }
/// <summary> /// <summary>
/// Gets the optional original language of the media item. /// Gets the optional original language of the media item.
/// </summary> /// </summary>
@@ -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 =====================================================================================
@@ -81,13 +75,13 @@ public abstract class BaseMetadata : ValueObject
/// <param name="originalLanguage">The optional original language of the element to which this metadata object belongs to.</param> /// <param name="originalLanguage">The optional original language of the element to which this metadata object belongs to.</param>
/// <exception cref="ArgumentNullException">Thrown when the <see cref="title"/> value is <see langword="null"/></exception> /// <exception cref="ArgumentNullException">Thrown when the <see cref="title"/> value is <see langword="null"/></exception>
protected BaseMetadata( protected BaseMetadata(
string title, string title,
Optional<string> originalTitle, Optional<string> originalTitle,
Optional<string> description, Optional<string> description,
ReleaseInfo releaseInfo, ReleaseInfo releaseInfo,
List<Genre> genres, List<Genre> genres,
List<Tag> tags, List<Tag> tags,
Optional<LanguageInfo> language, Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage) Optional<LanguageInfo> originalLanguage)
{ {
Title = title ?? throw new ArgumentNullException(nameof(title)); Title = title ?? throw new ArgumentNullException(nameof(title));
@@ -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
} }
@@ -59,11 +59,11 @@ public class ReleaseInfo : ValueObject
/// <param name="releaseCountry">The optional country or region of release.</param> /// <param name="releaseCountry">The optional country or region of release.</param>
/// <param name="releaseVersion">The optional release version or edition.</param> /// <param name="releaseVersion">The optional release version or edition.</param>
private ReleaseInfo( private ReleaseInfo(
Optional<DateOnly> originalReleaseDate, Optional<DateOnly> originalReleaseDate,
Optional<int> originalReleaseYear, Optional<int> originalReleaseYear,
Optional<DateOnly> reReleaseDate, Optional<DateOnly> reReleaseDate,
Optional<int> reReleaseYear, Optional<int> reReleaseYear,
Optional<string> releaseCountry, Optional<string> releaseCountry,
Optional<string> releaseVersion) Optional<string> releaseVersion)
{ {
OriginalReleaseDate = originalReleaseDate; OriginalReleaseDate = originalReleaseDate;
@@ -89,22 +89,22 @@ public class ReleaseInfo : ValueObject
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="ReleaseInfo"/>, or an error message. /// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="ReleaseInfo"/>, or an error message.
/// </returns> /// </returns>
public static ErrorOr<ReleaseInfo> Create( public static ErrorOr<ReleaseInfo> Create(
Optional<DateOnly> originalReleaseDate, Optional<DateOnly> originalReleaseDate,
Optional<int> originalReleaseYear, Optional<int> originalReleaseYear,
Optional<DateOnly> reReleaseDate, Optional<DateOnly> reReleaseDate,
Optional<int> reReleaseYear, Optional<int> reReleaseYear,
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/>
@@ -64,19 +64,19 @@ public class AudioMetadata : BaseMetadata
/// <param name="genres">The genres of the audio.</param> /// <param name="genres">The genres of the audio.</param>
/// <param name="tags">The tags associated with the audio.</param> /// <param name="tags">The tags associated with the audio.</param>
public AudioMetadata( public AudioMetadata(
string title, string title,
Optional<string> originalTitle, Optional<string> originalTitle,
int durationInSeconds, int durationInSeconds,
int sampleRate, int sampleRate,
int channels, int channels,
ReleaseInfo releaseInfo, ReleaseInfo releaseInfo,
Optional<string> description, Optional<string> description,
List<Genre> genres, List<Genre> genres,
List<Tag> tags, List<Tag> tags,
Optional<LanguageInfo> language, Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage, Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth, Optional<int> bitDepth,
Optional<string> audioCodec, Optional<string> audioCodec,
Optional<int> bitrate) Optional<int> bitrate)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{ {
@@ -110,43 +110,43 @@ public class AudioMetadata : BaseMetadata
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="AudioMetadata"/>, or an error message. /// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="AudioMetadata"/>, or an error message.
/// </returns> /// </returns>
public static ErrorOr<AudioMetadata> Create( public static ErrorOr<AudioMetadata> Create(
string title, string title,
Optional<string> originalTitle, Optional<string> originalTitle,
int durationInSeconds, int durationInSeconds,
int sampleRate, int sampleRate,
int channels, int channels,
ReleaseInfo release, ReleaseInfo release,
Optional<string> Optional<string>
description, description,
List<Genre> genres, List<Genre> genres,
List<Tag> tags, List<Tag> tags,
Optional<LanguageInfo> language, Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage, Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth, Optional<int> bitDepth,
Optional<string> audioCodec, Optional<string> audioCodec,
Optional<int> bitrate) Optional<int> bitrate)
{ {
return new AudioMetadata( return new AudioMetadata(
title, title,
originalTitle, originalTitle,
durationInSeconds, durationInSeconds,
sampleRate, sampleRate,
channels, channels,
release, release,
description, description,
genres, genres,
tags, tags,
language, language,
originalLanguage, originalLanguage,
bitDepth, bitDepth,
audioCodec, audioCodec,
bitrate); bitrate);
} }
/// <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;
@@ -19,7 +19,7 @@ public sealed class Directory : FileSystemItem
#region ================================================================== FIELD MEMBERS ================================================================================ #region ================================================================== FIELD MEMBERS ================================================================================
private readonly List<FileSystemItem> _items = []; private readonly List<FileSystemItem> _items = [];
#endregion #endregion
#region ==================================================================== PROPERTIES ================================================================================= #region ==================================================================== PROPERTIES =================================================================================
/// <summary> /// <summary>
/// Gets or sets the creation date of the file system item. Can be optional if the information is not available. /// Gets or sets the creation date of the file system item. Can be optional if the information is not available.
@@ -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 =====================================================================================
@@ -35,7 +32,7 @@ public sealed class WindowsRootItem : FileSystemItem
/// <param name="id">The unique identifier of the root item in the file system path.</param> /// <param name="id">The unique identifier of the root item in the file system path.</param>
/// <param name="name">The name of the root item.</param> /// <param name="name">The name of the root item.</param>
private WindowsRootItem(FileSystemPathId id, string name) : base(id, name, FileSystemItemType.Root) private WindowsRootItem(FileSystemPathId id, string name) : base(id, name, FileSystemItemType.Root)
{ {
} }
#endregion #endregion
@@ -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>
@@ -84,9 +82,9 @@ public class DirectoryService : IDirectoryService
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{ {
ErrorOr<Directory> errorDirResult = Directory.Create(subPath, !dirNameResult.IsError ? dirNameResult.Value : null!, ErrorOr<Directory> errorDirResult = Directory.Create(subPath, !dirNameResult.IsError ? dirNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(), !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None()); !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None());
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) if (setStatusResult.IsError)
@@ -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>
@@ -148,14 +144,12 @@ public class DirectoryService : IDirectoryService
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{ {
ErrorOr<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, ErrorOr<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(), !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None()); !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None());
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>
@@ -298,14 +290,12 @@ public class DirectoryService : IDirectoryService
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{ {
ErrorOr<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, ErrorOr<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(), !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None()); !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None());
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)
{ {
@@ -85,7 +83,7 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{ {
ErrorOr<File> errorFileResult = File.Create(filePath, !fileNameResult.IsError ? fileNameResult.Value : null!, ErrorOr<File> errorFileResult = File.Create(filePath, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(), !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size); !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
if (errorFileResult.IsError) if (errorFileResult.IsError)
return errorFileResult.Errors; return errorFileResult.Errors;
@@ -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)
@@ -155,14 +153,12 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{ {
ErrorOr<File> errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, ErrorOr<File> errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(), !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size); !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
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)
@@ -219,14 +215,12 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{ {
ErrorOr<File> errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, ErrorOr<File> errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(), !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size); !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
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)
@@ -279,14 +271,12 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{ {
ErrorOr<File> errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, ErrorOr<File> errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(), !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size); !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
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>
@@ -29,7 +29,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param> /// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
public FileSystemPermissionsService(IPlatformContextManager platformContextManager) public FileSystemPermissionsService(IPlatformContextManager platformContextManager)
{ {
_platformContextManager = platformContextManager; _platformContextManager = platformContextManager;
} }
#endregion #endregion
@@ -85,7 +85,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
modes = AccessModes.F_OK; // check existence, not an exact match but the closest modes = AccessModes.F_OK; // check existence, not an exact match but the closest
break; break;
case FileAccessMode.Delete: case FileAccessMode.Delete:
if (fileInfo.FileType == FileTypes.Directory) if (fileInfo.FileType == FileTypes.Directory)
return fileInfo.CanAccess(AccessModes.W_OK | AccessModes.X_OK); // to delete a directory, we need write and execute permissions on the directory itself return fileInfo.CanAccess(AccessModes.W_OK | AccessModes.X_OK); // to delete a directory, we need write and execute permissions on the directory itself
else else
{ {
@@ -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;
} }
@@ -203,7 +203,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
} }
} }
catch catch
{ {
return false; return false;
} }
@@ -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
@@ -9,7 +9,7 @@ namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.S
/// <summary> /// <summary>
/// Interface for the service for handling thumbnails. /// Interface for the service for handling thumbnails.
/// </summary> /// </summary>
public interface IThumbnailService public interface IThumbnailService
{ {
#region ===================================================================== METHODS =================================================================================== #region ===================================================================== METHODS ===================================================================================
/// <summary> /// <summary>
@@ -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
@@ -166,7 +167,7 @@ public class ThumbnailService : IThumbnailService
break; break;
default: default:
return imageBytes; // for unsupported formats, just return the original bytes return imageBytes; // for unsupported formats, just return the original bytes
} }
return outputMemoryStream.ToArray(); return outputMemoryStream.ToArray();
} }
@@ -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}\";
@@ -15,7 +15,7 @@ public class WindowsPlatformContext : IWindowsPlatformContext
/// Gets the platform type, which is Windows for this context. /// Gets the platform type, which is Windows for this context.
/// </summary> /// </summary>
public PlatformType Platform { get; } = PlatformType.Windows; public PlatformType Platform { get; } = PlatformType.Windows;
/// <summary> /// <summary>
/// Gets the path strategy for Windows platforms. /// Gets the path strategy for Windows platforms.
/// </summary> /// </summary>
@@ -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
} }
@@ -20,37 +20,37 @@ public class StreamInfo : ValueObject
/// Gets the id of the stream. /// Gets the id of the stream.
/// </summary> /// </summary>
public string StreamId { get; } public string StreamId { get; }
/// <summary> /// <summary>
/// Gets the MimeType of the stream. /// Gets the MimeType of the stream.
/// </summary> /// </summary>
public string MimeType { get; } public string MimeType { get; }
/// <summary> /// <summary>
/// Gets the bitrate of the stream. /// Gets the bitrate of the stream.
/// </summary> /// </summary>
public int Bitrate { get; } public int Bitrate { get; }
/// <summary> /// <summary>
/// Gets the codec of the stream. /// Gets the codec of the stream.
/// </summary> /// </summary>
public string Codec { get; } public string Codec { get; }
/// <summary> /// <summary>
/// Gets the optional resolution of the stream. /// Gets the optional resolution of the stream.
/// </summary> /// </summary>
public Optional<string> Resolution { get; } public Optional<string> Resolution { get; }
/// <summary> /// <summary>
/// Gets the optional frame rate of the stream. /// Gets the optional frame rate of the stream.
/// </summary> /// </summary>
public Optional<float> FrameRate { get; } public Optional<float> FrameRate { get; }
/// <summary> /// <summary>
/// Gets the optional sample rate of the stream. /// Gets the optional sample rate of the stream.
/// </summary> /// </summary>
public Optional<int> SampleRate { get; } public Optional<int> SampleRate { get; }
/// <summary> /// <summary>
/// Gets the optional channels of the stream. /// Gets the optional channels of the stream.
/// </summary> /// </summary>
@@ -70,13 +70,13 @@ public class StreamInfo : ValueObject
/// <param name="sampleRate">The sample rate of the stream (for audio).</param> /// <param name="sampleRate">The sample rate of the stream (for audio).</param>
/// <param name="channels">The number of channels (for audio).</param> /// <param name="channels">The number of channels (for audio).</param>
private StreamInfo( private StreamInfo(
string streamId, string streamId,
string mimeType, string mimeType,
int bitrate, int bitrate,
string codec, string codec,
Optional<string> resolution, Optional<string> resolution,
Optional<float> frameRate, Optional<float> frameRate,
Optional<int> sampleRate, Optional<int> sampleRate,
Optional<int> channels) Optional<int> channels)
{ {
StreamId = streamId; StreamId = streamId;
@@ -106,24 +106,24 @@ public class StreamInfo : ValueObject
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="StreamInfo"/>, or an error message. /// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="StreamInfo"/>, or an error message.
/// </returns> /// </returns>
public static ErrorOr<StreamInfo> Create( public static ErrorOr<StreamInfo> Create(
string streamId, string streamId,
string mimeType, string mimeType,
int bitrate, int bitrate,
string codec, string codec,
Optional<string> resolution, Optional<string> resolution,
Optional<float> frameRate, Optional<float> frameRate,
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/>
public override IEnumerable<object> GetEqualityComponents() public override IEnumerable<object> GetEqualityComponents()
{ {
@@ -53,10 +53,10 @@ public class MediaContributor : AggregateRoot<MediaContributorId>
/// <param name="dateOfBirth">The optional date of birth of the contributor.</param> /// <param name="dateOfBirth">The optional date of birth of the contributor.</param>
/// <param name="dateOfBirth">The optional date of death of the contributor.</param> /// <param name="dateOfBirth">The optional date of death of the contributor.</param>
private MediaContributor( private MediaContributor(
MediaContributorId id, MediaContributorId id,
MediaContributorName name, MediaContributorName name,
MediaContributorRole role, MediaContributorRole role,
Optional<DateOnly> dateOfBirth, Optional<DateOnly> dateOfBirth,
Optional<DateOnly> dateOfDeath) Optional<DateOnly> dateOfDeath)
{ {
Id = id; Id = id;
@@ -87,10 +87,10 @@ public class MediaContributor : AggregateRoot<MediaContributorId>
/// <param name="name">The name of the contributor.</param> /// <param name="name">The name of the contributor.</param>
/// <returns>The created <see cref="MediaContributor"/> instance.</returns> /// <returns>The created <see cref="MediaContributor"/> instance.</returns>
public static ErrorOr<MediaContributor> Create( public static ErrorOr<MediaContributor> Create(
MediaContributorId id, MediaContributorId id,
MediaContributorName name, MediaContributorName name,
MediaContributorRole role, MediaContributorRole role,
Optional<DateOnly> dateOfBirth, Optional<DateOnly> dateOfBirth,
Optional<DateOnly> dateOfDeath) Optional<DateOnly> dateOfDeath)
{ {
return new MediaContributor(id, name, role, dateOfBirth, dateOfDeath); return new MediaContributor(id, name, role, dateOfBirth, dateOfDeath);
@@ -49,7 +49,7 @@ public sealed class MediaContributorName : ValueObject
public static ErrorOr<MediaContributorName> Create(string displayName, Optional<string> legalName) public static ErrorOr<MediaContributorName> Create(string displayName, Optional<string> legalName)
{ {
// TODO: enforce invariants // TODO: enforce invariants
return new MediaContributorName(displayName, legalName); return new MediaContributorName(displayName, legalName);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -29,7 +29,7 @@ public sealed class MediaContributorId : EntityId<Guid>
public static MediaContributorId CreateUnique() public static MediaContributorId CreateUnique()
{ {
// TODO: enforce invariants // TODO: enforce invariants
return new MediaContributorId(Guid.NewGuid()); return new MediaContributorId(Guid.NewGuid());
} }
/// <summary> /// <summary>
@@ -40,7 +40,7 @@ public sealed class MediaContributorId : EntityId<Guid>
public static MediaContributorId Create(Guid value) public static MediaContributorId Create(Guid value)
{ {
// TODO: enforce invariants // TODO: enforce invariants
return new MediaContributorId(value); return new MediaContributorId(value);
} }
/// <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 =====================================================================================
@@ -66,7 +60,7 @@ public sealed class Movie : Entity<MovieId>
/// </summary> /// </summary>
private Movie() // only needed during reflection private Movie() // only needed during reflection
{ {
} }
#pragma warning restore CS8618 #pragma warning restore CS8618
#endregion #endregion
@@ -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
} }
@@ -12,7 +12,7 @@ namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.Value
/// </summary> /// </summary>
[DebuggerDisplay("{Value}")] [DebuggerDisplay("{Value}")]
public sealed class MovieId : EntityId<Guid> public sealed class MovieId : EntityId<Guid>
{ {
#region ====================================================================== CTOR ===================================================================================== #region ====================================================================== CTOR =====================================================================================
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="MovieId"/> class. /// Initializes a new instance of the <see cref="MovieId"/> class.
@@ -31,7 +31,7 @@ public sealed class MovieId : EntityId<Guid>
public static MovieId CreateUnique() public static MovieId CreateUnique()
{ {
// TODO: enforce invariants // TODO: enforce invariants
return new MovieId(Guid.NewGuid()); return new MovieId(Guid.NewGuid());
} }
/// <summary> /// <summary>
@@ -42,7 +42,7 @@ public sealed class MovieId : EntityId<Guid>
public static MovieId Create(Guid value) public static MovieId Create(Guid value)
{ {
// TODO: enforce invariants // TODO: enforce invariants
return new MovieId(value); return new MovieId(value);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -60,18 +60,18 @@ public class VideoMetadata : BaseMetadata
/// <param name="genres">The genres of the video.</param> /// <param name="genres">The genres of the video.</param>
/// <param name="tags">The tags associated with the video.</param> /// <param name="tags">The tags associated with the video.</param>
private VideoMetadata( private VideoMetadata(
string title, string title,
Optional<string> originalTitle, Optional<string> originalTitle,
int durationInSeconds, int durationInSeconds,
string resolution, string resolution,
Optional<string> description, Optional<string> description,
ReleaseInfo releaseInfo, ReleaseInfo releaseInfo,
Optional<LanguageInfo> language, Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage, Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate, Optional<float> frameRate,
Optional<string> videoCodec, Optional<string> videoCodec,
Optional<string> audioCodec, Optional<string> audioCodec,
List<Genre> genres, List<Genre> genres,
List<Tag> tags) List<Tag> tags)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{ {
@@ -104,18 +104,18 @@ public class VideoMetadata : BaseMetadata
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="VideoMetadata"/>, or an error message. /// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="VideoMetadata"/>, or an error message.
/// </returns> /// </returns>
public static ErrorOr<VideoMetadata> Create( public static ErrorOr<VideoMetadata> Create(
string title, string title,
Optional<string> originalTitle, Optional<string> originalTitle,
int durationInSeconds, int durationInSeconds,
string resolution, string resolution,
Optional<string> description, Optional<string> description,
ReleaseInfo releaseInfo, ReleaseInfo releaseInfo,
Optional<LanguageInfo> language, Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage, Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate, Optional<float> frameRate,
Optional<string> videoCodec, Optional<string> videoCodec,
Optional<string> audioCodec, Optional<string> audioCodec,
List<Genre> genres, List<Genre> genres,
List<Tag> tags) List<Tag> tags)
{ {
return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, description, releaseInfo, return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, description, releaseInfo,
@@ -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 =====================================================================================
@@ -69,9 +66,9 @@ public sealed class BookSeries : Entity<BookSeriesId>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message. /// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message.
/// </returns> /// </returns>
public static ErrorOr<BookSeries> Create( public static ErrorOr<BookSeries> Create(
BookSeriesId id, BookSeriesId id,
WrittenContentMetadata metadata, WrittenContentMetadata metadata,
bool isComplete, bool isComplete,
List<Book> books) List<Book> books)
{ {
// TODO: enforce invariants // TODO: enforce invariants
@@ -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
} }
@@ -14,7 +14,7 @@ public interface IBookLibraryService
/// Gets the collection of books in the library. /// Gets the collection of books in the library.
/// </summary> /// </summary>
ICollection<Book> Books { get; } ICollection<Book> Books { get; }
// ICollection<BookSeries> Series { get; } // ICollection<BookSeries> Series { get; }
#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/>
@@ -48,7 +48,7 @@ public class WrittenContentMetadata : BaseMetadata
ReleaseInfo releaseInfo, ReleaseInfo releaseInfo,
List<Genre> genres, List<Genre> genres,
List<Tag> tags, List<Tag> tags,
Optional<LanguageInfo> language, Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage, Optional<LanguageInfo> originalLanguage,
Optional<string> publisher, Optional<string> publisher,
Optional<int> pageCount) Optional<int> pageCount)
@@ -88,23 +88,23 @@ 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,
releaseInfo, releaseInfo,
genres, tags, genres, tags,
language, language,
originalLanguage, originalLanguage,
publisher, publisher,
pageCount pageCount
); );
} }
@@ -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,14 +24,14 @@ 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);
configuration.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true); configuration.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.shared.Development.json", optional: true, reloadOnChange: true); configuration.AddJsonFile("appsettings.shared.Development.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
// bind the common settings section // bind the common settings section
services.AddOptions<CommonSettingsModel>() services.AddOptions<CommonSettingsModel>()
.Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName)) .Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName))
@@ -42,7 +42,7 @@ public static class SharedConfiguration
services.AddOptions<DatabaseSettingsModel>() services.AddOptions<DatabaseSettingsModel>()
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName)) .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName))
.ValidateFluently() .ValidateFluently()
.ValidateOnStart(); .ValidateOnStart();
return services; return services;
} }
#endregion #endregion
@@ -52,15 +52,15 @@ 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)
return ValidateOptionsResult.Success; return ValidateOptionsResult.Success;
// 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,8 +36,8 @@ 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));
} }
/// <summary> /// <summary>
@@ -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 =>
@@ -45,7 +42,7 @@ public static class PresentationApiLayerServices
services.AddEndpointsApiExplorer(); services.AddEndpointsApiExplorer();
services.AddSwaggerGen(); services.AddSwaggerGen();
services.ConfigureOptions<ConfigureSwaggerOptions>(); services.ConfigureOptions<ConfigureSwaggerOptions>();
services.AddApiVersioning(options => services.AddApiVersioning(options =>
{ {
options.DefaultApiVersion = new ApiVersion(1, 0); options.DefaultApiVersion = new ApiVersion(1, 0);
@@ -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,8 +40,8 @@ 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;
@@ -40,7 +40,7 @@ public class PathController : ApiController
_mediator = mediator; _mediator = mediator;
} }
#endregion #endregion
#region ===================================================================== METHODS =================================================================================== #region ===================================================================== METHODS ===================================================================================
/// <summary> /// <summary>
/// Gets the root of <paramref name="path"/>. /// Gets the root of <paramref name="path"/>.
@@ -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" />
@@ -53,6 +52,10 @@
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" /> <ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
<ProjectReference Include="..\Lumina.Infrastructure\Lumina.Infrastructure.csproj" /> <ProjectReference Include="..\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
<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>
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more