Adds book reading support with EPUB and PDF reader plugins

This commit is contained in:
BinaryAlley committed 2026-09-02 04:45:11 -07:00
1 parent 275fd83ff2
commit f7ccdf3d1c
271 files changed
+11501 -361

No files matched your search

@@ -25,23 +25,23 @@ using System.Threading.RateLimiting;
namespace Lumina.Presentation.Api.Common.DependencyInjection;
/// <summary>
/// Contains all services of the Presentation API layer.
/// Utility class for registering the services of the Presentation Api layer into the Dependency Injection container.
/// </summary>
[ExcludeFromCodeCoverage]
public static class PresentationApiLayerServices
{
/// <summary>
/// Registers the services of the Presentation API layer into the dependency injection container.
/// 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>
/// <param name="configuration">The configuration used to read the application configuration.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting
services.AddMemoryCache(); // Used for the tracking involved in authentication rate limiting.
services.AddProblemDetails();
// the readiness health check verifies that the database can be reached, and is probed by container orchestrators and load balancers
// The readiness health check verifies that the database can be reached, and is probed by container orchestrators and load balancers.
services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("database", HealthStatus.Unhealthy, ["ready"]);
@@ -49,10 +49,10 @@ public static class PresentationApiLayerServices
{
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
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
// TODO: also implement account locking after a number of failed login attempts.
services.AddRateLimiter(rateLimiterOptions =>
{
rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
@@ -68,16 +68,16 @@ public static class PresentationApiLayerServices
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
clientIp,
onRejectedContext.HttpContext.Request.Path,
onRejectedContext.Lease.IsAcquired); // when False, the request was rejected because it exceeded rate limits
onRejectedContext.Lease.IsAcquired); // When False, the request was rejected because it exceeded rate limits.
onRejectedContext.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
onRejectedContext.HttpContext.Response.ContentType = "application/problem+json";
// set standard rate limit headers
// Set standard rate limit headers.
if (onRejectedContext.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
onRejectedContext.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
// set custom rate limit headers
// Set custom rate limit headers.
onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Limit"] = "10";
onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0";
onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Reset"] = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds().ToString();
@@ -95,23 +95,23 @@ public static class PresentationApiLayerServices
};
rateLimiterOptions.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
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
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
// Add authentication and specify the JWT scheme to check tokens against.
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwtBearerOptions =>
{
@@ -128,10 +128,10 @@ public static class PresentationApiLayerServices
jwtBearerOptions.Events = new JwtBearerEvents
{
OnChallenge = jwtBearerChallengeContext => // event triggered when authentication is not successful for whatever reason
OnChallenge = jwtBearerChallengeContext => // Event triggered when authentication is not successful for whatever reason.
{
jwtBearerChallengeContext.HandleResponse(); // prevent the default 401 response
// set the response status code to 401 Unauthorized
jwtBearerChallengeContext.HandleResponse(); // Prevent the default 401 response.
// Set the response status code to 401 Unauthorized.
jwtBearerChallengeContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
jwtBearerChallengeContext.Response.ContentType = "application/problem+json";
@@ -139,7 +139,7 @@ public static class PresentationApiLayerServices
if (!string.IsNullOrEmpty(jwtBearerChallengeContext.Error))
{
errorDetails = jwtBearerChallengeContext.Error switch
{ // TODO: implement translation
{ // TODO: implement translation.
"invalid_token" => !string.IsNullOrEmpty(jwtBearerChallengeContext.ErrorDescription)
? $"Invalid token: {jwtBearerChallengeContext.ErrorDescription}"
: "The token is invalid",
@@ -174,9 +174,8 @@ public static class PresentationApiLayerServices
services.AddFastEndpoints(endpointDiscoveryOptions =>
{
endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ];
// only scan the application assembly, so that duplicate copies of it loaded into other assembly load
// contexts during the process lifetime are never scanned again; otherwise a single host can register
// every endpoint multiple times and fail with duplicate routes
// Only scan the application assembly, so that duplicate copies of it loaded into other assembly load contexts during the process lifetime are never scanned again;
// otherwise a single host can register every endpoint multiple times and fail with duplicate routes.
endpointDiscoveryOptions.DisableAutoDiscovery = true;
});
@@ -200,7 +199,7 @@ public static class PresentationApiLayerServices
};
documentOptions.RemoveEmptyRequestSchema = true;
documentOptions.ShortSchemaNames = true;
}); // for an eventual next version:
}); // For an eventual next version:
//.SwaggerDocument(documentOptions =>
//{
// documentOptions.MaxEndpointVersion = 2;
@@ -16,7 +16,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Common.DependencyInjection;
/// <summary>
/// Contains the OpenTelemetry services of the Presentation API layer.
/// Utility class for registering the OpenTelemetry services of the Presentation Api layer into the Dependency Injection container.
/// </summary>
[ExcludeFromCodeCoverage]
public static class PresentationApiTelemetryServices
@@ -25,10 +25,10 @@ public static class PresentationApiTelemetryServices
private const string ENTITY_FRAMEWORK_CORE_METER_NAME = "Microsoft.EntityFrameworkCore";
/// <summary>
/// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container.
/// Registers the OpenTelemetry 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>
/// <param name="configuration">The configuration used to read the application configuration.</param>
/// <param name="environment">The hosting environment of the application.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
@@ -28,5 +28,7 @@ public static partial class ApiRoutes
public const string GET_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers";
public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "/libraries/{libraryId}/artwork-providers/{pluginId}/enabled";
public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers/reorder";
public const string GET_LIBRARY_BOOK_READERS = "/libraries/{libraryId}/book-readers";
public const string SET_LIBRARY_BOOK_READER_ENABLED = "/libraries/{libraryId}/book-readers/{pluginId}/enabled";
}
}
@@ -14,5 +14,9 @@ public static partial class ApiRoutes
public const string GET_BOOKS = "/books";
public const string GET_BOOKS_LITE = "/books/lite";
public const string ADD_BOOK = "/books";
public const string GET_BOOK_READING_MANIFEST = "/books/{bookId}/reading/manifest";
public const string GET_BOOK_READING_AVAILABILITY = "/books/{bookId}/reading/availability";
public const string GET_BOOK_READING_SECTION = "/books/{bookId}/reading/sections/{locationRef}";
public const string GET_BOOK_READING_RESOURCE = "/books/{bookId}/reading/resources/{resourceKey}";
}
}
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
@@ -2,7 +2,7 @@
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -2,7 +2,7 @@
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
/// <summary>
/// API endpoint for the <c>/books/{bookId}/reading/availability</c> route.
/// </summary>
public class GetReadingAvailabilityEndpoint : BaseEndpoint<GetReadingAvailabilityRequest, IResult>
{
private readonly IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>> _getReadingAvailabilityQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpoint"/> class.
/// </summary>
/// <param name="getReadingAvailabilityQueryHandler">Injected service for handling get reading availability queries.</param>
public GetReadingAvailabilityEndpoint(IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>> getReadingAvailabilityQueryHandler)
{
_getReadingAvailabilityQueryHandler = getReadingAvailabilityQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Checks the reading availability of the book identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the Id of the book whose reading availability is checked.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetReadingAvailabilityRequest request, CancellationToken cancellationToken)
{
Result<ReadingAvailabilityResponse> result = await _getReadingAvailabilityQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetReadingAvailabilityEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityEndpointSummary : Summary<GetReadingAvailabilityEndpoint, GetReadingAvailabilityRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointSummary"/> class.
/// </summary>
public GetReadingAvailabilityEndpointSummary()
{
Summary = "Checks the reading availability of a book.";
Description = "Checks whether the book can be opened for reading, resolving the book reader configured for its media library and verifying that the reader is enabled, without extracting the book.";
ExampleRequest = new GetReadingAvailabilityRequest(
BookId: Guid.NewGuid()
);
RequestParam(r => r.BookId, "The Id of the book whose reading availability is checked. Required.");
ResponseParam<ReadingAvailabilityResponse>(r => r.BookId, "The Id of the book whose reading availability is reported.");
ResponseParam<ReadingAvailabilityResponse>(r => r.LibraryId, "The Id of the media library the book belongs to.");
ResponseParam<ReadingAvailabilityResponse>(r => r.IsAvailable, "Whether the book can be opened for reading.");
ResponseParam<ReadingAvailabilityResponse>(r => r.ErrorCode, "The code of the error preventing the book from being read, when it cannot be read. Can be null when the book is available.");
Response(200, "The reading availability of the book is returned.",
example: new ReadingAvailabilityResponse(
BookId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
IsAvailable: false,
ErrorCode: "ReaderDisabled"
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books/{bookId}/reading/availability"
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books/{bookId}/reading/availability",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the book does not exist.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "BookNotFound",
instance = "/api/v1/books/{bookId}/reading/availability",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/{bookId}/reading/availability",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"BookIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
/// <summary>
/// API endpoint for the <c>/books/{bookId}/reading/manifest</c> route.
/// </summary>
public class GetReadingManifestEndpoint : BaseEndpoint<GetReadingManifestRequest, IResult>
{
private readonly IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>> _getReadingManifestQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingManifestEndpoint"/> class.
/// </summary>
/// <param name="getReadingManifestQueryHandler">Injected service for handling get reading manifest queries.</param>
public GetReadingManifestEndpoint(IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>> getReadingManifestQueryHandler)
{
_getReadingManifestQueryHandler = getReadingManifestQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_READING_MANIFEST);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the reading manifest of the book identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the Id of the book whose reading manifest is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetReadingManifestRequest request, CancellationToken cancellationToken)
{
Result<ReadingManifestResponse> result = await _getReadingManifestQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetReadingManifestEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestEndpointSummary : Summary<GetReadingManifestEndpoint, GetReadingManifestRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingManifestEndpointSummary"/> class.
/// </summary>
public GetReadingManifestEndpointSummary()
{
Summary = "Retrieves the reading manifest of a book.";
Description = "Retrieves the reading manifest of a book, containing the metadata, the table of contents, the spine, and the resources needed to render the reader.";
ExampleRequest = new GetReadingManifestRequest(
BookId: Guid.NewGuid()
);
RequestParam(r => r.BookId, "The Id of the book whose reading manifest is retrieved. Required.");
ResponseParam<ReadingManifestResponse>(r => r.Title, "The title of the book.");
ResponseParam<ReadingManifestResponse>(r => r.Author, "The author of the book, if known.");
ResponseParam<ReadingManifestResponse>(r => r.CoverResourceKey, "The resource key of the cover image of the book, if applicable.");
ResponseParam<ReadingManifestResponse>(r => r.Spine, "The ordered spine of the reading sections of the book.");
ResponseParam<ReadingManifestResponse>(r => r.ResourceKeys, "The resource keys of the resources of the book.");
ResponseParam<ReadingManifestResponse>(r => r.HasTextContent, "Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content.");
Response(200, "The reading manifest of the book is returned.",
example: new ReadingManifestResponse(
Title: "The Fellowship of the Ring",
Author: "J.R.R. Tolkien",
CoverResourceKey: "cover-image",
TableOfContents:
[
new ReadingTocEntryResponse(
Label: "Chapter 1",
LocationRef: "chapter-1",
Children: []
)
],
Spine:
[
new ReadingSpineItemResponse(
LocationRef: "chapter-1",
Title: "Chapter 1"
)
],
ResourceKeys: ["cover-image"],
HasTextContent: true
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books/{bookId}/reading/manifest"
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books/{bookId}/reading/manifest",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the book does not exist, no reader plugin supports its format, or the reader plugin is disabled.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "ReaderDisabled",
instance = "/api/v1/books/{bookId}/reading/manifest",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/{bookId}/reading/manifest",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"BookIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
/// <summary>
/// API endpoint for the <c>/books/{bookId}/reading/resources/{resourceKey}</c> route.
/// </summary>
public class GetReadingResourceEndpoint : BaseEndpoint<GetReadingResourceRequest, IResult>
{
private readonly IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>> _getReadingResourceQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingResourceEndpoint"/> class.
/// </summary>
/// <param name="getReadingResourceQueryHandler">Injected service for handling get reading resource queries.</param>
public GetReadingResourceEndpoint(IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>> getReadingResourceQueryHandler)
{
_getReadingResourceQueryHandler = getReadingResourceQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_READING_RESOURCE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the resource of the book identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the Id of the book and the resource key of the resource.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetReadingResourceRequest request, CancellationToken cancellationToken)
{
Result<ReadingResourceDataDto> result = await _getReadingResourceQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
if (result.IsFailure)
return Problem(result.Errors);
// The media type of a resource is declared by the book itself, so it is not trusted: a resource whose declared media type could be
// rendered as an active document (for example an SVG) is served as an opaque binary download instead, and every resource is served
// with content sniffing disabled, so that the browser never executes book content as anything but what this endpoint declares.
HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff";
return TypedResults.Bytes(result.Value.Data, GetSafeContentType(result.Value.MimeType));
}
/// <summary>
/// Gets the safe content type of a book resource, replacing the media types that could be rendered as active documents with an opaque binary type.
/// </summary>
/// <param name="mediaType">The media type declared by the book.</param>
/// <returns>The safe content type the resource is served with.</returns>
private static string GetSafeContentType(string mediaType)
{
// Images, audio, video, fonts, and stylesheets are inert content the reader can render; everything else (an SVG, an XML or HTML
// document, a script) is served as an opaque download, so that opening a resource URL never executes active content.
if (mediaType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) && !string.Equals(mediaType, "image/svg+xml", StringComparison.OrdinalIgnoreCase))
return mediaType;
if (mediaType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || mediaType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
return mediaType;
if (mediaType.StartsWith("font/", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mediaType, "application/font-woff", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mediaType, "application/font-woff2", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mediaType, "application/vnd.ms-opentype", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mediaType, "application/x-font-ttf", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mediaType, "application/x-font-opentype", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mediaType, "text/css", StringComparison.OrdinalIgnoreCase))
return mediaType;
return "application/octet-stream";
}
}
@@ -0,0 +1,92 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetReadingResourceEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceEndpointSummary : Summary<GetReadingResourceEndpoint, GetReadingResourceRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingResourceEndpointSummary"/> class.
/// </summary>
public GetReadingResourceEndpointSummary()
{
Summary = "Retrieves a resource of a book, for reading.";
Description = "Retrieves the binary content of a resource of a book, such as an image or a font referenced by a reading section.";
ExampleRequest = new GetReadingResourceRequest(
BookId: Guid.NewGuid(),
ResourceKey: "cover-image"
);
RequestParam(r => r.BookId, "The Id of the book whose resource is retrieved. Required.");
RequestParam(r => r.ResourceKey, "The opaque resource key of the resource. Required.");
Response(200, "The resource of the book is returned.");
Response(401, "Authentication required.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}"
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the book does not exist, no reader plugin supports its format, the reader plugin is disabled, or the resource was not found.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "ResourceNotFound",
instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"BookIdCannotBeEmpty",
"ResourceKeyCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
/// <summary>
/// API endpoint for the <c>/books/{bookId}/reading/sections/{locationRef}</c> route.
/// </summary>
public class GetReadingSectionEndpoint : BaseEndpoint<GetReadingSectionRequest, IResult>
{
private readonly IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>> _getReadingSectionQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingSectionEndpoint"/> class.
/// </summary>
/// <param name="getReadingSectionQueryHandler">Injected service for handling get reading section queries.</param>
public GetReadingSectionEndpoint(IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>> getReadingSectionQueryHandler)
{
_getReadingSectionQueryHandler = getReadingSectionQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_READING_SECTION);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the content of the reading section of the book identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the Id of the book and the location reference of the reading section.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetReadingSectionRequest request, CancellationToken cancellationToken)
{
Result<ReadingSectionDto> result = await _getReadingSectionQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetReadingSectionEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionEndpointSummary : Summary<GetReadingSectionEndpoint, GetReadingSectionRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingSectionEndpointSummary"/> class.
/// </summary>
public GetReadingSectionEndpointSummary()
{
Summary = "Retrieves the content of a reading section of a book.";
Description = "Retrieves the sanitized HTML content of the reading section of a book, ready to be rendered by the client.";
ExampleRequest = new GetReadingSectionRequest(
BookId: Guid.NewGuid(),
LocationRef: "chapter-1"
);
RequestParam(r => r.BookId, "The Id of the book whose reading section is retrieved. Required.");
RequestParam(r => r.LocationRef, "The opaque location reference of the reading section. Required.");
ResponseParam<ReadingSectionDto>(r => r.LocationRef, "The opaque location reference of the reading section.");
ResponseParam<ReadingSectionDto>(r => r.Title, "The title of the reading section, if known.");
ResponseParam<ReadingSectionDto>(r => r.ContentHtml, "The sanitized HTML content of the reading section.");
Response(200, "The content of the reading section is returned.",
example: new ReadingSectionDto(
LocationRef: "chapter-1",
Title: "Chapter 1",
ContentHtml: "<h1>Chapter 1</h1><p>A long journey begins...</p>"
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}"
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the book does not exist, no reader plugin supports its format, the reader plugin is disabled, or the reading section was not found.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "SectionNotFound",
instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"BookIdCannotBeEmpty",
"LocationRefCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.Management;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryBookReaders;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/book-readers</c> route.
/// </summary>
public class GetLibraryBookReadersEndpoint : BaseEndpoint<GetLibraryBookReadersRequest, IResult>
{
private readonly IQueryHandler<GetLibraryBookReadersQuery, Result<IReadOnlyList<LibraryBookReaderResponse>>> _getLibraryBookReadersQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryBookReadersEndpoint"/> class.
/// </summary>
/// <param name="getLibraryBookReadersQueryHandler">Injected service for handling get library book readers queries.</param>
public GetLibraryBookReadersEndpoint(IQueryHandler<GetLibraryBookReadersQuery, Result<IReadOnlyList<LibraryBookReaderResponse>>> getLibraryBookReadersQueryHandler)
{
_getLibraryBookReadersQueryHandler = getLibraryBookReadersQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the book readers configured for the media library identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the Id of the media library whose book readers are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetLibraryBookReadersRequest request, CancellationToken cancellationToken)
{
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _getLibraryBookReadersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Contracts.Responses.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryBookReaders;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetLibraryBookReadersEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryBookReadersEndpointSummary : Summary<GetLibraryBookReadersEndpoint, GetLibraryBookReadersRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryBookReadersEndpointSummary"/> class.
/// </summary>
public GetLibraryBookReadersEndpointSummary()
{
Summary = "Retrieves the book readers configured for a media library.";
Description = "Retrieves the book readers configured for a media library, with their supported file extensions and enabled state.";
ExampleRequest = new GetLibraryBookReadersRequest(
LibraryId: Guid.NewGuid()
);
RequestParam(r => r.LibraryId, "The Id of the media library whose book readers are retrieved. Required.");
ResponseParam<LibraryBookReaderResponse>(r => r.PluginId, "The unique identifier of the plugin providing the book reader.");
ResponseParam<LibraryBookReaderResponse>(r => r.Name, "The display name of the book reader.");
ResponseParam<LibraryBookReaderResponse>(r => r.SupportedExtensions, "The file extensions supported by the book reader.");
ResponseParam<LibraryBookReaderResponse>(r => r.IsEnabled, "Whether the book reader is enabled for the media library.");
Response(200, "The book readers configured for the media library are returned.",
example: new LibraryBookReaderResponse[] {
new(
PluginId: Guid.NewGuid(),
Name: "EPUB Reader",
SupportedExtensions: [".epub"],
IsEnabled: true
),
new(
PluginId: Guid.NewGuid(),
Name: "PDF Reader",
SupportedExtensions: [".pdf"],
IsEnabled: false
)
}
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/libraries/{libraryId}/book-readers"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/{libraryId}/book-readers",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the requested media library does not exist.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = "/api/v1/libraries/{libraryId}/book-readers",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/libraries/{libraryId}/book-readers",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.Management;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/book-readers/{pluginId}/enabled</c> route.
/// </summary>
public class SetLibraryBookReaderEnabledEndpoint : BaseEndpoint<SetLibraryBookReaderEnabledRequest, IResult>
{
private readonly ICommandHandler<SetLibraryBookReaderEnabledCommand, Result<Success>> _setLibraryBookReaderEnabledCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledEndpoint"/> class.
/// </summary>
/// <param name="setLibraryBookReaderEnabledCommandHandler">Injected service for handling set library book reader enabled commands.</param>
public SetLibraryBookReaderEnabledEndpoint(ICommandHandler<SetLibraryBookReaderEnabledCommand, Result<Success>> setLibraryBookReaderEnabledCommandHandler)
{
_setLibraryBookReaderEnabledCommandHandler = setLibraryBookReaderEnabledCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Enables or disables the book reader identified by <paramref name="request"/> for the media library.
/// </summary>
/// <param name="request">The request containing the Ids of the media library and of the book reader.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(SetLibraryBookReaderEnabledRequest request, CancellationToken cancellationToken)
{
Result<Success> result = await _setLibraryBookReaderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,99 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetLibraryBookReaderEnabledEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledEndpointSummary : Summary<SetLibraryBookReaderEnabledEndpoint, SetLibraryBookReaderEnabledRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledEndpointSummary"/> class.
/// </summary>
public SetLibraryBookReaderEnabledEndpointSummary()
{
Summary = "Enables or disables a book reader for a media library.";
Description = "Enables or disables the book reader of the media library identified by the request.";
ExampleRequest = new SetLibraryBookReaderEnabledRequest(
LibraryId: Guid.NewGuid(),
PluginId: Guid.NewGuid(),
IsEnabled: true
);
RequestParam(r => r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required.");
RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required.");
RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library. Required.");
Response(200, "The book reader of the media library is enabled or disabled.",
example: new
{
success = true
}
);
Response(401, "Authentication required.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled"
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the requested media library does not exist.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"PluginIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -28,7 +28,9 @@ public class GetUserSettingsEndpointSummary : Summary<GetUserSettingsEndpoint, E
ItemsPerPage: 48,
ShouldIgnoreThePrefixForAlphaPicker: false,
IsThemeCachingEnabled: true,
ShouldAggregateMetadataWhenMissing: false
ShouldAggregateMetadataWhenMissing: false,
ShouldRenderPdfAsImages: false,
ShouldPreserveBookStyles: true
));
Response(401, "Authentication required.", "application/problem+json",
@@ -26,13 +26,17 @@ public class UpdateUserSettingsEndpointSummary : Summary<UpdateUserSettingsEndpo
ItemsPerPage: 48,
ShouldIgnoreThePrefixForAlphaPicker: false,
IsThemeCachingEnabled: true,
ShouldAggregateMetadataWhenMissing: false
ShouldAggregateMetadataWhenMissing: false,
ShouldRenderPdfAsImages: false,
ShouldPreserveBookStyles: true
);
RequestParam(r => r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required.");
RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Required.");
RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required.");
RequestParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not. Required.");
RequestParam(r => r.ShouldRenderPdfAsImages, "Whether PDF books are rendered as page images for the user, or not. Required.");
RequestParam(r => r.ShouldPreserveBookStyles, "Whether the styles of the book content are preserved when it is rendered for the user, or not. Required.");
Response(200, "The settings of the current user were successfully updated.");
+23 -16
View File
@@ -8,6 +8,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Presentation.Api.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.Middlewares;
using Lumina.Presentation.Api.Common.Utilities;
@@ -57,22 +58,22 @@ public class Program
builder.Services.AddDataAccessLayerServices();
builder.Services.AddDomainLayerServices();
// determine log path based on environment
// 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
logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // Use docker volume path.
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5214); // HTTP only; also, the port is also the same port exposed in the Dockerfile
options.ListenAnyIP(5214); // HTTP only; also, the port is also the same port exposed in the Dockerfile.
});
}
else
logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path
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
// Set environment variable for Serilog configuration.
Environment.SetEnvironmentVariable("LOG_PATH", logPath);
builder.Host.UseSerilog((context, services, configuration) =>
@@ -85,7 +86,7 @@ public class Program
app.UseSerilogRequestLogging();
// apply any pending migrations
// Apply any pending migrations.
using (IServiceScope scope = app.Services.CreateScope())
{
IServiceProvider services = scope.ServiceProvider;
@@ -94,8 +95,8 @@ public class Program
LuminaDbContext context = services.GetRequiredService<LuminaDbContext>();
await context.Database.MigrateAsync();
// enable the Write-Ahead Logging journal mode and a busy timeout, so that the Entity Framework connection and the dedicated connections
// used by the bulk data access operations of Dapper can access the database concurrently, without database locking errors
// Enable the Write-Ahead Logging journal mode and a busy timeout, so that the Entity Framework connection and the dedicated connections
// used by the bulk data access operations of Dapper can access the database concurrently, without database locking errors.
SqliteConnection sqliteConnection = new(context.Database.GetDbConnection().ConnectionString);
sqliteConnection.Open();
using SqliteCommand sqliteCommand = sqliteConnection.CreateCommand();
@@ -113,7 +114,7 @@ public class Program
app.UseRouting();
app.UseCors("SecurePolicy");
app.UseApiExceptionHandling(); // catches any unhandled exception and returns a ProblemDetails response
app.UseApiExceptionHandling(); // Catches any unhandled exception and returns a ProblemDetails response.
//app.UseHttpsRedirection();
@@ -130,7 +131,7 @@ public class Program
config.Endpoints.ShortNames = true;
});
// add API documentation (OpenApi/Scalar)
// Add API documentation (OpenApi/Scalar).
app.MapOpenApi();
app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); // this is needed for API versioning to work correctly with Scalar
app.MapScalarApiReference(scalarOptions =>
@@ -138,22 +139,28 @@ public class Program
scalarOptions.WithTitle("Lumina API")
.WithTheme(ScalarTheme.BluePlanet)
.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
//.WithFavicon() // TODO: enable when favicon is added
//.WithFavicon() // TODO: enable when favicon is added.
.WithDotNetFlag(true);
});
// add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked,
// and NOT for the health probes, which would otherwise begin a database transaction on every probe
// Add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked,
// and NOT for the health probes, which would otherwise begin a database transaction on every probe.
app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware<EventualConsistencyMiddleware>());
// create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API
// Create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API.
string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting);
if (!Directory.Exists(mediaRootPath))
Directory.CreateDirectory(mediaRootPath);
// ensure the default file system structure is present
// Wipe the temporary directory, so that it cannot grow across restarts.
string readingCachePath = ReadingCachePaths.GetRootDirectory();
if (Directory.Exists(readingCachePath))
Directory.Delete(readingCachePath, recursive: true);
Directory.CreateDirectory(readingCachePath);
// Ensure the default file system structure is present.
using (IServiceScope scope = app.Services.CreateScope())
{
IServiceProvider services = scope.ServiceProvider;
@@ -177,7 +184,7 @@ public class Program
app.MapHub<MediaLibraryScanProgressHub>("/scanProgressHub");
// the liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable
// The liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable.
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = _ => false,