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)
return await next(request, cancellationToken).ConfigureAwait(false);
// 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 (validationResult.IsValid)
return await next(request, cancellationToken).ConfigureAwait(false);
// 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
// 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;
@@ -25,7 +25,7 @@ public class OptionalJsonConverter<TValue> : JsonConverter<Optional<TValue>>
{
if (reader.TokenType == JsonTokenType.Null)
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!);
}
@@ -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>
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
return false;
return typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>);
return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>);
}
/// <summary>
@@ -1,10 +1,10 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Behaviors;
using Mapster;
using MapsterMapper;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using FluentValidation;
using MapsterMapper;
using Mapster;
#endregion
namespace Lumina.Application.Common.DependencyInjection;
@@ -23,10 +23,7 @@ public static class ApplicationLayerServices
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
{
// register Mediator
services.AddMediator(options =>
{
options.ServiceLifetime = ServiceLifetime.Scoped;
});
services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped);
// register the validation behavior
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
@@ -35,7 +32,7 @@ public static class ApplicationLayerServices
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
// register mapster configs in this assembly
var mapsterConfig = TypeAdapterConfig.GlobalSettings;
TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(ApplicationLayerServices).Assembly);
services.AddSingleton(mapsterConfig);
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<string>.FromNullable(src.Edition),
Optional<int>.FromNullable(src.VolumeNumber),
Optional<BookSeries>.None(),
Optional<BookSeries>.None(),
Optional<string>.FromNullable(src.ASIN),
Optional<string>.FromNullable(src.GoodreadsId),
Optional<string>.FromNullable(src.LCCN),
@@ -121,7 +121,7 @@ public class BookMappingConfig : IRegister
src.Created,
Optional<DateTime>.FromNullable(src.Updated),
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(
r.Value ?? 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.Services;
using Mapster;
using MapsterMapper;
using Mediator;
using System.Collections.Generic;
using System.Threading;
@@ -44,7 +43,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, E
/// </returns>
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));
}
#endregion
@@ -56,27 +56,25 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
{
List<FileSystemTreeNodeResponse> result = [];
// retrieve the list of drives
var getDrivesResult = GetDrives();
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> getDrivesResult = GetDrives();
if (getDrivesResult.IsError)
return getDrivesResult.Errors;
result.AddRange(getDrivesResult.Value);
var pathPartsResults = _pathService.ParsePath(request.Path);
ErrorOr<IEnumerable<PathSegment>> pathPartsResults = _pathService.ParsePath(request.Path);
if (pathPartsResults.IsError)
return pathPartsResults.Errors;
var pathParts = pathPartsResults.Value.ToList();
var currentPath = pathParts[0].Name;
List<PathSegment> pathParts = pathPartsResults.Value.ToList();
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)
return buildDirectoryTreeResult.Errors;
// add subdirectories of the last directory node
var loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles);
if (loadChildrenResult.IsError)
return loadChildrenResult.Errors;
return await ValueTask.FromResult(result);
ErrorOr<Success> loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles);
return loadChildrenResult.IsError ? (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)loadChildrenResult.Errors : (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)await ValueTask.FromResult(result);
}
/// <summary>
@@ -87,10 +85,10 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
/// </returns>
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> GetDrives()
{
var driveResult = _driveService.GetDrives();
if (driveResult.IsError)
return driveResult.Errors;
return ErrorOrFactory.From(driveResult.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>());
ErrorOr<IEnumerable<FileSystemItem>> driveResult = _driveService.GetDrives();
return driveResult.IsError
? (ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>)driveResult.Errors
: ErrorOrFactory.From(driveResult.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>());
}
/// <summary>
@@ -104,21 +102,21 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> BuildDirectoryTree(List<FileSystemTreeNodeResponse> drives, List<PathSegment> pathParts, out FileSystemTreeNodeResponse currentNode)
{
// find the root drive that matches the first part of the path
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;
currentNode = drive;
var currentPath = pathParts[0].Name;
string currentPath = pathParts[0].Name;
// 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)
return combinedPathResult.Errors;
currentPath = combinedPathResult.Value;
// 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,
Name = pathParts[i].Name,
@@ -140,13 +138,13 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles)
{
// 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)
return subDirectoriesResult.Errors;
// 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,
Path = subDirectory.Id.Path,
@@ -159,13 +157,13 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
if (includeFiles)
{
// 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)
return filesResult.Errors;
// 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,
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.Services;
using Mapster;
using MapsterMapper;
using Mediator;
using System.Collections.Generic;
using System.Threading;
@@ -44,7 +43,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler<GetTreeDirectories
/// </returns>
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));
}
#endregion
@@ -43,7 +43,7 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
/// </returns>
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));
}
#endregion
@@ -43,7 +43,7 @@ public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
/// </returns>
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));
}
#endregion
@@ -43,7 +43,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, Error
/// </returns>
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));
}
#endregion
@@ -3,7 +3,6 @@ using ErrorOr;
using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Mapster;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
@@ -42,7 +41,7 @@ public class CombinePathCommandHandler : IRequestHandler<CombinePathCommand, Err
/// </returns>
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));
}
#endregion
@@ -43,7 +43,7 @@ public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr
/// </returns>
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));
}
#endregion
@@ -43,7 +43,7 @@ public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, Err
/// </returns>
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));
}
#endregion
@@ -40,7 +40,7 @@ public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr
/// <returns>The root of the specified path.</returns>
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));
}
#endregion
@@ -57,7 +57,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
{
// TODO: update Api.Book.md documentation when the functionality is fully implemented
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
}
@@ -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: 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.MaxValue ?? default,
Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : default),
Optional<int>.FromNullable(rating.VoteCount)));
// 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
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();
if (errors.Count != 0)
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();
if (errors.Count != 0)
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();
if (errors.Count != 0)
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<int>.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate),
@@ -107,11 +107,11 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
);
if (releaseInfoResult.IsError)
return releaseInfoResult.Errors;
var releaseInfo = releaseInfoResult.Value;
ReleaseInfo releaseInfo = releaseInfoResult.Value;
LanguageInfo? languageInfo = null;
if (request.Metadata.Language is not null)
{
var languageInfoResult = LanguageInfo.Create(
ErrorOr<LanguageInfo> languageInfoResult = LanguageInfo.Create(
request.Metadata.Language.LanguageCode!,
request.Metadata.Language.LanguageName!,
Optional<string>.FromNullable(request.Metadata.Language.NativeName));
@@ -122,7 +122,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
LanguageInfo? originalLanguageInfo = null;
if (request.Metadata.OriginalLanguage is not null)
{
var originalLanguageInfoResult = LanguageInfo.Create(
ErrorOr<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
request.Metadata.OriginalLanguage.LanguageCode!,
request.Metadata.OriginalLanguage.LanguageName!,
Optional<string>.FromNullable(request.Metadata.OriginalLanguage.NativeName));
@@ -130,7 +130,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
var metadataResult = WrittenContentMetadata.Create(
ErrorOr<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
request.Metadata.Title!,
Optional<string>.FromNullable(request.Metadata.OriginalTitle),
Optional<string>.FromNullable(request.Metadata.Description),
@@ -144,7 +144,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
);
if (metadataResult.IsError)
return metadataResult.Errors;
var createBookResult = Book.Create(
ErrorOr<Book> createBookResult = Book.Create(
metadataResult.Value,
Optional<BookFormat>.FromNullable(request.Format),
Optional<string>.FromNullable(request.Edition),
@@ -166,9 +166,9 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
if (createBookResult.IsError)
return createBookResult.Errors;
var bookRepository = _unitOfWork.GetRepository<IBookRepository>();
var persistenceBook = _mapper.Map<BookModel>(createBookResult.Value);
var insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
BookModel persistenceBook = _mapper.Map<BookModel>(createBookResult.Value);
ErrorOr<Created> insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsError)
return insertBookResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -43,8 +43,8 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<Book>>> Handle(GetBooksQuery request, CancellationToken cancellationToken)
{
var bookRepository = _unitOfWork.GetRepository<IBookRepository>();
var getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
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);
}
#endregion
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
@@ -1,4 +1,4 @@
namespace Lumina.Contracts.Enums.FileSystem.VideoLibrary;
namespace Lumina.Contracts.Enums.VideoLibrary;
/// <summary>
/// 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>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
@@ -15,5 +15,4 @@
<ItemGroup>
<Folder Include="Responses\WrittenContentLibrary\BookLibrary\" />
</ItemGroup>
</Project>
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Models.FileManagement;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Lumina.Contracts.Models.FileManagement;
#endregion
namespace Lumina.Contracts.Responses.FileManagement;
@@ -126,7 +126,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookModel>
ratingBuilder.Property(rating => rating.Source)
.HasConversion<string>()
.HasMaxLength(50)
.HasMaxLength(50)
.IsRequired();
});
@@ -139,12 +139,12 @@ public class BookConfiguration : IEntityTypeConfiguration<BookModel>
isbnBuilder.Property(isbn => isbn.Value)
.HasColumnName("ISBN")
.HasMaxLength(13)
.HasMaxLength(13)
.IsRequired();
isbnBuilder.Property(isbn => isbn.Format)
.HasConversion<string>()
.HasMaxLength(6)
.HasMaxLength(6)
.IsRequired();
});
}
@@ -27,13 +27,10 @@ public static class DataAccessLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
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))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
services.AddDbContext<LuminaDbContext>(options =>
{
options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}");
});
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}"));
services.AddScoped<IUnitOfWork, UnitOfWork>();
Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes();
@@ -1,216 +1,206 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
namespace Lumina.DataAccess.Common.Migrations;
/// <inheritdoc />
public partial class InitialMigration : Migration
{
/// <inheritdoc />
public partial class InitialMigration : Migration
protected override void Up(MigrationBuilder migrationBuilder)
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Books",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
OriginalTitle = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true),
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
OriginalReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
OriginalReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
ReReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReleaseCountry = table.Column<string>(type: "TEXT", nullable: true),
ReleaseVersion = table.Column<string>(type: "TEXT", nullable: true),
LanguageCode = table.Column<string>(type: "TEXT", nullable: true),
LanguageName = table.Column<string>(type: "TEXT", nullable: true),
LanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageCode = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
Publisher = table.Column<string>(type: "TEXT", maxLength: 100, nullable: true),
PageCount = table.Column<int>(type: "INTEGER", nullable: true),
Format = table.Column<string>(type: "TEXT", nullable: false),
Edition = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
VolumeNumber = table.Column<int>(type: "INTEGER", nullable: true),
ASIN = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true),
GoodreadsId = table.Column<string>(type: "TEXT", nullable: true),
LCCN = table.Column<string>(type: "TEXT", nullable: true),
OCLCNumber = table.Column<string>(type: "TEXT", nullable: true),
OpenLibraryId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
LibraryThingId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
GoogleBooksId = table.Column<string>(type: "TEXT", maxLength: 12, nullable: true),
BarnesAndNobleId = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true),
AppleBooksId = table.Column<string>(type: "TEXT", nullable: true),
Created = table.Column<DateTime>(type: "TEXT", nullable: false),
Updated = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Books", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Books",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
OriginalTitle = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true),
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
OriginalReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
OriginalReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReReleaseDate = table.Column<DateOnly>(type: "TEXT", nullable: true),
ReReleaseYear = table.Column<int>(type: "INTEGER", nullable: true),
ReleaseCountry = table.Column<string>(type: "TEXT", nullable: true),
ReleaseVersion = table.Column<string>(type: "TEXT", nullable: true),
LanguageCode = table.Column<string>(type: "TEXT", nullable: true),
LanguageName = table.Column<string>(type: "TEXT", nullable: true),
LanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageCode = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageName = table.Column<string>(type: "TEXT", nullable: true),
OriginalLanguageNativeName = table.Column<string>(type: "TEXT", nullable: true),
Publisher = table.Column<string>(type: "TEXT", maxLength: 100, nullable: true),
PageCount = table.Column<int>(type: "INTEGER", nullable: true),
Format = table.Column<string>(type: "TEXT", nullable: false),
Edition = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
VolumeNumber = table.Column<int>(type: "INTEGER", nullable: true),
ASIN = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true),
GoodreadsId = table.Column<string>(type: "TEXT", nullable: true),
LCCN = table.Column<string>(type: "TEXT", nullable: true),
OCLCNumber = table.Column<string>(type: "TEXT", nullable: true),
OpenLibraryId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
LibraryThingId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),
GoogleBooksId = table.Column<string>(type: "TEXT", maxLength: 12, nullable: true),
BarnesAndNobleId = table.Column<string>(type: "TEXT", maxLength: 10, nullable: true),
AppleBooksId = table.Column<string>(type: "TEXT", nullable: true),
Created = table.Column<DateTime>(type: "TEXT", nullable: false),
Updated = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table => table.PrimaryKey("PK_Books", x => x.Id));
migrationBuilder.CreateTable(
name: "Genres",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Genres", x => x.Name);
});
migrationBuilder.CreateTable(
name: "Genres",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false)
},
constraints: table => table.PrimaryKey("PK_Genres", x => x.Name));
migrationBuilder.CreateTable(
name: "Tags",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Tags", x => x.Name);
});
migrationBuilder.CreateTable(
name: "Tags",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false)
},
constraints: table => table.PrimaryKey("PK_Tags", x => x.Name));
migrationBuilder.CreateTable(
name: "BookISBNs",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
ISBN = table.Column<string>(type: "TEXT", maxLength: 13, nullable: false),
Format = table.Column<string>(type: "TEXT", maxLength: 6, nullable: false),
BookId = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BookISBNs", x => x.Id);
table.ForeignKey(
name: "FK_BookISBNs_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookISBNs",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
ISBN = table.Column<string>(type: "TEXT", maxLength: 13, nullable: false),
Format = table.Column<string>(type: "TEXT", maxLength: 6, nullable: false),
BookId = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BookISBNs", x => x.Id);
table.ForeignKey(
name: "FK_BookISBNs_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookRatings",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Source = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
Value = 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)
},
constraints: table =>
{
table.PrimaryKey("PK_BookRatings", x => x.Id);
table.ForeignKey(
name: "FK_BookRatings_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookRatings",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Source = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
Value = 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)
},
constraints: table =>
{
table.PrimaryKey("PK_BookRatings", x => x.Id);
table.ForeignKey(
name: "FK_BookRatings_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookGenres",
columns: table => new
{
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
GenreId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BookGenres", x => new { x.BookId, x.GenreId });
table.ForeignKey(
name: "FK_BookGenres_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BookGenres_Genres_GenreId",
column: x => x.GenreId,
principalTable: "Genres",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookGenres",
columns: table => new
{
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
GenreId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BookGenres", x => new { x.BookId, x.GenreId });
table.ForeignKey(
name: "FK_BookGenres_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BookGenres_Genres_GenreId",
column: x => x.GenreId,
principalTable: "Genres",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookTags",
columns: table => new
{
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
TagId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BookTags", x => new { x.BookId, x.TagId });
table.ForeignKey(
name: "FK_BookTags_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BookTags_Tags_TagId",
column: x => x.TagId,
principalTable: "Tags",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookTags",
columns: table => new
{
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
TagId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BookTags", x => new { x.BookId, x.TagId });
table.ForeignKey(
name: "FK_BookTags_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BookTags_Tags_TagId",
column: x => x.TagId,
principalTable: "Tags",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_BookGenres_GenreId",
table: "BookGenres",
column: "GenreId");
migrationBuilder.CreateIndex(
name: "IX_BookGenres_GenreId",
table: "BookGenres",
column: "GenreId");
migrationBuilder.CreateIndex(
name: "IX_BookISBNs_BookId",
table: "BookISBNs",
column: "BookId");
migrationBuilder.CreateIndex(
name: "IX_BookISBNs_BookId",
table: "BookISBNs",
column: "BookId");
migrationBuilder.CreateIndex(
name: "IX_BookRatings_BookId",
table: "BookRatings",
column: "BookId");
migrationBuilder.CreateIndex(
name: "IX_BookRatings_BookId",
table: "BookRatings",
column: "BookId");
migrationBuilder.CreateIndex(
name: "IX_BookTags_TagId",
table: "BookTags",
column: "TagId");
}
migrationBuilder.CreateIndex(
name: "IX_BookTags_TagId",
table: "BookTags",
column: "TagId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "BookGenres");
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "BookGenres");
migrationBuilder.DropTable(
name: "BookISBNs");
migrationBuilder.DropTable(
name: "BookISBNs");
migrationBuilder.DropTable(
name: "BookRatings");
migrationBuilder.DropTable(
name: "BookRatings");
migrationBuilder.DropTable(
name: "BookTags");
migrationBuilder.DropTable(
name: "BookTags");
migrationBuilder.DropTable(
name: "Genres");
migrationBuilder.DropTable(
name: "Genres");
migrationBuilder.DropTable(
name: "Books");
migrationBuilder.DropTable(
name: "Books");
migrationBuilder.DropTable(
name: "Tags");
}
migrationBuilder.DropTable(
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>
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)
return Errors.WrittenContent.BookAlreadyExists;
// 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))
.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))
.ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -20,7 +20,7 @@ public class RepositoryDictionary
/// <summary>
/// Gets the number of added repositories.
/// </summary>
public int Count { get { return _container.Count; } }
public int Count => _container.Count;
#endregion
#region ===================================================================== METHODS ===================================================================================
@@ -53,10 +53,10 @@ public class LuminaDbContext : DbContext
public override int SaveChanges()
{
// 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 &&
(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 (entityEntry.State == EntityState.Added)
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
@@ -30,5 +30,4 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
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.Path;
@@ -13,7 +13,7 @@ public static partial class Errors
{
#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 ContributorDisplayNameCannotBeEmpty => Error.Validation(nameof(ContributorDisplayNameCannotBeEmpty));
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.
/// </summary>
protected AggregateRoot() // only needed during reflection
{
{
}
#pragma warning restore CS8618
#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.
/// </summary>
protected Entity() // only needed during reflection
{
{
}
#pragma warning restore CS8618
#endregion
@@ -37,7 +37,7 @@ public abstract class ValueObject : IEquatable<ValueObject>
{
if (obj is null || obj.GetType() != GetType())
return false;
var valueObject = (ValueObject)obj;
ValueObject valueObject = (ValueObject)obj;
return GetEqualityComponents().SequenceEqual(valueObject.GetEqualityComponents());
}
@@ -16,17 +16,11 @@ public readonly struct Optional<TValue>
/// Gets a value indicating whether this structure has a value.
/// </summary>
public bool HasValue { get; }
/// <summary>
/// Gets the value represented by this structure.
/// </summary>
public TValue Value
{
get
{
return HasValue ? _value! : default!;
}
}
public TValue Value => HasValue ? _value! : default!;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -18,12 +18,12 @@ public abstract class BaseMetadata : ValueObject
private readonly List<Tag> _tags;
private readonly List<Genre> _genres;
#endregion
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets the title of the media item.
/// </summary>
public string Title { get; private set;}
public string Title { get; private set; }
/// <summary>
/// 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.
/// </summary>
public Optional<LanguageInfo> Language { get; private set; }
/// <summary>
/// Gets the optional original language of the media item.
/// </summary>
@@ -53,18 +53,12 @@ public abstract class BaseMetadata : ValueObject
/// <summary>
/// Gets the list of tags associated with the media item.
/// </summary>
public IReadOnlyCollection<Tag> Tags
{
get { return _tags.AsReadOnly(); }
}
public IReadOnlyCollection<Tag> Tags => _tags.AsReadOnly();
/// <summary>
/// Gets the list of genres associated with the media item.
/// </summary>
public IReadOnlyCollection<Genre> Genres
{
get { return _genres.AsReadOnly(); }
}
public IReadOnlyCollection<Genre> Genres => _genres.AsReadOnly();
#endregion
#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>
/// <exception cref="ArgumentNullException">Thrown when the <see cref="title"/> value is <see langword="null"/></exception>
protected BaseMetadata(
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage)
{
Title = title ?? throw new ArgumentNullException(nameof(title));
@@ -109,9 +103,9 @@ public abstract class BaseMetadata : ValueObject
yield return OriginalTitle;
yield return Description;
yield return ReleaseInfo;
foreach (var genre in _genres)
foreach (Genre genre in _genres)
yield return genre;
foreach (var tag in _tags)
foreach (Tag tag in _tags)
yield return tag;
yield return Language;
yield return OriginalLanguage;
@@ -41,9 +41,7 @@ public class Genre : ValueObject
/// </returns>
public static ErrorOr<Genre> Create(string name)
{
if (string.IsNullOrWhiteSpace(name))
return Errors.Errors.Metadata.GenreNameCannotBeEmpty;
return new Genre(name);
return string.IsNullOrWhiteSpace(name) ? (ErrorOr<Genre>)Errors.Errors.Metadata.GenreNameCannotBeEmpty : (ErrorOr<Genre>)new Genre(name);
}
/// <inheritdoc/>
@@ -58,13 +58,11 @@ public class LanguageInfo : ValueObject
/// </returns>
public static ErrorOr<LanguageInfo> Create(string languageCode, string languageName, Optional<string> nativeName)
{
if (string.IsNullOrWhiteSpace(languageCode))
return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty;
if (string.IsNullOrWhiteSpace(languageName))
return Errors.Errors.Metadata.LanguageNameCannotBeEmpty;
if (languageCode.Length != 2)
return Errors.Errors.Metadata.InvalidIsoCode;
return new LanguageInfo(languageCode, languageName, nativeName);
return string.IsNullOrWhiteSpace(languageCode)
? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.LanguageCodeCannotBeEmpty
: string.IsNullOrWhiteSpace(languageName)
? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.LanguageNameCannotBeEmpty
: languageCode.Length != 2 ? (ErrorOr<LanguageInfo>)Errors.Errors.Metadata.InvalidIsoCode : (ErrorOr<LanguageInfo>)new LanguageInfo(languageCode, languageName, nativeName);
}
/// <inheritdoc/>
@@ -51,7 +51,7 @@ public abstract class Rating : ValueObject
/// <returns>The rating value as a percentage of the maximum value.</returns>
public decimal AsPercentage()
{
return (Value / MaxValue) * 100;
return Value / MaxValue * 100;
}
#endregion
}
@@ -59,11 +59,11 @@ public class ReleaseInfo : ValueObject
/// <param name="releaseCountry">The optional country or region of release.</param>
/// <param name="releaseVersion">The optional release version or edition.</param>
private ReleaseInfo(
Optional<DateOnly> originalReleaseDate,
Optional<DateOnly> originalReleaseDate,
Optional<int> originalReleaseYear,
Optional<DateOnly> reReleaseDate,
Optional<int> reReleaseYear,
Optional<string> releaseCountry,
Optional<DateOnly> reReleaseDate,
Optional<int> reReleaseYear,
Optional<string> releaseCountry,
Optional<string> releaseVersion)
{
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.
/// </returns>
public static ErrorOr<ReleaseInfo> Create(
Optional<DateOnly> originalReleaseDate,
Optional<DateOnly> originalReleaseDate,
Optional<int> originalReleaseYear,
Optional<DateOnly> reReleaseDate,
Optional<int> reReleaseYear,
Optional<string> releaseCountry,
Optional<DateOnly> reReleaseDate,
Optional<int> reReleaseYear,
Optional<string> releaseCountry,
Optional<string> releaseVersion)
{
if (originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value)
return Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch;
if (reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value)
return Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch;
if (originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value)
return Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate;
if (originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value)
return Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear;
return new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion);
return originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch
: reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch
: originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate
: originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value
? (ErrorOr<ReleaseInfo>)Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear
: (ErrorOr<ReleaseInfo>)new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion);
}
/// <inheritdoc/>
@@ -41,9 +41,7 @@ public class Tag : ValueObject
/// </returns>
public static ErrorOr<Tag> Create(string name)
{
if (string.IsNullOrWhiteSpace(name))
return Errors.Errors.Metadata.TagNameCannotBeEmpty;
return new Tag(name);
return string.IsNullOrWhiteSpace(name) ? (ErrorOr<Tag>)Errors.Errors.Metadata.TagNameCannotBeEmpty : (ErrorOr<Tag>)new Tag(name);
}
/// <inheritdoc/>
@@ -64,19 +64,19 @@ public class AudioMetadata : BaseMetadata
/// <param name="genres">The genres of the audio.</param>
/// <param name="tags">The tags associated with the audio.</param>
public AudioMetadata(
string title,
Optional<string> originalTitle,
int durationInSeconds,
int sampleRate,
int channels,
ReleaseInfo releaseInfo,
string title,
Optional<string> originalTitle,
int durationInSeconds,
int sampleRate,
int channels,
ReleaseInfo releaseInfo,
Optional<string> description,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
Optional<int> bitrate)
: 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.
/// </returns>
public static ErrorOr<AudioMetadata> Create(
string title,
Optional<string> originalTitle,
int durationInSeconds,
int sampleRate,
int channels,
ReleaseInfo release,
Optional<string>
string title,
Optional<string> originalTitle,
int durationInSeconds,
int sampleRate,
int channels,
ReleaseInfo release,
Optional<string>
description,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
Optional<int> bitrate)
{
return new AudioMetadata(
title,
originalTitle,
durationInSeconds,
sampleRate,
channels,
release,
description,
genres,
title,
originalTitle,
durationInSeconds,
sampleRate,
channels,
release,
description,
genres,
tags,
language,
originalLanguage,
bitDepth,
audioCodec,
language,
originalLanguage,
bitDepth,
audioCodec,
bitrate);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
foreach (var component in base.GetEqualityComponents())
foreach (object component in base.GetEqualityComponents())
yield return component;
yield return DurationInSeconds;
yield return SampleRate;
@@ -19,7 +19,7 @@ public sealed class Directory : FileSystemItem
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly List<FileSystemItem> _items = [];
#endregion
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// 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>
/// Gets the collection of file system items that are children to the current directory entity.
/// </summary>
public IReadOnlyCollection<FileSystemItem> Items
{
get { return _items.AsReadOnly(); }
}
public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -77,15 +74,13 @@ public sealed class Directory : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError)
return createPathResult.Errors;
Directory newDirectory = new Directory(
Directory newDirectory = new(
createPathResult.Value,
name,
dateCreated,
dateModified);
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newDirectory;
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : (ErrorOr<Directory>)newDirectory;
}
/// <summary>
@@ -106,15 +101,13 @@ public sealed class Directory : FileSystemItem
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
Directory newDirectory = new Directory(
Directory newDirectory = new(
id,
name,
dateCreated,
dateModified);
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newDirectory;
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : (ErrorOr<Directory>)newDirectory;
}
/// <summary>
@@ -74,16 +74,14 @@ public sealed class File : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError)
return createPathResult.Errors;
File newFile = new File(
File newFile = new(
createPathResult.Value,
name,
dateCreated,
dateModified,
size);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newFile;
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : (ErrorOr<File>)newFile;
}
/// <summary>
@@ -107,16 +105,14 @@ public sealed class File : FileSystemItem
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
File newFile = new File(
File newFile = new(
id,
name,
dateCreated,
dateModified,
size);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newFile;
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : (ErrorOr<File>)newFile;
}
/// <summary>
@@ -23,10 +23,7 @@ public sealed class UnixRootItem : FileSystemItem
/// <summary>
/// Gets the collection of file system items that are children to the current file system root entity.
/// </summary>
public IReadOnlyCollection<FileSystemItem> Items
{
get { return _items.AsReadOnly(); }
}
public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -54,13 +51,11 @@ public sealed class UnixRootItem : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(PATH);
if (createPathResult.IsError)
return createPathResult.Errors;
UnixRootItem newRoot = new UnixRootItem(
UnixRootItem newRoot = new(
createPathResult.Value,
PATH);
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newRoot;
return setStatusResult.IsError ? (ErrorOr<UnixRootItem>)setStatusResult.Errors : (ErrorOr<UnixRootItem>)newRoot;
}
#endregion
}
@@ -22,10 +22,7 @@ public sealed class WindowsRootItem : FileSystemItem
/// <summary>
/// Gets the collection of file system items that are children to the current file system root entity.
/// </summary>
public IReadOnlyCollection<FileSystemItem> Items
{
get { return _items.AsReadOnly(); }
}
public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
#endregion
#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="name">The name of the root item.</param>
private WindowsRootItem(FileSystemPathId id, string name) : base(id, name, FileSystemItemType.Root)
{
{
}
#endregion
@@ -58,13 +55,11 @@ public sealed class WindowsRootItem : FileSystemItem
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError)
return createPathResult.Errors;
WindowsRootItem newRoot = new WindowsRootItem(
WindowsRootItem newRoot = new(
createPathResult.Value,
name);
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newRoot;
return setStatusResult.IsError ? (ErrorOr<WindowsRootItem>)setStatusResult.Errors : (ErrorOr<WindowsRootItem>)newRoot;
}
/// <summary>
@@ -82,13 +77,11 @@ public sealed class WindowsRootItem : FileSystemItem
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
WindowsRootItem newFile = new WindowsRootItem(
WindowsRootItem newFile = new(
id,
name);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newFile;
return setStatusResult.IsError ? (ErrorOr<WindowsRootItem>)setStatusResult.Errors : (ErrorOr<WindowsRootItem>)newFile;
}
#endregion
}
@@ -44,12 +44,12 @@ internal class DirectoryProviderService : IDirectoryProviderService
public ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false))
return Errors.Permission.UnauthorizedAccess;
return ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path)
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false)
? (ErrorOr<IEnumerable<FileSystemPathId>>)Errors.Permission.UnauthorizedAccess
: ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path)
.OrderBy(path => path)
.Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar)
.Select(path => FileSystemPathId.Create(path))
.Select(FileSystemPathId.Create)
.Where(errorOrPathId => !errorOrPathId.IsError)
.Select(errorOrPathId => errorOrPathId.Value)
.AsEnumerable());
@@ -85,9 +85,9 @@ internal class DirectoryProviderService : IDirectoryProviderService
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path));
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path));
}
/// <summary>
@@ -98,9 +98,9 @@ internal class DirectoryProviderService : IDirectoryProviderService
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path));
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path));
}
/// <summary>
@@ -270,7 +270,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name);
if (!string.IsNullOrEmpty(newDirectory))
{
var newDirectoryPathResult = FileSystemPathId.Create(newDirectory);
ErrorOr<FileSystemPathId> newDirectoryPathResult = FileSystemPathId.Create(newDirectory);
if (newDirectoryPathResult.IsError)
return newDirectoryPathResult.Errors;
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false))
@@ -45,9 +45,7 @@ public class DirectoryService : IDirectoryService
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return GetSubdirectories(fileSystemPathIdResult.Value);
return fileSystemPathIdResult.IsError ? (ErrorOr<IEnumerable<Directory>>)fileSystemPathIdResult.Errors : GetSubdirectories(fileSystemPathIdResult.Value);
}
/// <summary>
@@ -84,9 +82,9 @@ public class DirectoryService : IDirectoryService
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
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());
if(errorDirResult.IsError)
if (errorDirResult.IsError)
return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
@@ -113,9 +111,7 @@ public class DirectoryService : IDirectoryService
public ErrorOr<Directory> CreateDirectory(string path, string name)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return CreateDirectory(fileSystemPathIdResult.Value, name);
return fileSystemPathIdResult.IsError ? (ErrorOr<Directory>)fileSystemPathIdResult.Errors : CreateDirectory(fileSystemPathIdResult.Value, name);
}
/// <summary>
@@ -148,14 +144,12 @@ public class DirectoryService : IDirectoryService
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
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());
if (errorDirResult.IsError)
return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorDirResult;
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : errorDirResult;
}
else
return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
@@ -180,9 +174,9 @@ public class DirectoryService : IDirectoryService
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
return fileSystemDestinationPathIdResult.IsError
? (ErrorOr<Directory>)fileSystemDestinationPathIdResult.Errors
: CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
@@ -226,9 +220,9 @@ public class DirectoryService : IDirectoryService
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
return fileSystemDestinationPathIdResult.IsError
? (ErrorOr<Directory>)fileSystemDestinationPathIdResult.Errors
: MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
@@ -263,9 +257,7 @@ public class DirectoryService : IDirectoryService
public ErrorOr<Directory> RenameDirectory(string path, string name)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return RenameDirectory(fileSystemPathIdResult.Value, name);
return fileSystemPathIdResult.IsError ? (ErrorOr<Directory>)fileSystemPathIdResult.Errors : RenameDirectory(fileSystemPathIdResult.Value, name);
}
/// <summary>
@@ -298,14 +290,12 @@ public class DirectoryService : IDirectoryService
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
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());
if (errorDirResult.IsError)
return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorDirResult;
return setStatusResult.IsError ? (ErrorOr<Directory>)setStatusResult.Errors : errorDirResult;
}
else
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)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return DeleteDirectory(fileSystemPathIdResult.Value);
return fileSystemPathIdResult.IsError ? (ErrorOr<Deleted>)fileSystemPathIdResult.Errors : DeleteDirectory(fileSystemPathIdResult.Value);
}
/// <summary>
@@ -41,10 +41,8 @@ public class DriveService : IDriveService
{
if (_platformContext.Platform == PlatformType.Unix)
{
var unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible);
if (unixRootResult.IsError)
return unixRootResult.Errors;
return new List<FileSystemItem>() { unixRootResult.Value };
ErrorOr<UnixRootItem> unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible);
return unixRootResult.IsError ? (ErrorOr<IEnumerable<FileSystemItem>>)unixRootResult.Errors : (ErrorOr<IEnumerable<FileSystemItem>>)new List<FileSystemItem>() { unixRootResult.Value };
}
else
return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives()
@@ -53,7 +51,7 @@ public class DriveService : IDriveService
.Select(driveInfo =>
{
ErrorOr<FileSystemItem> root;
var windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name);
ErrorOr<WindowsRootItem> windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name);
if (windowsRootResult.IsError)
return windowsRootResult.Errors;
else
@@ -44,11 +44,11 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory))
return Errors.Permission.UnauthorizedAccess;
return ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path)
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory)
? (ErrorOr<IEnumerable<FileSystemPathId>>)Errors.Permission.UnauthorizedAccess
: ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path)
.OrderBy(p => p)
.Select(p => FileSystemPathId.Create(p))
.Select(FileSystemPathId.Create)
.Where(errorOrPathId => !errorOrPathId.IsError)
.Select(errorOrPathId => errorOrPathId.Value)
.AsEnumerable());
@@ -82,9 +82,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<byte[]> GetFileAsync(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess;
return System.IO.File.ReadAllBytes(path.Path);
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)
? (ErrorOr<byte[]>)Errors.Permission.UnauthorizedAccess
: (ErrorOr<byte[]>)System.IO.File.ReadAllBytes(path.Path);
}
/// <summary>
@@ -95,9 +95,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path));
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path));
}
/// <summary>
@@ -108,9 +108,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path));
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
? (ErrorOr<Optional<DateTime>>)Errors.Permission.UnauthorizedAccess
: (ErrorOr<Optional<DateTime>>)Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path));
}
/// <summary>
@@ -121,9 +121,9 @@ internal class FileProviderService : IFileProviderService
public ErrorOr<long?> GetSize(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
return Errors.Permission.UnauthorizedAccess;
return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0;
return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)
? (ErrorOr<long?>)Errors.Permission.UnauthorizedAccess
: (ErrorOr<long?>)(_fileSystem.FileInfo.New(path.Path)?.Length ?? 0);
}
/// <summary>
@@ -233,7 +233,7 @@ internal class FileProviderService : IFileProviderService
string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name);
if (!string.IsNullOrEmpty(newFile))
{
var newFilePathResult = FileSystemPathId.Create(newFile);
ErrorOr<FileSystemPathId> newFilePathResult = FileSystemPathId.Create(newFile);
if (newFilePathResult.IsError)
return newFilePathResult.Errors;
// 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>
public ErrorOr<IEnumerable<File>> GetFiles(string path)
{
var fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return GetFiles(fileSystemPathIdResult.Value);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
return fileSystemPathIdResult.IsError ? (ErrorOr<IEnumerable<File>>)fileSystemPathIdResult.Errors : GetFiles(fileSystemPathIdResult.Value);
}
/// <summary>
@@ -71,7 +69,7 @@ public class FileService : IFileService
ErrorOr<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path);
if (filePathsResult.IsError)
return filePathsResult.Errors;
List<File> result = new();
List<File> result = [];
IEnumerable<FileSystemPathId> filePaths = filePathsResult.Value;
foreach (FileSystemPathId filePath in filePaths)
{
@@ -85,7 +83,7 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
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);
if (errorFileResult.IsError)
return errorFileResult.Errors;
@@ -96,7 +94,7 @@ public class FileService : IFileService
}
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)
return fileResult.Errors;
result.Add(fileResult.Value);
@@ -117,13 +115,13 @@ public class FileService : IFileService
// make sure the paths are in the expected format
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
return fileSystemDestinationPathIdResult.IsError
? (ErrorOr<File>)fileSystemDestinationPathIdResult.Errors
: CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
@@ -135,7 +133,7 @@ public class FileService : IFileService
/// <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)
{
var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsError)
return fileExists.Errors;
else if (fileExists.Value == false)
@@ -155,14 +153,12 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
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);
if (errorFileResult.IsError)
return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorFileResult;
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
}
else
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
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
return fileSystemDestinationPathIdResult.IsError
? (ErrorOr<File>)fileSystemDestinationPathIdResult.Errors
: MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
@@ -199,7 +195,7 @@ public class FileService : IFileService
/// <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)
{
var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsError)
return fileExists.Errors;
else if (fileExists.Value == false)
@@ -219,14 +215,12 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
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);
if (errorFileResult.IsError)
return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorFileResult;
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
}
else
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>
public ErrorOr<File> RenameFile(string path, string name)
{
var fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return RenameFile(fileSystemPathIdResult.Value, name);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
return fileSystemPathIdResult.IsError ? (ErrorOr<File>)fileSystemPathIdResult.Errors : RenameFile(fileSystemPathIdResult.Value, name);
}
/// <summary>
@@ -256,10 +248,10 @@ public class FileService : IFileService
public ErrorOr<File> RenameFile(FileSystemPathId path, string name)
{
// 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)
return combinedPath.Errors;
var fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value);
ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value);
if (fileExists.IsError)
return fileExists.Errors;
else if (fileExists.Value == true)
@@ -279,14 +271,12 @@ public class FileService : IFileService
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
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);
if (errorFileResult.IsError)
return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorFileResult;
return setStatusResult.IsError ? (ErrorOr<File>)setStatusResult.Errors : errorFileResult;
}
else
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>
public ErrorOr<Deleted> DeleteFile(string path)
{
var fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return DeleteFile(fileSystemPathIdResult.Value);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
return fileSystemPathIdResult.IsError ? (ErrorOr<Deleted>)fileSystemPathIdResult.Errors : DeleteFile(fileSystemPathIdResult.Value);
}
/// <summary>
@@ -29,7 +29,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
public FileSystemPermissionsService(IPlatformContextManager platformContextManager)
{
_platformContextManager = platformContextManager;
_platformContextManager = platformContextManager;
}
#endregion
@@ -85,7 +85,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
modes = AccessModes.F_OK; // check existence, not an exact match but the closest
break;
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
else
{
@@ -147,7 +147,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
_ = fileSystemInfo.CreationTime; // trigger potential access denial
break;
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();
break;
}
@@ -203,7 +203,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService
}
}
catch
catch
{
return false;
}
@@ -60,7 +60,7 @@ public class FileTypeService : IFileTypeService
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess;
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
if (stream.Length < BUFFER_SIZE)
return ImageType.None;
@@ -73,12 +73,9 @@ public class FileTypeService : IFileTypeService
return type;
// no known image header types were found, check other methods
string content = Encoding.UTF8.GetString(buffer.ToArray());
if (IsSvg(content, path.Path))
return ImageType.SVG;
else if (IsTga(buffer.ToArray()))
return ImageType.TGA;
else
return ImageType.None;
return IsSvg(content, path.Path)
? (ErrorOr<ImageType>)ImageType.SVG
: IsTga(buffer.ToArray()) ? (ErrorOr<ImageType>)ImageType.TGA : (ErrorOr<ImageType>)ImageType.None;
}
/// <summary>
@@ -96,7 +93,7 @@ public class FileTypeService : IFileTypeService
if (initialContent.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase))
{
// 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];
stream.Read(svgBuffer, 0, 1000);
string extendedContent = Encoding.UTF8.GetString(svgBuffer);
@@ -116,7 +113,7 @@ public class FileTypeService : IFileTypeService
if (buffer.Length < 18)
return false;
byte imageType = buffer[2];
return imageType == 1 || imageType == 2 || imageType == 10;
return imageType is 1 or 2 or 10;
}
/// <summary>
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
#endregion
@@ -9,7 +9,7 @@ namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.S
/// <summary>
/// Interface for the service for handling thumbnails.
/// </summary>
public interface IThumbnailService
public interface IThumbnailService
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
@@ -20,10 +20,7 @@ public class PathService : IPathService
/// <summary>
/// Gets the character used to separate path segments.
/// </summary>
public char PathSeparator
{
get { return _platformContext.PathStrategy.PathSeparator; }
}
public char PathSeparator => _platformContext.PathStrategy.PathSeparator;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -46,9 +43,7 @@ public class PathService : IPathService
public bool IsValidPath(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return false;
return _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
return !newPathResult.IsError && _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
}
/// <summary>
@@ -59,9 +54,7 @@ public class PathService : IPathService
public bool Exists(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return false;
return _platformContext.PathStrategy.Exists(newPathResult.Value);
return !newPathResult.IsError && _platformContext.PathStrategy.Exists(newPathResult.Value);
}
/// <summary>
@@ -76,9 +69,7 @@ public class PathService : IPathService
if (newPathResult.IsError)
return newPathResult.Errors;
ErrorOr<FileSystemPathId> combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name);
if (combinedPathResult.IsError)
return combinedPathResult.Errors;
return combinedPathResult.Value.Path;
return combinedPathResult.IsError ? (ErrorOr<string>)combinedPathResult.Errors : (ErrorOr<string>)combinedPathResult.Value.Path;
}
/// <summary>
@@ -89,9 +80,7 @@ public class PathService : IPathService
public ErrorOr<IEnumerable<PathSegment>> ParsePath(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
return _platformContext.PathStrategy.ParsePath(newPathResult.Value);
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : _platformContext.PathStrategy.ParsePath(newPathResult.Value);
}
/// <summary>
@@ -102,9 +91,7 @@ public class PathService : IPathService
public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
}
/// <summary>
@@ -124,9 +111,7 @@ public class PathService : IPathService
public ErrorOr<PathSegment> GetPathRoot(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
return newPathResult.IsError ? (ErrorOr<PathSegment>)newPathResult.Errors : _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
}
#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>
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality)
{
var fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
return fileSystemPathIdResult.IsError
? (ErrorOr<Thumbnail>)fileSystemPathIdResult.Errors
: await GetThumbnailAsync(fileSystemPathIdResult.Value, quality);
}
/// <summary>
@@ -59,21 +59,21 @@ public class ThumbnailService : IThumbnailService
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(FileSystemPathId path, int quality)
{
// 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)
return imageTypeResult.Errors;
if (imageTypeResult.Value != ImageType.None)
{
// then, get its bytes
var resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path);
ErrorOr<byte[]> resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path);
if (resultFileContents.IsError)
return resultFileContents.Errors;
byte[] fileContents = resultFileContents.Value;
// finally, resize or adjust quality based on image type
byte[]? adjustedImage = null;
if (imageTypeResult.Value == ImageType.JPEG || imageTypeResult.Value == ImageType.JPEG_CANON || imageTypeResult.Value == ImageType.JPEG2000
|| imageTypeResult.Value == ImageType.JPEG_UNKNOWN || imageTypeResult.Value == ImageType.PNG || imageTypeResult.Value == ImageType.BMP
|| imageTypeResult.Value == ImageType.WEBP || imageTypeResult.Value == ImageType.GIF || imageTypeResult.Value == ImageType.TIFF || imageTypeResult.Value == ImageType.TGA)
if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000
or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP
or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA)
adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality);
return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents);
}
@@ -90,8 +90,8 @@ public class ThumbnailService : IThumbnailService
/// <returns>A byte array representing the processed image.</returns>
private static async Task<byte[]> AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality)
{
using var inputMemoryStream = new MemoryStream(imageBytes);
using var outputMemoryStream = new MemoryStream();
using MemoryStream inputMemoryStream = new(imageBytes);
using MemoryStream outputMemoryStream = new();
switch (imageType)
{
case ImageType.JPEG:
@@ -99,22 +99,23 @@ public class ThumbnailService : IThumbnailService
case ImageType.JPEG_CANON:
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 });
break;
}
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
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);
break;
}
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
break;
}
@@ -133,8 +134,8 @@ public class ThumbnailService : IThumbnailService
/// <returns>The bytes of the adjusted image.</returns>
private static async Task<byte[]> AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality)
{
using var inputMemoryStream = new MemoryStream(imageBytes);
using var outputMemoryStream = new MemoryStream();
using MemoryStream inputMemoryStream = new(imageBytes);
using MemoryStream outputMemoryStream = new();
Image image = await Image.LoadAsync(inputMemoryStream);
double ratio = quality / 100.0;
int newWidth = (int)(image.Width * ratio);
@@ -142,7 +143,7 @@ public class ThumbnailService : IThumbnailService
// ensure new dimensions are not zero
newWidth = Math.Max(1, newWidth);
newHeight = Math.Max(1, newHeight);
var options = new ResizeOptions
ResizeOptions options = new()
{
Size = new Size(newWidth, newHeight),
Mode = ResizeMode.Max
@@ -166,7 +167,7 @@ public class ThumbnailService : IThumbnailService
break;
default:
return imageBytes; // for unsupported formats, just return the original bytes
}
}
return outputMemoryStream.ToArray();
}
@@ -183,7 +184,7 @@ public class ThumbnailService : IThumbnailService
/// </returns>
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
}
@@ -1,5 +1,4 @@
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;
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
#endregion
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
@@ -21,10 +21,7 @@ public class UnixPathStrategy : IUnixPathStrategy
#endregion
#region ==================================================================== PROPERTIES =================================================================================
public char PathSeparator
{
get { return '/'; }
}
public char PathSeparator => '/';
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -47,13 +44,13 @@ public class UnixPathStrategy : IUnixPathStrategy
public bool IsValidPath(FileSystemPathId path)
{
// check for invalid path characters
var invalidChars = GetInvalidPathCharsForPlatform();
char[] invalidChars = GetInvalidPathCharsForPlatform();
if (path.Path.IndexOfAny(invalidChars) >= 0)
return false;
// check for relative paths
if (path.Path.StartsWith("./") || path.Path.StartsWith("../"))
return false;
var pathPattern = @"^\/([\w\-\.\~!$&'()*+,;=:@ ]+(\/[\w\-\.\~!$&'()*+,;=:@ ]+)*)?\/?$";
string pathPattern = @"^\/([\w\-\.\~!$&'()*+,;=:@ ]+(\/[\w\-\.\~!$&'()*+,;=:@ ]+)*)?\/?$";
return Regex.IsMatch(path.Path, pathPattern);
}
@@ -124,15 +121,13 @@ public class UnixPathStrategy : IUnixPathStrategy
if (tempPath.EndsWith('/'))
tempPath = tempPath.TrimEnd(PathSeparator);
// 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 (lastIndex < 0)
return Errors.FileManagement.CannotNavigateUp;
// return the path up to the last slash, or, if there's only the root slash, return that one instead
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]);
if (newPathResult.IsError)
return newPathResult.Errors;
return ParsePath(newPathResult.Value);
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : ParsePath(newPathResult.Value);
}
/// <summary>
@@ -155,9 +150,9 @@ public class UnixPathStrategy : IUnixPathStrategy
return Errors.FileManagement.InvalidPath;
// On Unix-like systems, the root is always "/"
if (path.Path.StartsWith(PathSeparator))
return new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true);
return Errors.FileManagement.InvalidPath;
return path.Path.StartsWith(PathSeparator)
? (ErrorOr<PathSegment>)new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true)
: (ErrorOr<PathSegment>)Errors.FileManagement.InvalidPath;
}
#endregion
}
@@ -1,12 +1,12 @@
#region ========================================================================= USING =====================================================================================
using System;
using ErrorOr;
using System.Collections.Generic;
using Lumina.Domain.Common.Errors;
using System.Text.RegularExpressions;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System.Linq;
using System;
using System.Collections.Generic;
using System.IO.Abstractions;
using System.Linq;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
@@ -21,10 +21,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
#endregion
#region ==================================================================== PROPERTIES =================================================================================
public char PathSeparator
{
get { return '\\'; }
}
public char PathSeparator => '\\';
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -47,12 +44,12 @@ public class WindowsPathStrategy : IWindowsPathStrategy
public bool IsValidPath(FileSystemPathId path)
{
// check for invalid path characters
var invalidChars = GetInvalidPathCharsForPlatform();
char[] invalidChars = GetInvalidPathCharsForPlatform();
if (path.Path.IndexOfAny(invalidChars) >= 0)
return false;
// regular expression to match valid absolute paths
// 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);
}
@@ -92,18 +89,18 @@ public class WindowsPathStrategy : IWindowsPathStrategy
public ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
{
// 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 Errors.FileManagement.InvalidPath;
return ErrorOrFactory.From(GetPathSegments());
return !path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator
? (ErrorOr<IEnumerable<PathSegment>>)Errors.FileManagement.InvalidPath
: ErrorOrFactory.From(GetPathSegments());
IEnumerable<PathSegment> GetPathSegments()
{
// the drive segment
yield return new PathSegment(path.Path[..2], isDirectory: false, isDrive: true);
// extract the other segments
var segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < segments.Length; i++)
string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < segments.Length; i++)
{
var segment = segments[i];
string segment = segments[i];
bool isDirectory;
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
@@ -132,15 +129,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy
if (tempPath.EndsWith('\\'))
tempPath = tempPath.TrimEnd(PathSeparator);
// 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 (lastIndex < 0)
return Errors.FileManagement.CannotNavigateUp;
// if we are at the drive root level after trimming, return drive root, otherwise, return the path up to the last slash
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]);
if (newPathResult.IsError)
return newPathResult.Errors;
return ParsePath(newPathResult.Value);
return newPathResult.IsError ? (ErrorOr<IEnumerable<PathSegment>>)newPathResult.Errors : ParsePath(newPathResult.Value);
}
/// <summary>
@@ -172,11 +167,11 @@ public class WindowsPathStrategy : IWindowsPathStrategy
// check for UNC paths (e.g., "\\server\share")
if (path.Path.StartsWith('\\'))
{
var parseResult = ParsePath(path);
ErrorOr<IEnumerable<PathSegment>> parseResult = ParsePath(path);
if (parseResult.IsError)
return parseResult.Errors;
var segments = parseResult.Value.ToList();
List<PathSegment> segments = parseResult.Value.ToList();
if (segments.Count >= 2)
{
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.
/// </summary>
public PlatformType Platform { get; } = PlatformType.Windows;
/// <summary>
/// Gets the path strategy for Windows platforms.
/// </summary>
@@ -48,9 +48,7 @@ public sealed class FileSystemPathId : ValueObject
/// </returns>
public static ErrorOr<FileSystemPathId> Create(string path)
{
if (string.IsNullOrWhiteSpace(path))
return Errors.FileManagement.InvalidPath;
return new FileSystemPathId(path);
return string.IsNullOrWhiteSpace(path) ? (ErrorOr<FileSystemPathId>)Errors.FileManagement.InvalidPath : (ErrorOr<FileSystemPathId>)new FileSystemPathId(path);
}
#endregion
}
@@ -20,37 +20,37 @@ public class StreamInfo : ValueObject
/// Gets the id of the stream.
/// </summary>
public string StreamId { get; }
/// <summary>
/// Gets the MimeType of the stream.
/// </summary>
public string MimeType { get; }
/// <summary>
/// Gets the bitrate of the stream.
/// </summary>
public int Bitrate { get; }
/// <summary>
/// Gets the codec of the stream.
/// </summary>
public string Codec { get; }
/// <summary>
/// Gets the optional resolution of the stream.
/// </summary>
public Optional<string> Resolution { get; }
/// <summary>
/// Gets the optional frame rate of the stream.
/// </summary>
public Optional<float> FrameRate { get; }
/// <summary>
/// Gets the optional sample rate of the stream.
/// </summary>
public Optional<int> SampleRate { get; }
/// <summary>
/// Gets the optional channels of the stream.
/// </summary>
@@ -70,13 +70,13 @@ public class StreamInfo : ValueObject
/// <param name="sampleRate">The sample rate of the stream (for audio).</param>
/// <param name="channels">The number of channels (for audio).</param>
private StreamInfo(
string streamId,
string mimeType,
int bitrate,
string streamId,
string mimeType,
int bitrate,
string codec,
Optional<string> resolution,
Optional<string> resolution,
Optional<float> frameRate,
Optional<int> sampleRate,
Optional<int> sampleRate,
Optional<int> channels)
{
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.
/// </returns>
public static ErrorOr<StreamInfo> Create(
string streamId,
string mimeType,
int bitrate,
string streamId,
string mimeType,
int bitrate,
string codec,
Optional<string> resolution,
Optional<float> frameRate,
Optional<int> sampleRate,
Optional<string> resolution,
Optional<float> frameRate,
Optional<int> sampleRate,
Optional<int> channels)
{
if (streamId is null)
return Errors.FileManagement.StreamIdCannotBeEmpty;
if (codec is null)
return Errors.FileManagement.CodecCannotBeEmpty;
if (bitrate <= 0)
return Errors.FileManagement.BitrateMustBeAPositiveNumber;
return new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
return streamId is null
? (ErrorOr<StreamInfo>)Errors.FileManagement.StreamIdCannotBeEmpty
: codec is null
? (ErrorOr<StreamInfo>)Errors.FileManagement.CodecCannotBeEmpty
: bitrate <= 0
? (ErrorOr<StreamInfo>)Errors.FileManagement.BitrateMustBeAPositiveNumber
: (ErrorOr<StreamInfo>)new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
}
/// <inheritdoc/>
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 death of the contributor.</param>
private MediaContributor(
MediaContributorId id,
MediaContributorName name,
MediaContributorRole role,
Optional<DateOnly> dateOfBirth,
MediaContributorId id,
MediaContributorName name,
MediaContributorRole role,
Optional<DateOnly> dateOfBirth,
Optional<DateOnly> dateOfDeath)
{
Id = id;
@@ -87,10 +87,10 @@ public class MediaContributor : AggregateRoot<MediaContributorId>
/// <param name="name">The name of the contributor.</param>
/// <returns>The created <see cref="MediaContributor"/> instance.</returns>
public static ErrorOr<MediaContributor> Create(
MediaContributorId id,
MediaContributorName name,
MediaContributorRole role,
Optional<DateOnly> dateOfBirth,
MediaContributorId id,
MediaContributorName name,
MediaContributorRole role,
Optional<DateOnly> dateOfBirth,
Optional<DateOnly> 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)
{
// TODO: enforce invariants
return new MediaContributorName(displayName, legalName);
return new MediaContributorName(displayName, legalName);
}
/// <inheritdoc/>
@@ -29,7 +29,7 @@ public sealed class MediaContributorId : EntityId<Guid>
public static MediaContributorId CreateUnique()
{
// TODO: enforce invariants
return new MediaContributorId(Guid.NewGuid());
return new MediaContributorId(Guid.NewGuid());
}
/// <summary>
@@ -40,7 +40,7 @@ public sealed class MediaContributorId : EntityId<Guid>
public static MediaContributorId Create(Guid value)
{
// TODO: enforce invariants
return new MediaContributorId(value);
return new MediaContributorId(value);
}
/// <inheritdoc/>
@@ -30,18 +30,12 @@ public sealed class Movie : Entity<MovieId>
/// <summary>
/// Gets the list of ratings for this movie.
/// </summary>
public IReadOnlyCollection<Rating> Ratings
{
get { return _ratings.AsReadOnly(); }
}
public IReadOnlyCollection<Rating> Ratings => _ratings.AsReadOnly();
/// <summary>
/// Gets the list of media contributors (actors, directors, etc) starring in this movie.
/// </summary>
public IReadOnlyCollection<MediaContributorId> Contributors
{
get { return _contributors.AsReadOnly(); }
}
public IReadOnlyCollection<MediaContributorId> Contributors => _contributors.AsReadOnly();
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -66,7 +60,7 @@ public sealed class Movie : Entity<MovieId>
/// </summary>
private Movie() // only needed during reflection
{
}
#pragma warning restore CS8618
#endregion
@@ -14,9 +14,6 @@ public sealed class MovieLibraryService : IMovieLibraryService
/// <summary>
/// Gets the collection of movies in the library.
/// </summary>
public ICollection<Movie> Movies
{
get { throw new NotImplementedException(); }
}
public ICollection<Movie> Movies => throw new NotImplementedException();
#endregion
}
@@ -12,7 +12,7 @@ namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.Value
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class MovieId : EntityId<Guid>
{
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="MovieId"/> class.
@@ -31,7 +31,7 @@ public sealed class MovieId : EntityId<Guid>
public static MovieId CreateUnique()
{
// TODO: enforce invariants
return new MovieId(Guid.NewGuid());
return new MovieId(Guid.NewGuid());
}
/// <summary>
@@ -42,7 +42,7 @@ public sealed class MovieId : EntityId<Guid>
public static MovieId Create(Guid value)
{
// TODO: enforce invariants
return new MovieId(value);
return new MovieId(value);
}
/// <inheritdoc/>
@@ -60,18 +60,18 @@ public class VideoMetadata : BaseMetadata
/// <param name="genres">The genres of the video.</param>
/// <param name="tags">The tags associated with the video.</param>
private VideoMetadata(
string title,
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
string title,
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
Optional<string> description,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
Optional<string> videoCodec,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
Optional<string> videoCodec,
Optional<string> audioCodec,
List<Genre> genres,
List<Genre> genres,
List<Tag> tags)
: 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.
/// </returns>
public static ErrorOr<VideoMetadata> Create(
string title,
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
string title,
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
Optional<string> description,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
Optional<string> videoCodec,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
Optional<string> videoCodec,
Optional<string> audioCodec,
List<Genre> genres,
List<Genre> genres,
List<Tag> tags)
{
return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, description, releaseInfo,
@@ -125,7 +125,7 @@ public class VideoMetadata : BaseMetadata
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
foreach (var component in base.GetEqualityComponents())
foreach (object component in base.GetEqualityComponents())
yield return component;
yield return DurationInSeconds;
yield return Resolution;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities;
@@ -14,9 +14,6 @@ public class TvShowLibraryService : ITvShowLibraryService
/// <summary>
/// Gets the collection of TV shows in the library.
/// </summary>
public ICollection<TvShow> TvShows
{
get { throw new NotImplementedException(); }
}
public ICollection<TvShow> TvShows => throw new NotImplementedException();
#endregion
}
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate;
@@ -99,26 +99,17 @@ public sealed class Book : AggregateRoot<BookId>
/// <summary>
/// Gets the list of ISBN (International Standard Book Number) of the book.
/// </summary>
public IReadOnlyCollection<Isbn> ISBNs
{
get { return _isbns.AsReadOnly(); }
}
public IReadOnlyCollection<Isbn> ISBNs => _isbns.AsReadOnly();
/// <summary>
/// Gets the list of media contributors (actors, directors, etc) starring in this book.
/// </summary>
public IReadOnlyCollection<MediaContributorId> Contributors
{
get { return _contributors.AsReadOnly(); }
}
public IReadOnlyCollection<MediaContributorId> Contributors => _contributors.AsReadOnly();
/// <summary>
/// Gets the list of ratings for this book.
/// </summary>
public IReadOnlyCollection<BookRating> Ratings
{
get { return _ratings.AsReadOnly(); }
}
public IReadOnlyCollection<BookRating> Ratings => _ratings.AsReadOnly();
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -33,10 +33,7 @@ public sealed class BookSeries : Entity<BookSeriesId>
/// <summary>
/// Gets the collection of books in the series.
/// </summary>
public IReadOnlyCollection<Book> Books
{
get { return _books.AsReadOnly(); }
}
public IReadOnlyCollection<Book> Books => _books.AsReadOnly();
#endregion
#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.
/// </returns>
public static ErrorOr<BookSeries> Create(
BookSeriesId id,
WrittenContentMetadata metadata,
bool isComplete,
BookSeriesId id,
WrittenContentMetadata metadata,
bool isComplete,
List<Book> books)
{
// TODO: enforce invariants
@@ -14,9 +14,6 @@ public sealed class BookLibraryService : IBookLibraryService
/// <summary>
/// Gets the collection of books in the library.
/// </summary>
public ICollection<Book> Books
{
get { throw new NotImplementedException(); }
}
public ICollection<Book> Books => throw new NotImplementedException();
#endregion
}
@@ -14,7 +14,7 @@ public interface IBookLibraryService
/// Gets the collection of books in the library.
/// </summary>
ICollection<Book> Books { get; }
// ICollection<BookSeries> Series { get; }
#endregion
@@ -51,11 +51,9 @@ public class BookRating : Rating
/// </returns>
public static ErrorOr<BookRating> Create(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
{
if (maxValue < 0 || value < 0)
return Errors.Metadata.RatingValueMustBePositive;
if (value > maxValue)
return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue;
return new BookRating(value, maxValue, source, voteCount);
return maxValue < 0 || value < 0
? (ErrorOr<BookRating>)Errors.Metadata.RatingValueMustBePositive
: value > maxValue ? (ErrorOr<BookRating>)Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue : (ErrorOr<BookRating>)new BookRating(value, maxValue, source, voteCount);
}
/// <inheritdoc/>
@@ -48,7 +48,7 @@ public class WrittenContentMetadata : BaseMetadata
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<string> publisher,
Optional<int> pageCount)
@@ -88,23 +88,23 @@ public class WrittenContentMetadata : BaseMetadata
Optional<string> publisher,
Optional<int> pageCount)
{
if (string.IsNullOrWhiteSpace(title))
return Errors.Metadata.TitleCannotBeEmpty;
if (releaseInfo is null)
return Errors.Metadata.ReleaseInfoCannotBeNull;
if (genres is null)
return Errors.Metadata.GenresListCannotBeNull;
if (tags is null)
return Errors.Metadata.TagsListCannotBeNull;
return new WrittenContentMetadata(
title,
originalTitle,
description,
releaseInfo,
genres, tags,
language,
originalLanguage,
publisher,
return string.IsNullOrWhiteSpace(title)
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.TitleCannotBeEmpty
: releaseInfo is null
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.ReleaseInfoCannotBeNull
: genres is null
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.GenresListCannotBeNull
: tags is null
? (ErrorOr<WrittenContentMetadata>)Errors.Metadata.TagsListCannotBeNull
: (ErrorOr<WrittenContentMetadata>)new WrittenContentMetadata(
title,
originalTitle,
description,
releaseInfo,
genres, tags,
language,
originalLanguage,
publisher,
pageCount
);
}
@@ -112,7 +112,7 @@ public class WrittenContentMetadata : BaseMetadata
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
foreach (var component in base.GetEqualityComponents())
foreach (object component in base.GetEqualityComponents())
yield return component;
yield return Publisher;
yield return PageCount;
+2 -3
View File
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
@@ -24,5 +24,4 @@
<ItemGroup>
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
</ItemGroup>
</Project>
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using System.Reflection;
using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
#endregion
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>
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))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
configuration.SetBasePath(basePath);
configuration.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.shared.Development.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
// bind the common settings section
services.AddOptions<CommonSettingsModel>()
.Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName))
@@ -42,7 +42,7 @@ public static class SharedConfiguration
services.AddOptions<DatabaseSettingsModel>()
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName))
.ValidateFluently()
.ValidateOnStart();
.ValidateOnStart();
return services;
}
#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
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
if (validationResult.IsValid)
return ValidateOptionsResult.Success;
// if the validation fails, collect 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();
// and return them with a failure result
@@ -1,18 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.9.2" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
@@ -35,5 +34,4 @@
<ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
</ItemGroup>
</Project>
@@ -36,8 +36,8 @@ public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
public void Configure(SwaggerGenOptions options)
{
// add swagger document for every API version discovered
foreach (var description in _provider.ApiVersionDescriptions)
options.SwaggerDoc(description.GroupName,CreateVersionInfo(description));
foreach (ApiVersionDescription description in _provider.ApiVersionDescriptions)
options.SwaggerDoc(description.GroupName, CreateVersionInfo(description));
}
/// <summary>
@@ -57,7 +57,7 @@ public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
/// <returns>The created <see cref="OpenApiInfo"/> instance.</returns>
private OpenApiInfo CreateVersionInfo(ApiVersionDescription description)
{
var info = new OpenApiInfo()
OpenApiInfo info = new()
{
Title = "Lumina API",
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>
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))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
configuration.SetBasePath(basePath);
@@ -25,14 +25,11 @@ public static class PresentationApiLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
services.AddCors(options => options.AddPolicy("AllowAll",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
.AllowAnyHeader()));
// add services to the container
services.AddControllers().AddJsonOptions(options =>
@@ -45,7 +42,7 @@ public static class PresentationApiLayerServices
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.ConfigureOptions<ConfigureSwaggerOptions>();
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
@@ -62,7 +59,7 @@ public static class PresentationApiLayerServices
services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();
// register mapster configs
var mapsterConfig = TypeAdapterConfig.GlobalSettings;
TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly);
services.AddSingleton(mapsterConfig);
services.AddScoped<IMapper, ServiceMapper>();
@@ -53,7 +53,7 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory
string? detail = null, string? instance = null)
{
statusCode ??= 500;
var problemDetails = new ProblemDetails
ProblemDetails problemDetails = new()
{
Status = statusCode,
Title = title,
@@ -81,7 +81,7 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory
{
ArgumentNullException.ThrowIfNull(modelStateDictionary);
statusCode ??= 400;
var problemDetails = new ValidationProblemDetails(modelStateDictionary)
ValidationProblemDetails problemDetails = new(modelStateDictionary)
{
Status = statusCode,
Type = type,
@@ -104,23 +104,20 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory
private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int 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.Type ??= clientErrorData.Link;
}
var traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier;
string? traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier;
if (traceId != null)
problemDetails.Extensions["traceId"] = traceId;
// 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
if (errors is not null)
{
problemDetails.Extensions.Add("errors", errors.Select(error =>
{
return error.Code;
}));
problemDetails.Extensions.Add("errors", errors.Select(error => error.Code));
}
//problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString()));
_configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails });
@@ -23,7 +23,7 @@ public class UrlStringBinder : IModelBinder
throw new ArgumentNullException(nameof(bindingContext));
string modelName = bindingContext.ModelName;
// 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)
return Task.CompletedTask;
string? value = valueProviderResult.FirstValue;
@@ -43,7 +43,7 @@ public abstract class ApiController : ControllerBase
/// <param name="error">The error to convert.</param>
protected internal IActionResult Problem(Error error)
{
var statusCode = error.Type switch
int statusCode = error.Type switch
{
ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.NotFound => StatusCodes.Status404NotFound,
@@ -62,8 +62,8 @@ public abstract class ApiController : ControllerBase
/// <param name="errors">The list of errors to convert.</param>
protected internal IActionResult ValidationProblem(List<Error> errors)
{
var modelStateDictionary = new ModelStateDictionary();
foreach (var error in errors)
ModelStateDictionary modelStateDictionary = new();
foreach (Error error in errors)
modelStateDictionary.AddModelError(error.Code, error.Description);
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);
if (!result.IsError && result.Value is not null)
{
foreach (var treeNode in result.Value)
foreach (FileSystemTreeNodeResponse treeNode in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
@@ -69,7 +69,7 @@ public class DirectoriesController : ApiController
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeDirectoriesQuery(path), cancellationToken).ConfigureAwait(false);
if (!result.IsError && result.Value is not null)
{
foreach (var directory in result.Value)
foreach (FileSystemTreeNodeResponse directory in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
@@ -89,7 +89,7 @@ public class DirectoriesController : ApiController
ErrorOr<IEnumerable<DirectoryResponse>> result = await _mediator.Send(new GetDirectoriesQuery(path), cancellationToken).ConfigureAwait(false);
if (!result.IsError && result.Value is not null)
{
foreach (var directory in result.Value)
foreach (DirectoryResponse directory in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
@@ -43,7 +43,7 @@ public class DrivesController : ApiController
public async Task<IActionResult> GetDrives(CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
return result.Match(Ok, Problem);
}
#endregion
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSysem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
@@ -39,8 +40,8 @@ public class FileSystemController : ApiController
[HttpGet("get-type")]
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);
}
#endregion
}
}
@@ -47,7 +47,7 @@ public class FilesController : ApiController
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);
foreach (var file in result.Value)
foreach (FileSystemTreeNodeResponse file in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
@@ -66,7 +66,7 @@ public class FilesController : ApiController
ErrorOr<IEnumerable<FileResponse>> result = await _mediator.Send(new GetFilesQuery(path), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (var file in result.Value)
foreach (FileResponse file in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
@@ -40,7 +40,7 @@ public class PathController : ApiController
_mediator = mediator;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// 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)
{
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>
@@ -74,7 +74,7 @@ public class PathController : ApiController
public async Task<IActionResult> GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
return result.Match(Ok, Problem);
}
/// <summary>
@@ -87,7 +87,7 @@ public class PathController : ApiController
public async Task<IActionResult> CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken)
{
ErrorOr<PathSegmentResponse> result = await _mediator.Send(new CombinePathCommand(originalPath, newPath), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
return result.Match(Ok, Problem);
}
/// <summary>
@@ -99,7 +99,7 @@ public class PathController : ApiController
public async Task<IActionResult> SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
return result.Match(Ok, Problem);
}
/// <summary>
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Controllers.Common;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
@@ -20,7 +20,7 @@ public class HealthController : ApiController
public async Task<IActionResult> CheckHealth()
{
// TODO: to be implemented
return Ok();
return await Task.FromResult(Ok());
}
#endregion
}
@@ -43,8 +43,8 @@ public class BooksController : ApiController
[HttpGet()]
public async Task<IActionResult> GetBooks()
{
var result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
ErrorOr.ErrorOr<System.Collections.Generic.IEnumerable<Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Book>> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false);
return result.Match(Ok, Problem);
}
/// <summary>
@@ -54,8 +54,8 @@ public class BooksController : ApiController
[HttpPost()]
public async Task<IActionResult> AddBook(AddBookRequest request)
{
var result = await _mediator.Send(_mapper.Map<AddBookCommand>(request)).ConfigureAwait(false);
return result.Match(result => Created($"/api/v1/books/{result.Id}", result), errors => Problem(errors));
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), Problem);
}
#endregion
}
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<UserSecretsId>37d55c87-4374-4971-82e9-012fcaad1853</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<ContainerRepository>lumina-server</ContainerRepository>
@@ -17,7 +17,6 @@
<Compile Include="..\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mapster" Version="7.4.0" />
<PackageReference Include="Mapster.DependencyInjection" Version="1.0.1" />
@@ -53,6 +52,10 @@
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
<ProjectReference Include="..\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
<ProjectReference Include="..\Lumina.DataAccess\Lumina.DataAccess.csproj" />
</ItemGroup>
</ItemGroup>
<!--disable warnings generated by Mediator source generator-->
<PropertyGroup>
<NoWarn>$(NoWarn);CS0436</NoWarn>
</PropertyGroup>
</Project>
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more