Updates to .NET 9.0

This commit is contained in:
BinaryAlley committed 2024-11-13 20:46:54 +02:00
commit acbdb0a5f8
853 files changed
+34993 -10123

No files matched your search

@@ -1,64 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
#endregion
namespace Lumina.Presentation.Api.Common.Configuration;
/// <summary>
/// Configures the Swagger options.
/// </summary>
public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
private readonly IApiVersionDescriptionProvider _provider;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureSwaggerOptions"/> class.
/// </summary>
/// <param name="provider">Provider for API version descriptions.</param>
public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider)
{
_provider = provider;
}
/// <summary>
/// Configures the Swagger options.
/// </summary>
/// <param name="options">The options instance to configure.</param>
public void Configure(SwaggerGenOptions options)
{
// add swagger document for every API version discovered
foreach (ApiVersionDescription description in _provider.ApiVersionDescriptions)
options.SwaggerDoc(description.GroupName, CreateVersionInfo(description));
}
/// <summary>
/// Configures the Swagger options.
/// </summary>
/// <param name="name">The name of the options instance being configured.</param>
/// <param name="options">The options instance to configure.</param>
public void Configure(string? name, SwaggerGenOptions options)
{
Configure(options);
}
/// <summary>
/// Creates the version information for the Swagger document.
/// </summary>
/// <param name="description">The API version description.</param>
/// <returns>The created <see cref="OpenApiInfo"/> instance.</returns>
private OpenApiInfo CreateVersionInfo(ApiVersionDescription description)
{
OpenApiInfo info = new()
{
Title = "Lumina API",
Version = description.ApiVersion.ToString()
};
if (description.IsDeprecated)
info.Description += " This API version has been deprecated.";
return info;
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
#endregion
@@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection;
/// <summary>
/// Class containing the configuration bindings of the Presentation API layer.
/// </summary>
[ExcludeFromCodeCoverage]
internal static class PresentationApiLayerConfiguration
{
/// <summary>
@@ -30,4 +32,4 @@ internal static class PresentationApiLayerConfiguration
return services;
}
}
}
@@ -1,13 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Converters;
using Lumina.Presentation.Api.Common.Configuration;
using Lumina.Presentation.Api.Common.Errors;
using Mapster;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using FastEndpoints;
using FastEndpoints.Swagger;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
#endregion
namespace Lumina.Presentation.Api.Common.DependencyInjection;
@@ -15,15 +22,149 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection;
/// <summary>
/// Contains all services of the Presentation API layer.
/// </summary>
[ExcludeFromCodeCoverage]
public static class PresentationApiLayerServices
{
/// <summary>
/// Registers the services of the Presentation API layer into the dependency injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="configuration">Application configuration properties.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting
services.AddProblemDetails();
services.Configure<JsonOptions>(jsonOptions =>
{
jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
jsonOptions.SerializerOptions.MaxDepth = 256;
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
});
// TODO: also implement account locking after a number of failed login attempts
services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
{
ILogger logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();
string clientIp = context.HttpContext.Request.Headers["X-Forwarded-For"]
.FirstOrDefault()?.Split(',')[0].Trim()
?? context.HttpContext.Connection.RemoteIpAddress?.ToString()
?? "unknown";
Log.Warning(
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
clientIp,
context.HttpContext.Request.Path,
context.Lease.IsAcquired); // when False, the request was rejected because it exceeded rate limits
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.HttpContext.Response.ContentType = "application/problem+json";
// set standard rate limit headers
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
// set custom rate limit headers
context.HttpContext.Response.Headers["X-RateLimit-Limit"] = "10";
context.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0";
context.HttpContext.Response.Headers["X-RateLimit-Reset"] = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds().ToString();
var problem = new
{
type = "https://tools.ietf.org/html/rfc7231#section-6.5.29",
title = "TooManyRequests", // TODO: implement translation?
status = StatusCodes.Status429TooManyRequests,
detail = "Too many attempts. Please try again later.",
retryAfter = "15"
};
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
};
options.AddPolicy("authenticationPolicy", httpContext =>
{
string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // first check forwarded headers, in case this is behind a reverse proxy
.FirstOrDefault()?.Split(',')[0].Trim() // take first IP, if multiple available, to avoid IP spoofing attempts
?? httpContext.Connection.RemoteIpAddress?.ToString() // then try RemoteIpAddress
?? "unknown"; // fallback if both are null
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: $"auth_{clientIp}",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 10, // allow 10 attempts
Window = TimeSpan.FromMinutes(15), // within 15 minute window
QueueLimit = 0, // don't queue requests
AutoReplenishment = true // automatically reset rate limiter tokens
});
});
});
// add authentication and specify the JWT scheme to check tokens against
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["JwtSettings:Issuer"],
ValidAudience = configuration["JwtSettings:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]!)),
};
options.Events = new JwtBearerEvents
{
OnChallenge = context => // event triggered when authentication is not successful for whatever reason
{
context.HandleResponse(); // prevent the default 401 response
// set the response status code to 401 Unauthorized
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/problem+json";
IProblemDetailsService problemDetailsService = context.HttpContext.RequestServices.GetRequiredService<IProblemDetailsService>();
return context.Response.WriteAsJsonAsync(new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = StatusCodes.Status401Unauthorized,
title = "Unauthorized",
detail = "You are not authorized",
instance = context.HttpContext.Request.Path
});
}
};
});
services.AddAuthorization();
services.AddFastEndpoints(
o => o.Assemblies =
[
typeof(Program).Assembly
]);
services.SwaggerDocument(documentOptions =>
{
documentOptions.SerializerSettings = s =>
{
s.PropertyNamingPolicy = null;
s.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
};
documentOptions.MaxEndpointVersion = 1;
documentOptions.MinEndpointVersion = 1;
documentOptions.DocumentSettings = s =>
{
s.DocumentName = "Release 1.0";
s.Title = "Lumina API";
s.Version = "v1.0";
};
documentOptions.RemoveEmptyRequestSchema = true;
documentOptions.ShortSchemaNames = true;
});
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
@@ -33,41 +174,6 @@ public static class PresentationApiLayerServices
.AllowAnyHeader());
});
// add services to the container
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.MaxDepth = 256;
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.Converters.Add(new OptionalJsonConverterFactory());
});
// add services to the container.
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.ConfigureOptions<ConfigureSwaggerOptions>();
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();
// register mapster configs
TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly);
services.AddSingleton(mapsterConfig);
services.AddScoped<IMapper, ServiceMapper>();
return services;
}
}
@@ -1,118 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.Common.Errors;
/// <summary>
/// Problem details factory which adds custom properties to the default implementation provided by Microsoft.
/// </summary>
public class CustomProblemDetailsFactory : ProblemDetailsFactory
{
private readonly ApiBehaviorOptions _options;
private readonly Action<ProblemDetailsContext>? _configure;
/// <summary>
/// Initializes a new instance of the <see cref="CustomProblemDetailsFactory"/> class.
/// </summary>
/// <param name="apiBehaviorOptions">Injected service for retrieving <see cref="ApiBehaviorOptions"/>.</param>
/// <param name="problemDetailsOptions">Injected service for retrieving <see cref="ProblemDetailsOptions"/>.</param>
/// <exception cref="ArgumentNullException">Thrown when the value of options (if any) is <see langword="null"/>.</exception>
public CustomProblemDetailsFactory(IOptions<ApiBehaviorOptions> apiBehaviorOptions, IOptions<ProblemDetailsOptions>? problemDetailsOptions = null)
{
_options = apiBehaviorOptions?.Value ?? throw new ArgumentNullException(nameof(apiBehaviorOptions));
_configure = problemDetailsOptions?.Value?.CustomizeProblemDetails;
}
/// <summary>
/// Creates a <see cref="ProblemDetails"/> instance that configures defaults based on values specified in <see cref="ApiBehaviorOptions"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/>.</param>
/// <param name="statusCode">The value for <see cref="ProblemDetails.Status"/>.</param>
/// <param name="title">The value for <see cref="ProblemDetails.Title"/>.</param>
/// <param name="type">The value for <see cref="ProblemDetails.Type"/>.</param>
/// <param name="detail">The value for <see cref="ProblemDetails.Detail"/>.</param>
/// <param name="instance">The value for <see cref="ProblemDetails.Instance"/>.</param>
/// <returns>The <see cref="ProblemDetails"/> instance.</returns>
public override ProblemDetails CreateProblemDetails(HttpContext httpContext, int? statusCode = null, string? title = null, string? type = null,
string? detail = null, string? instance = null)
{
statusCode ??= 500;
ProblemDetails problemDetails = new()
{
Status = statusCode,
Title = title,
Type = type,
Detail = detail,
Instance = instance,
};
ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode.Value);
return problemDetails;
}
/// <summary>
/// Creates a <see cref="ValidationProblemDetails"/> instance that configures defaults based on values specified in <see cref="ApiBehaviorOptions"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext" />.</param>
/// <param name="modelStateDictionary">The <see cref="ModelStateDictionary"/>.</param>
/// <param name="statusCode">The value for <see cref="ProblemDetails.Status"/>.</param>
/// <param name="title">The value for <see cref="ProblemDetails.Title"/>.</param>
/// <param name="type">The value for <see cref="ProblemDetails.Type"/>.</param>
/// <param name="detail">The value for <see cref="ProblemDetails.Detail"/>.</param>
/// <param name="instance">The value for <see cref="ProblemDetails.Instance"/>.</param>
/// <returns>The <see cref="ValidationProblemDetails"/> instance.</returns>
public override ValidationProblemDetails CreateValidationProblemDetails(HttpContext httpContext, ModelStateDictionary modelStateDictionary, int? statusCode = null,
string? title = null, string? type = null, string? detail = null, string? instance = null)
{
ArgumentNullException.ThrowIfNull(modelStateDictionary);
statusCode ??= 400;
ValidationProblemDetails problemDetails = new(modelStateDictionary)
{
Status = statusCode,
Type = type,
Detail = detail,
Instance = instance,
};
if (title != null)
problemDetails.Title = title; // for validation problem details, don't overwrite the default title with null
ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode.Value);
return problemDetails;
}
/// <summary>
/// Creates a <see cref="ValidationProblemDetails"/> instance that configures defaults based on values specified in <see cref="ApiBehaviorOptions"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext" />.</param>
/// <param name="statusCode">The value for <see cref="ProblemDetails.Status"/>.</param>
/// <param name="problemDetails">The value for <see cref="ProblemDetails"/>.</param>
/// <returns>The <see cref="ValidationProblemDetails"/> instance.</returns>
private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int statusCode)
{
problemDetails.Status ??= statusCode;
if (_options.ClientErrorMapping.TryGetValue(statusCode, out ClientErrorData? clientErrorData))
{
problemDetails.Title ??= clientErrorData.Title;
problemDetails.Type ??= clientErrorData.Link;
}
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
List<Error>? errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List<Error>;
// add any extra custom properties
if (errors is not null)
problemDetails.Extensions.Add("errors", errors.Select(error => error.Code));
//problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString()));
_configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails });
}
}
@@ -1,6 +1,4 @@
#region ========================================================================= USING =====================================================================================
namespace Lumina.Presentation.Api.Common.Http;
#endregion
/// <summary>
/// Constants shared by HttpContext across a HTTP request (avoid magic strings).
@@ -8,4 +6,4 @@ namespace Lumina.Presentation.Api.Common.Http;
public static class HttpContextItemKeys
{
public const string ERRORS = "errors";
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary;
using Mapster;
#endregion
namespace Lumina.Presentation.Api.Common.Mapping.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Mapping configuration for books between the API request object and the command object.
/// </summary>
public class BookMappingConfig : IRegister
{
/// <summary>
/// Registers the mapping configuration.
/// </summary>
/// <param name="config">The type adapter configuration.</param>
public void Register(TypeAdapterConfig config)
{
config.NewConfig<AddBookRequest, AddBookCommand>()
.Map(dest => dest.ASIN, src => src.ASIN)
.Map(dest => dest.ISBNs, src => src.ISBNs)
.Map(dest => dest.LCCN, src => src.LCCN)
.Map(dest => dest.OCLCNumber, src => src.OCLCNumber)
.MapToConstructor(true);
}
}
@@ -1,38 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Common.ModelBinders;
/// <summary>
/// Custom model binder for URL parameters. For some reason, the default binder converts "%20" to "+", instead of " ".
/// </summary>
public class UrlStringBinder : IModelBinder
{
/// <summary>
/// Binds a model to a value by using the specified controller context and binding context.
/// </summary>
/// <param name="bindingContext">The context within which to bind the model.</param>
/// <returns>A task representing the bind operation.</returns>
public Task BindModelAsync(ModelBindingContext bindingContext)
{
ArgumentNullException.ThrowIfNull(bindingContext);
string modelName = bindingContext.ModelName;
// try to fetch the value of the argument by name
ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
return Task.CompletedTask;
string? value = valueProviderResult.FirstValue;
if (value is null)
{
bindingContext.Result = ModelBindingResult.Failed();
return Task.CompletedTask;
}
// do the custom decoding here
value = Uri.UnescapeDataString(value);
bindingContext.Result = ModelBindingResult.Success(value);
return Task.CompletedTask;
}
}
@@ -0,0 +1,17 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Directories route.
/// </summary>
public static class Directories
{
public const string GET_DIRECTORY_TREE = "/directories/get-directory-tree";
public const string GET_TREE_DIRECTORIES = "/directories/get-tree-directories";
public const string GET_DIRECTORIES = "/directories/get-directories";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Drives route.
/// </summary>
public static class Drives
{
public const string GET_DRIVES = "/drives/get-drives";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the FileSystem route.
/// </summary>
public static class FileSystem
{
public const string GET_TYPES = "/file-system/get-type";
}
}
@@ -0,0 +1,16 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Files route.
/// </summary>
public static class Files
{
public const string GET_TREE_FILES = "/files/get-tree-files";
public const string GET_FILES = "/files/get-files";
}
}
@@ -0,0 +1,21 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Path route.
/// </summary>
public static class Path
{
public const string GET_PATH_ROOT = "/path/get-path-root";
public const string GET_PATH_SEPARATOR = "/path/get-path-separator";
public const string GET_PATH_PARENT = "/path/get-path-parent";
public const string COMBINE = "/path/combine";
public const string SPLIT = "/path/split";
public const string VALIDATE = "/path/validate";
public const string CHECK_PATH_EXISTS = "/path/check-path-exists";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Thumbnails route.
/// </summary>
public static class Thumbnails
{
public const string GET_THUMBNAIL = "/thumbnails/get-thumbnail";
}
}
@@ -0,0 +1,17 @@
namespace Lumina.Presentation.Api.Common.Routes.Library.Management;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Libraries route.
/// </summary>
public static class Libraries
{
public const string GET_LIBRARY_BY_ID = "/libraries/{id}";
public const string GET_LIBRARIES = "/libraries";
public const string ADD_LIBRARY = "/libraries";
}
}
@@ -0,0 +1,17 @@
namespace Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Books route.
/// </summary>
public static class Books
{
public const string GET_BOOK_BY_ID = "/books/{id}";
public const string GET_BOOKS = "/books";
public const string ADD_BOOK = "/books";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Health route.
/// </summary>
public static class Health
{
public const string CHECK_HEALTH = "/check-health";
}
}
@@ -0,0 +1,16 @@
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Initialization route.
/// </summary>
public static class Initialization
{
public const string SETUP_APPLICATION = "/initialization";
public const string CHECK_INITIALIZATION = "/initialization";
}
}
@@ -0,0 +1,18 @@
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Authentication route.
/// </summary>
public static class Authentication
{
public const string REGISTER_ACCOUNT = "/auth/register";
public const string LOGIN_ACCOUNT = "/auth/login";
public const string RECOVER_PASSWORD = "/auth/recover-password";
public const string CHANGE_PASSWORD = "/auth/change-password";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Users route.
/// </summary>
public static class Users
{
public const string GET_USER_BY_ID = "/users/{id}";
}
}
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using System.Collections.Frozen;
using System.Collections.Generic;
#endregion
@@ -1,69 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.Common;
/// <summary>
/// Base class for API controllers.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
public abstract class ApiController : ControllerBase
{
/// <summary>
/// Handles controllers errors.
/// </summary>
/// <param name="errors">The error to handle.</param>
protected internal IActionResult Problem(List<Error> errors)
{
if (errors.Count is 0) // if there are no custom errors given, return a generic problem
return Problem();
// try to make the problem type more specific
if (errors.All(error => error.Type == ErrorType.Validation))
return ValidationProblem(errors);
// here we could handle custom error types, for instance: if (errors.All(error => error.NumericType == 23)), where 23 could be "domain errors"
// share the list of errors within the scope of this HTTP request
HttpContext.Items[HttpContextItemKeys.ERRORS] = errors;
// get a HTTP error status code for the selected domain error type
return Problem(errors.First());
}
/// <summary>
/// Converts an <see cref="Error"/> to a standard problem response.
/// </summary>
/// <param name="error">The error to convert.</param>
protected internal IActionResult Problem(Error error)
{
int statusCode = error.Type switch
{
ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Validation => StatusCodes.Status400BadRequest,
ErrorType.Failure => StatusCodes.Status403Forbidden,
_ => StatusCodes.Status500InternalServerError,
};
// return the HTTP error status and the domain error message
return Problem(statusCode: statusCode, title: error.Type.ToString(), detail: error.Description);
}
/// <summary>
/// Converts a list of <see cref="Error"/> into a standard validation problem response.
/// </summary>
/// <param name="errors">The list of errors to convert.</param>
protected internal IActionResult ValidationProblem(List<Error> 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.");
}
}
@@ -1,101 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories;
using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree;
using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system directories.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class DirectoriesController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="DirectoriesController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public DirectoriesController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the tree of expanded directories leading up to <paramref name="path"/>, with the additional list of drives, and children of the last child directory.
/// </summary>
/// <param name="path">The path for which to get the directory tree.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-directory-tree")]
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetDirectoryTree([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileSystemTreeNodeResponse treeNode in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return treeNode;
}
}
}
/// <summary>
/// Gets the directories of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the directories.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-tree-directories")]
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeDirectoriesQuery(path,includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileSystemTreeNodeResponse directory in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return directory;
}
}
}
/// <summary>
/// Gets the directories of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the directories.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-directories")]
public async IAsyncEnumerable<DirectoryResponse> GetDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<DirectoryResponse>> result = await _mediator.Send(new GetDirectoriesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (DirectoryResponse directory in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return directory;
}
}
}
}
@@ -1,43 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system drives.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class DrivesController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="DrivesController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public DrivesController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Controller action for getting the list of all file system drives.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-drives")]
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));
}
}
@@ -1,41 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file systems.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/file-system")]
public class FileSystemController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public FileSystemController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the type of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-type")]
public async Task<IActionResult> GetType(CancellationToken cancellationToken)
{
FileSystemTypeResponse platformType = await _mediator.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false);
return Ok(platformType);
}
}
@@ -1,78 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles;
using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system files.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class FilesController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="FilesController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public FilesController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the files of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the files.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-tree-files")]
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileSystemTreeNodeResponse file in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return file;
}
}
}
/// <summary>
/// Gets the files of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the files.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-files")]
public async IAsyncEnumerable<FileResponse> GetFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileResponse>> result = await _mediator.Send(new GetFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileResponse file in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return file;
}
}
}
}
@@ -1,124 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath;
using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath;
using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists;
using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent;
using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot;
using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator;
using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system paths.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class PathController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="PathController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public PathController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the root of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-root")]
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));
}
/// <summary>
/// Gets the path separator character of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-separator")]
public async Task<IActionResult> GetPathSeparator(CancellationToken cancellationToken)
{
PathSeparatorResponse result = await _mediator.Send(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Gets the path separator character of the file system.
/// </summary>
/// <param name="path">The path for which to get the parent path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-parent")]
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));
}
/// <summary>
/// Combines <paramref name="originalPath"/> with <paramref name="newPath"/>.
/// </summary>
/// <param name="originalPath">The path to combine to.</param>
/// <param name="newPath">The path to combine with.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("combine")]
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));
}
/// <summary>
/// Gets the path components of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the path segments.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("split")]
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));
}
/// <summary>
/// Validates the validity of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path to be validated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("validate")]
public async Task<IActionResult> ValidatePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{
PathValidResponse result = await _mediator.Send(new ValidatePathQuery(path), cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Checks whether <paramref name="path"/> exists or not.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("check-path-exists")]
public async Task<IActionResult> CheckPathExists([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
PathExistsResponse result = await _mediator.Send(new CheckPathExistsQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
return Ok(result);
}
}
@@ -1,46 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Common.Utilities;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system items thumbnails.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ThumbnailsController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailsController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public ThumbnailsController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the thumbnail of a file identified by of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path of the file for which to get the thumbnail.</param>
/// <param name="quality">The quality to use for the thumbnail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-thumbnail")]
public async Task<IActionResult> GetThumbnail([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] int quality, CancellationToken cancellationToken)
{
ErrorOr<ThumbnailResponse> getResult = await _mediator.Send(new GetThumbnailQuery(path, quality), cancellationToken);
return getResult.Match(result => File(result.Bytes, MimeTypes.GetMimeType(result.Type)), errors => Problem(errors));
}
}
@@ -1,24 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Controllers.Common;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.Maintenance;
/// <summary>
/// Controller for health checks.
/// </summary>
[Route("[controller]")]
public class HealthController : ApiController
{
/// <summary>
/// Checks if the application is healthy.
/// </summary>
[HttpGet("check-health")]
public async Task<IActionResult> CheckHealth()
{
// TODO: to be implemented
return await Task.FromResult(Ok());
}
}
@@ -1,55 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Controllers.Common;
using MapsterMapper;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Controller for managing books.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class BooksController : ApiController
{
private readonly ISender _mediator;
private readonly IMapper _mapper;
/// <summary>
/// Initializes a new instance of the <see cref="BooksController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
/// <param name="mapper">Injected service for mapping objects.</param>
public BooksController(ISender mediator, IMapper mapper)
{
_mediator = mediator;
_mapper = mapper;
}
/// <summary>
/// Controller action for getting the list of all books.
/// </summary>
[HttpGet()]
public async Task<IActionResult> GetBooks()
{
ErrorOr.ErrorOr<System.Collections.Generic.IEnumerable<Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Book>> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
}
/// <summary>
/// Controller action for adding a book.
/// </summary>
/// <param name="request">The command to add a book.</param>
[HttpPost()]
public async Task<IActionResult> AddBook(AddBookRequest request)
{
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);
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Common;
/// <summary>
/// Base class for API endpoints.
/// </summary>
/// <typeparam name="TRequest">The type of the request object.</typeparam>
/// <typeparam name="TResponse">The type of the response object.</typeparam>
public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TResponse> where TRequest : notnull
where TResponse : notnull
{
/// <summary>
/// Handles controllers errors.
/// </summary>
/// <param name="errors">The error to handle.</param>
protected IResult Problem(List<Error> errors)
{
if (errors.Count is 0) // if there are no custom errors given, return a generic problem
return Results.Problem();
// try to make the problem type more specific
if (errors.All(error => error.Type == ErrorType.Validation))
return ValidationProblem(errors);
// here we could handle custom error types, for instance: if (errors.All(error => error.NumericType == 23)), where 23 could be "domain errors"
// share the list of errors within the scope of this HTTP request
HttpContext.Items[HttpContextItemKeys.ERRORS] = errors;
// get a HTTP error status code for the selected domain error type
return Problem(errors.First());
}
/// <summary>
/// Converts an <see cref="Error"/> to a standard problem response.
/// </summary>
/// <param name="error">The error to convert.</param>
protected IResult Problem(Error error)
{
Dictionary<string, object?> extensionsDictionary = [];
int statusCode = error.Type switch
{
ErrorType.Validation => StatusCodes.Status400BadRequest,
ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in)
ErrorType.Failure => StatusCodes.Status403Forbidden,
ErrorType.Forbidden => StatusCodes.Status403Forbidden,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Conflict => StatusCodes.Status409Conflict,
_ => StatusCodes.Status500InternalServerError,
};
extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
// return the HTTP error status and the domain error message
return Results.Problem(
detail: error.Description,
instance: HttpContext.Request.Path,
statusCode: statusCode,
title: error.Code,
extensions: extensionsDictionary
);
}
/// <summary>
/// Converts a list of <see cref="Error"/> into a standard validation problem response.
/// </summary>
/// <param name="errors">The list of errors to convert.</param>
protected IResult ValidationProblem(List<Error> errors)
{
Dictionary<string, string[]> errorsDictionary = [];
Dictionary<string, object?> extensionsDictionary = [];
// populate the errors dictionary with error codes and their descriptions
foreach (Error error in errors)
{
if (!errorsDictionary.TryGetValue(error.Code, out string[]? value))
errorsDictionary.Add(error.Code, [error.Description]);
else
{
if (!errorsDictionary[error.Code].Contains(error.Description))
errorsDictionary[error.Code] = [.. value, error.Description];
}
}
// add trace identifier to the extensions dictionary for tracing purposes
extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
// return a validation problem result with the constructed error details
return Results.ValidationProblem(
errorsDictionary,
detail: "One or more validation errors occurred.", // TODO: implement translation?
instance: HttpContext.Request.Path,
statusCode: 422,
title: "Validation Error",
extensions: extensionsDictionary
);
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
/// <summary>
/// API endpoint for the <c>/directories/get-directories</c> route.
/// </summary>
public class GetDirectoriesEndpoint : BaseEndpoint<GetDirectoriesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetDirectoriesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Directories.GET_DIRECTORIES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the directories of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the directories.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetDirectoriesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDirectoriesEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesEndpointSummary : Summary<GetDirectoriesEndpoint, GetDirectoriesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointSummary"/> class.
/// </summary>
public GetDirectoriesEndpointSummary()
{
Summary = "Retrieves the list of directories for a specified file system path.";
Description = "Returns the directories within the specified path, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the directories.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<DirectoryResponse>>(200, "The list of directories for the specified path is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree;
/// <summary>
/// API endpoint for the <c>/directories/get-directory-tree</c> route.
/// </summary>
public class GetDirectoryTreeEndpoint : BaseEndpoint<GetDirectoryTreeRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetDirectoryTreeEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Directories.GET_DIRECTORY_TREE);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the tree of expanded directories leading up to the path stored in <paramref name="request"/>, with the additional list of drives, and children of the last child directory.
/// </summary>
/// <param name="request">The request containing the file system path for for which to get the directory tree.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetDirectoryTreeRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDirectoryTreeEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointSummary : Summary<GetDirectoryTreeEndpoint, GetDirectoryTreeRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointSummary"/> class.
/// </summary>
public GetDirectoryTreeEndpointSummary()
{
Summary = "Retrieves the directory tree structure for a specified file system path.";
Description = "Returns a hierarchical view of the directory tree, with options to include files and hidden elements.";
RequestParam(r => r.Path, "The file system path for which to get the directory tree.");
RequestParam(r => r.IncludeFiles, "Whether to include files along the directories or not.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The directory tree structure for the specified path.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories;
/// <summary>
/// API endpoint for the <c>/directories/get-tree-directories</c> route.
/// </summary>
public class GetTreeDirectoriesEndpoint : BaseEndpoint<GetTreeDirectoriesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetTreeDirectoriesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Directories.GET_TREE_DIRECTORIES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the directories of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the directories.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetTreeDirectoriesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTreeDirectoriesEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointSummary : Summary<GetTreeDirectoriesEndpoint, GetTreeDirectoriesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointSummary"/> class.
/// </summary>
public GetTreeDirectoriesEndpointSummary()
{
Summary = "Retrieves the directory tree structure for the specified file system path.";
Description = "Returns the directory tree structure, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the directory tree.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The directory tree structure is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
/// <summary>
/// API endpoint for the <c>/drives/get-drives</c> route.
/// </summary>
public class GetDrivesEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetDrivesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Drives.GET_DRIVES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the list of file system drives.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDrivesEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesEndpointSummary : Summary<GetDrivesEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesEndpointSummary"/> class.
/// </summary>
public GetDrivesEndpointSummary()
{
Summary = "Retrieves the list of file system drives.";
Description = "Returns all available drives in the file system, on Windows, or the root path, on UNIX.";
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The list of file system drives is returned.");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
/// <summary>
/// API endpoint for the <c>/file-system/get-type</c> route.
/// </summary>
public class GetTypeEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetTypeEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetTypeEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.FileSystem.GET_TYPES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the type of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
FileSystemTypeResponse platformType = await _sender.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(platformType);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTypeEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTypeEndpointSummary : Summary<GetTypeEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTypeEndpointSummary"/> class.
/// </summary>
public GetTypeEndpointSummary()
{
Summary = "Gets the type of the file system.";
Description = "Returns the type of the file system.";
Response<FileSystemTypeResponse>(200, "The file system type is returned.");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles;
/// <summary>
/// API endpoint for the <c>/files/get-files</c> route.
/// </summary>
public class GetFilesEndpoint : BaseEndpoint<GetFilesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetFilesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Files.GET_FILES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the files of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the files.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetFilesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFilesEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesEndpointSummary : Summary<GetFilesEndpoint, GetFilesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesEndpointSummary"/> class.
/// </summary>
public GetFilesEndpointSummary()
{
Summary = "Retrieves the list of files for a specified file system path.";
Description = "Returns the files within the specified path, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the files.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The list of files is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
/// <summary>
/// API endpoint for the <c>/files/get-tree-files</c> route.
/// </summary>
public class GetTreeFilesEndpoint : BaseEndpoint<GetTreeFilesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetTreeFilesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Files.GET_TREE_FILES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the files of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the files.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetTreeFilesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTreeFilesEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesEndpointSummary : Summary<GetTreeFilesEndpoint, GetTreeFilesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesEndpointSummary"/> class.
/// </summary>
public GetTreeFilesEndpointSummary()
{
Summary = "Retrieves the tree structure of files for a specified file system path.";
Description = "Returns the files within the specified path in a hierarchical tree structure, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the tree files.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The tree structure of files is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
/// <summary>
/// API endpoint for the <c>/path/check-path-exists</c> route.
/// </summary>
public class CheckPathExistsEndpoint : BaseEndpoint<CheckPathExistsRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CheckPathExistsEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.CHECK_PATH_EXISTS);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Checks the existence of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path whose existence is checked.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken)
{
PathExistsResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(result);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
/// <summary>
/// Class used for providing a textual description for the <see cref="CheckPathExistsEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsEndpointSummary : Summary<CheckPathExistsEndpoint, CheckPathExistsRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsEndpointSummary"/> class.
/// </summary>
public CheckPathExistsEndpointSummary()
{
Summary = "Checks the existence of a file system path.";
Description = "Verifies if the specified file system path exists, with an option to include hidden elements in the search.";
RequestParam(r => r.Path, "The file system path to check the exitence of.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not.");
Response<PathSegmentResponse>(200, "Indicates whether the file system path exists.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath;
/// <summary>
/// API endpoint for the <c>/path/combine</c> route.
/// </summary>
public class CombinePathEndpoint : BaseEndpoint<CombinePathRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CombinePathEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.COMBINE);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Combines the paths stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the paths to be combined.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CombinePathRequest request, CancellationToken cancellationToken)
{
ErrorOr<PathSegmentResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath;
/// <summary>
/// Class used for providing a textual description for the <see cref="CombinePathEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathEndpointSummary : Summary<CombinePathEndpoint, CombinePathRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathEndpointSummary"/> class.
/// </summary>
public CombinePathEndpointSummary()
{
Summary = "Combines two file system paths.";
Description = "Combines the specified original path with a new path to form a single file system path.";
RequestParam(r => r.OriginalPath, "The file system path to combine to.");
RequestParam(r => r.NewPath, "The file system path to combine with.");
Response<PathSegmentResponse>(200, "Successfully combined the paths.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
/// <summary>
/// API endpoint for the <c>/path/get-path-parent</c> route.
/// </summary>
public class GetPathParentEndpoint : BaseEndpoint<GetPathParentRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetPathParentEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.GET_PATH_PARENT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the parent directory of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the parent directory.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetPathParentRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathParentEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentEndpointSummary : Summary<GetPathParentEndpoint, GetPathParentRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentEndpointSummary"/> class.
/// </summary>
public GetPathParentEndpointSummary()
{
Summary = "Retrieves the parent directory of the requested file system path.";
Description = "Fetches the parent directory of a specified file system path, if available.";
RequestParam(r => r.Path, "The path for which to get the parent directory.");
Response<IEnumerable<PathSegmentResponse>>(200, "The parent directory of the requested path is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
/// <summary>
/// API endpoint for the <c>/path/get-path-root</c> route.
/// </summary>
public class GetPathRootEndpoint : BaseEndpoint<GetPathRootRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetPathRootEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.GET_PATH_ROOT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the root of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetPathRootRequest request, CancellationToken cancellationToken)
{
ErrorOr<PathSegmentResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathRootEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootEndpointSummary : Summary<GetPathRootEndpoint, GetPathRootRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootEndpointSummary"/> class.
/// </summary>
public GetPathRootEndpointSummary()
{
Summary = "Retrieves a file system path root segment.";
Description = "Fetches the root segment of a specified file system path, using the provided path parameter.";
RequestParam(r => r.Path, "The file system path for which to get the root.");
Response<PathSegmentResponse>(200, "The root of the requested path is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
/// <summary>
/// API endpoint for the <c>/path/get-path-separator</c> route.
/// </summary>
public class GetPathSeparatorEndpoint : EndpointWithoutRequest<IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetPathSeparatorEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.GET_PATH_SEPARATOR);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the file system path separator character of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CancellationToken cancellationToken)
{
PathSeparatorResponse result = await _sender.Send(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(result);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathSeparatorEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathSeparatorEndpointSummary : Summary<GetPathSeparatorEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpointSummary"/> class.
/// </summary>
public GetPathSeparatorEndpointSummary()
{
Summary = "Retrieves the file system path separator character.";
Description = "Fetches the path separator character for the current file system that the API is running on.";
Response<PathSeparatorResponse>(200, "The path separator character is returned.");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath;
/// <summary>
/// API endpoint for the <c>/path/split</c> route.
/// </summary>
public class SplitPathEndpoint : BaseEndpoint<SplitPathRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public SplitPathEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.SPLIT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the path components of a file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(SplitPathRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath;
/// <summary>
/// Class used for providing a textual description for the <see cref="SplitPathEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathEndpointSummary : Summary<SplitPathEndpoint, SplitPathRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathEndpointSummary"/> class.
/// </summary>
public SplitPathEndpointSummary()
{
Summary = "Splits a file system path.";
Description = "Splits a file system path into its constituent segments.";
RequestParam(r => r.Path, "The file system path for which to get the path segments.");
Response<IEnumerable<PathSegmentResponse>>(200, "Successfully split the path into segments.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
/// <summary>
/// API endpoint for the <c>/path/validate</c> route.
/// </summary>
public class ValidatePathEndpoint : BaseEndpoint<ValidatePathRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public ValidatePathEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.VALIDATE);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Validates the validity of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path to validate.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ValidatePathRequest request, CancellationToken cancellationToken)
{
PathValidResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(result);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
/// <summary>
/// Class used for providing a textual description for the <see cref="ValidatePathEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathEndpointSummary : Summary<ValidatePathEndpoint, ValidatePathRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathEndpointSummary"/> class.
/// </summary>
public ValidatePathEndpointSummary()
{
Summary = "Validates a file system path.";
Description = "Checks if the specified file system path is valid according to predefined criteria.";
RequestParam(r => r.Path, "The file system path to validate.");
Response<PathValidResponse>(200, "The requested path is validated.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails;
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Common.Utilities;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// API endpoint for the <c>/thumbnails/get-thumbnail</c> route.
/// </summary>
public class GetThumbnailEndpoint : BaseEndpoint<GetThumbnailRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetThumbnailEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Thumbnails.GET_THUMBNAIL);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the thumbnail of the file located at the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path of the file for which to get the thumbnail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken)
{
ErrorOr<ThumbnailResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.File(success.Bytes, MimeTypes.GetMimeType(success.Type)), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThumbnailEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailEndpointSummary : Summary<GetThumbnailEndpoint, GetThumbnailRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpointSummary"/> class.
/// </summary>
public GetThumbnailEndpointSummary()
{
Summary = "Retrieves a thumbnail for a specified file.";
Description = "Returns a thumbnail image for the specified file, with the option to specify the quality.";
RequestParam(r => r.Path, "The path of the file for which to get the thumbnail.");
RequestParam(r => r.Quality, "The quality to use for the thumbnail.");
Response(200, "The thumbnail image for the specified file is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// </summary>
public class AddBookEndpoint : BaseEndpoint<AddBookRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="AddBookEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public AddBookEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Books.ADD_BOOK);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Adds a book stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the book to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken)
{
ErrorOr<BookResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Books.ADD_BOOK}/{result.Value.Id}", result.Value), Problem);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddBookEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryEndpointSummary"/> class.
/// </summary>
public AddLibraryEndpointSummary()
{
Summary = "Adds a new book.";
Description = "Creates a new book and returns its details, including the location of the newly created resource.";
RequestParam(r => r.Metadata, "Written content metadata of the book.");
RequestParam(r => r.Metadata!.Title, "The title of the written content.");
RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
RequestParam(r => r.Edition, "The edition of the book, if applicable.");
RequestParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
RequestParam(r => r.Series, "The series name, if the book is part of a series.");
RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
RequestParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
RequestParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable.");
RequestParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable.");
RequestParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable.");
RequestParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable.");
RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
RequestParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
RequestParam(r => r.Contributors, "The list of media contributors (actors, directors, etc) starring in this book.");
RequestParam(r => r.Ratings, "The list of ratings for this book.");
ResponseParam<BookResponse>(r => r.Id, "The unique identifier of the entity.");
ResponseParam<BookResponse>(r => r.Created, "The date and time when the entity was created.");
ResponseParam<BookResponse>(r => r.Updated, "The date and time when the entity was last updated.");
ResponseParam<BookResponse>(r => r.Metadata, "The written content metadata of the book.");
ResponseParam<BookResponse>(r => r.Metadata.Title, "The title of the media item.");
ResponseParam<BookResponse>(r => r.Metadata.OriginalTitle, "The original title of the media item.");
Response<BookResponse>(201, "The book was successfully created.", "The location of the created resource is provided in the Location header.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// </summary>
public class GetBooksEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetBooksEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOKS);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the list of all books.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<BookResponse>> result = await _sender.Send(new GetBooksQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetBooksEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpointSummary"/> class.
/// </summary>
public GetBooksEndpointSummary()
{
Summary = "Retrieves the list of books.";
Description = "Returns the entire list of books.";
Response<IEnumerable<BookResponse>>(200, "The list of books is returned.");
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.GetBook;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// </summary>
public class GetBookEndpoint : BaseEndpoint<GetBookRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetBookEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetBookEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_BY_ID);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Adds a book stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the book to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken)
{
//ErrorOr<Book> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
//return result.Match(success => TypedResults.CreatedAtRoute($"/api/v1/books/{success.Id}", success), Problem);
return await Task.FromResult(TypedResults.Ok());
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Presentation.Api.Common.Routes.Library.Management;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.Management.AddLibrary;
/// <summary>
/// API endpoint for the <c>/library</c> route.
/// </summary>
public class AddLibraryEndpoint : BaseEndpoint<AddLibraryRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public AddLibraryEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Libraries.ADD_LIBRARY);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Adds a media library stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the media library to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddLibraryRequest request, CancellationToken cancellationToken)
{
ErrorOr<LibraryResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Libraries.ADD_LIBRARY}/{result.Value.Id}", result.Value), Problem);
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.Management.AddLibrary;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddLibraryEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryEndpointSummary"/> class.
/// </summary>
public AddLibraryEndpointSummary()
{
Summary = "Adds a new media library.";
Description = "Creates a new media library and returns its details, including the location of the newly created resource.";
RequestParam(r => r.UserId, "The Id of the user owning the media library.");
RequestParam(r => r.Title, "The title of the media library.");
RequestParam(r => r.LibraryType, "The type of the media library.");
RequestParam(r => r.ContentLocations, ">The file system paths of the directories where the media library elements are located.");
ResponseParam<LibraryResponse>(r => r.Id, "The unique identifier of the entity.");
ResponseParam<LibraryResponse>(r => r.UserId, "The Id of the user owning the media library.");
ResponseParam<LibraryResponse>(r => r.Title, "The title of the media library.");
ResponseParam<LibraryResponse>(r => r.LibraryType, "The type of the media library.");
ResponseParam<LibraryResponse>(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located.");
ResponseParam<LibraryResponse>(r => r.Created, "The date and time when the entity was created.");
ResponseParam<LibraryResponse>(r => r.Updated, "The date and time when the entity was last updated.");
Response<LibraryResponse>(201, "The media library was successfully created.", "The location of the created resource is provided in the Location header.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization;
using Lumina.Contracts.Responses.UsersManagement;
using Lumina.Presentation.Api.Common.Routes.Maintenance;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// API endpoint for the <c>/initialization</c> route.
/// </summary>
public class CheckInitializationEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CheckInitializationEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Initialization.CHECK_INITIALIZATION);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Checks the initialization status of the application (if the Admin account exists).
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
InitializationResponse result = await _sender.Send(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false);
return await Task.FromResult(TypedResults.Ok(result));
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.UsersManagement;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="CheckInitializationEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckInitializationEndpointSummary : Summary<CheckInitializationEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpointSummary"/> class.
/// </summary>
public CheckInitializationEndpointSummary()
{
Summary = "Checks the initialization status of the application.";
Description = "Checks the initialization status of the application (if the Admin account exists).";
Response<InitializationResponse>(200, "The application initialization status is returned.");
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Presentation.Api.Common.Routes.Maintenance;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// API endpoint for the <c>/initialization</c> route.
/// </summary>
public class SetupApplicationEndpoint : BaseEndpoint<RegistrationRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public SetupApplicationEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Initialization.SETUP_APPLICATION);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Performs the initial application setup, including creating the Admin account.
/// </summary>
/// <param name="request">The request containing the Admin user to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> result = await _sender.Send(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetupApplicationEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetupApplicationEndpointSummary : Summary<SetupApplicationEndpoint, RegistrationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpointSummary"/> class.
/// </summary>
public SetupApplicationEndpointSummary()
{
Summary = "Performs the initial application setup.";
Description = "Performs the initial application setup, including creating the Admin account.";
RequestParam(r => r.Username, "The desired username for the new account.");
RequestParam(r => r.Password, "The password for the new account.");
RequestParam(r => r.PasswordConfirm, "The confirmation of the entered password, used to ensure consistency.");
RequestParam(r => r.Use2fa, "Indicates whether two-factor authentication (2FA) should be enabled for the new account.");
Response(200, "The Admin account of the application is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement;
using Lumina.Presentation.Api.Common.Routes.Maintenance;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance;
/// <summary>
/// API endpoint for the <c>/directories/get-directories</c> route.
/// </summary>
public class CheckHealthEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CheckHealthEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CheckHealthEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Health.CHECK_HEALTH);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gwts the health status of the backend system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
// TODO: to be implemented
return await Task.FromResult(TypedResults.Ok());
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword;
/// <summary>
/// API endpoint for the <c>/auth/change-password</c> route.
/// </summary>
public class ChangePasswordEndpoint : BaseEndpoint<ChangePasswordRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public ChangePasswordEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.CHANGE_PASSWORD);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Changes the password of an account.
/// </summary>
/// <param name="request">The request containing the account for which to change the password.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ChangePasswordRequest request, CancellationToken cancellationToken)
{
ErrorOr<ChangePasswordResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="ChangePasswordEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordEndpointSummary : Summary<ChangePasswordEndpoint, ChangePasswordRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpointSummary"/> class.
/// </summary>
public ChangePasswordEndpointSummary()
{
Summary = "Changes the password of an account.";
Description = "Changes the password of an account by reseting its password, after verifying TOTP code associated with the account.";
RequestParam(r => r.CurrentPassword, "The current password of the account for which to change the password.");
RequestParam(r => r.NewPassword, "The new password of the account for which to change the password.");
RequestParam(r => r.NewPasswordConfirm, "The confirmation of the new password of the account for which to change the password.");
Response(200, "The password of the account is changed.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login;
/// <summary>
/// API endpoint for the <c>/auth/login</c> route.
/// </summary>
public class LoginEndpoint : BaseEndpoint<LoginRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public LoginEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.LOGIN_ACCOUNT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
Options(x => x.RequireRateLimiting("authenticationPolicy"));
}
/// <summary>
/// Authenticates an account.
/// </summary>
/// <param name="request">The request containing the account to be authenticated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(LoginRequest request, CancellationToken cancellationToken)
{
ErrorOr<LoginResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login;
/// <summary>
/// Class used for providing a textual description for the <see cref="LoginEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginEndpointSummary : Summary<LoginEndpoint, LoginRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpointSummary"/> class.
/// </summary>
public LoginEndpointSummary()
{
Summary = "Authenticates an account.";
Description = "Authenticates an application account.";
RequestParam(r => r.Username, "The username of the account to authenticate.");
RequestParam(r => r.Password, "The password of the account to authenticate.");
RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account to authenticate.");
Response(200, "The JWT authentication token is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
/// <summary>
/// API endpoint for the <c>/auth/recover-password</c> route.
/// </summary>
public class RecoverPasswordEndpoint : BaseEndpoint<RecoverPasswordRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public RecoverPasswordEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.RECOVER_PASSWORD);
Version(1);
AllowAnonymous();
DontCatchExceptions();
Options(x => x.RequireRateLimiting("authenticationPolicy"));
}
/// <summary>
/// Recovers the password of an account.
/// </summary>
/// <param name="request">The request containing the account for which to recover the password.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RecoverPasswordRequest request, CancellationToken cancellationToken)
{
ErrorOr<RecoverPasswordResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="RecoverPasswordEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordEndpointSummary : Summary<RecoverPasswordEndpoint, RecoverPasswordRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointSummary"/> class.
/// </summary>
public RecoverPasswordEndpointSummary()
{
Summary = "Recovers the password of an account.";
Description = "Recovers the password of an account by reseting its password, after verifying TOTP code associated with the account.";
RequestParam(r => r.Username, "The username of the account for which to recover the password.");
RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account for which to recover the password.");
Response(200, "The password of the account is reset.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
/// <summary>
/// API endpoint for the <c>/auth/register</c> route.
/// </summary>
public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public RegisterEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.REGISTER_ACCOUNT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
Options(x => x.RequireRateLimiting("authenticationPolicy"));
}
/// <summary>
/// Registers a new account.
/// </summary>
/// <param name="request">The request containing the account to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
/// <summary>
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterEndpointSummary : Summary<RegisterEndpoint, RegistrationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpointSummary"/> class.
/// </summary>
public RegisterEndpointSummary()
{
Summary = "Registers a new account.";
Description = "Registes a new application account.";
RequestParam(r => r.Username, "The desired username for the new account.");
RequestParam(r => r.Password, "The password for the new account.");
RequestParam(r => r.PasswordConfirm, "The confirmation of the entered password, used to ensure consistency.");
RequestParam(r => r.Use2fa, "Indicates whether two-factor authentication (2FA) should be enabled for the new account.");
Response(200, "The new account of the application is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
+2 -1
View File
@@ -1,5 +1,6 @@
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
RUN mkdir /logs && chown -R app:app /logs
USER app
WORKDIR /app
EXPOSE 5214
@@ -53,4 +54,4 @@ EXPOSE 5214
ENTRYPOINT ["dotnet", "Lumina.Presentation.Api.dll"]
# to build this Docker image, run the following command from the root of the project (location of the .sln file):
# docker build --no-cache -t lumina-server -f Lumina.Presentation.Api/Dockerfile .
# docker build --no-cache -t lumina-api -f Lumina.Presentation.Api/Dockerfile .
@@ -3,13 +3,14 @@
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<UserSecretsId>37d55c87-4374-4971-82e9-012fcaad1853</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<ContainerRepository>lumina-server</ContainerRepository>
<DockerfileTag>lumina-server</DockerfileTag>
<ContainerRepository>lumina-api</ContainerRepository>
<DockerfileTag>lumina-api</DockerfileTag>
<DockerComposeProjectPath>..\docker-compose.dcproj</DockerComposeProjectPath>
</PropertyGroup>
@@ -18,31 +19,34 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mapster" Version="7.4.1-pre01" />
<PackageReference Include="Mapster.DependencyInjection" Version="1.0.2-pre01" />
<PackageReference Include="FastEndpoints" Version="5.31.0.6-beta" />
<PackageReference Include="FastEndpoints.Swagger" Version="5.31.0.6-beta" />
<PackageReference Include="Mediator.Abstractions" Version="3.0.0-preview.27" />
<PackageReference Include="Mediator.SourceGenerator" Version="3.0.0-preview.27">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-rc.2.24474.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.9.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0-rc.2.24474.1">
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog" Version="4.1.1-dev-02318" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Enrichers.AspnetcoreHttpcontext" Version="1.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.Development.json">
<None Update="appsettings.development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DependentUpon>appsettings.shared.json</DependentUpon>
<DependentUpon>appsettings.json</DependentUpon>
</None>
</ItemGroup>
@@ -53,7 +57,7 @@
<ProjectReference Include="..\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
<ProjectReference Include="..\Lumina.DataAccess\Lumina.DataAccess.csproj" />
</ItemGroup>
<!--disable warnings generated by Mediator source generator-->
<PropertyGroup>
<NoWarn>$(NoWarn);CS0436</NoWarn>
+81 -11
View File
@@ -1,11 +1,22 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Application.Common.DependencyInjection;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.DependencyInjection;
using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Serilog;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
#endregion
@@ -14,6 +25,7 @@ namespace Lumina.Presentation.Api;
/// <summary>
/// Application entry point, contains the composition root module, wires up all dependencies of the application.
/// </summary>
[ExcludeFromCodeCoverage]
public class Program
{
/// <summary>
@@ -27,28 +39,86 @@ public class Program
builder.Services.BindSharedConfiguration(builder.Configuration);
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
builder.Services.AddPresentationApiLayerServices();
builder.Services.AddPresentationApiLayerServices(builder.Configuration);
builder.Services.AddApplicationLayerServices();
builder.Services.AddInfrastructureLayerServices();
builder.Services.AddDataAccessLayerServices();
builder.Services.AddDomainLayerServices();
// determine log path based on environment
string logPath;
if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true")
{
logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5214); // HTTP only
});
}
else
logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path
Directory.CreateDirectory(logPath);
if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
logPath = logPath += Path.DirectorySeparatorChar;
// set environment variable for Serilog configuration
Environment.SetEnvironmentVariable("LOG_PATH", logPath);
builder.Host.UseSerilog((context, services, configuration) =>
{
configuration.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext();
});
WebApplication app = builder.Build();
app.UseSerilogRequestLogging();
// apply any pending migrations
using (IServiceScope scope = app.Services.CreateScope())
{
IServiceProvider services = scope.ServiceProvider;
try
{
LuminaDbContext context = services.GetRequiredService<LuminaDbContext>();
await context.Database.MigrateAsync();
}
catch (Exception ex)
{
ILogger logger = services.GetRequiredService<ILogger>();
logger.Fatal(ex, "Failed to run database migrations");
}
}
app.UseCors("AllowAll");
app.UseExceptionHandler("/error"); // uses a middleware which reexecutes the request to the error path
// configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseExceptionHandler("/error"); // uses a middleware which re-executes the request to the error path
//app.UseHttpsRedirection();
app.MapControllers();
app.UseAuthorization();
app.UseRateLimiter();
app.UseFastEndpoints(config =>
{
config.Endpoints.RoutePrefix = "api";
config.Versioning.Prefix = "v";
config.Versioning.DefaultVersion = 1;
config.Versioning.PrependToRoute = true;
config.Endpoints.ShortNames = true;
});
app.UseSwaggerGen();
string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting);
if (!Directory.Exists(mediaRootPath))
Directory.CreateDirectory(mediaRootPath);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(mediaRootPath),
RequestPath = "/media"
});
await app.RunAsync().ConfigureAwait(false);
}
@@ -17,16 +17,7 @@
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7057;http://localhost:5214"
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_HTTP_PORTS": "5214"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json"
}
}
+52 -18
View File
@@ -1,21 +1,55 @@
{
"Serilog": {
"WriteTo": [
{
"Name": "Debug"
},
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "Logs/lumina_api_.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
"JwtSettings": {
"SecretKey": "",
"ExpiryMinutes": 60,
"Issuer": "Lumina",
"Audience": "Lumina"
},
"EncryptionSettings": {
"SecretKey": "" // base64 string
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "%LOG_PATH%lumina_api_.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"retainedFileCountLimit": 7,
"fileSizeLimitBytes": 10485760,
"rollOnFileSizeLimit": true,
"shared": true,
"flushToDiskInterval": "00:00:01"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId",
"WithEnvironmentName"
],
"Properties": {
"Application": "LuminaApi"
}
}
]
},
"AllowedHosts": "*"
},
"AllowedHosts": "*"
}