diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ClearResumePointsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ClearResumePointsRequestMapping.cs
new file mode 100644
index 00000000..fc4788e3
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ClearResumePointsRequestMapping.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class ClearResumePointsRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the user whose resume points are deleted, taken from the route, or for the current user.
+ /// The converted command.
+ public static ClearResumePointsCommand ToCommand(this ClearResumePointsRequest request, string? targetUserId)
+ {
+ return new ClearResumePointsCommand(
+ targetUserId,
+ request.LibraryId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMapping.cs
new file mode 100644
index 00000000..5b3dbec6
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMapping.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class GetAllUsersConsumptionStatisticsRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted query.
+ public static GetAllUsersConsumptionStatisticsQuery ToQuery(this GetAllUsersConsumptionStatisticsRequest request)
+ {
+ return new GetAllUsersConsumptionStatisticsQuery(
+ request.LibraryId,
+ request.MediaKind,
+ request.FromUtc,
+ request.ToUtc
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMapping.cs
new file mode 100644
index 00000000..8413faa3
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMapping.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class GetConsumptionStatisticsRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the user whose statistics are retrieved, taken from the route, or for the current user.
+ /// The converted query.
+ public static GetConsumptionStatisticsQuery ToQuery(this GetConsumptionStatisticsRequest request, string? targetUserId)
+ {
+ return new GetConsumptionStatisticsQuery(
+ targetUserId,
+ request.LibraryId,
+ request.MediaKind,
+ request.FromUtc,
+ request.ToUtc
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs
new file mode 100644
index 00000000..4013f809
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class GetMostConsumedRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the user whose history is retrieved, taken from the route, or for the current user.
+ /// The converted query.
+ public static GetMostConsumedQuery ToQuery(this GetMostConsumedRequest request, string? targetUserId)
+ {
+ PaginationDataDto? paginationData = null;
+ if (request.CurrentPage is not null || request.PerPage is not null)
+ paginationData = new PaginationDataDto
+ {
+ CurrentPage = request.CurrentPage ?? 1,
+ PerPage = request.PerPage ?? 50
+ };
+
+ return new GetMostConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, paginationData);
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs
new file mode 100644
index 00000000..a73c82ac
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class GetRecentlyConsumedRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the user whose history is retrieved, taken from the route, or for the current user.
+ /// The converted query.
+ public static GetRecentlyConsumedQuery ToQuery(this GetRecentlyConsumedRequest request, string? targetUserId)
+ {
+ PaginationDataDto? paginationData = null;
+ if (request.CurrentPage is not null || request.PerPage is not null)
+ paginationData = new PaginationDataDto
+ {
+ CurrentPage = request.CurrentPage ?? 1,
+ PerPage = request.PerPage ?? 50
+ };
+
+ return new GetRecentlyConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, paginationData);
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs
new file mode 100644
index 00000000..d0bf4ce1
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class GetTagConsumptionRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the user whose statistics are retrieved, taken from the route, or for the current user.
+ /// The converted query.
+ public static GetTagConsumptionQuery ToQuery(this GetTagConsumptionRequest request, string? targetUserId)
+ {
+ return new GetTagConsumptionQuery(
+ targetUserId,
+ request.LibraryId,
+ request.MediaKind,
+ request.TagKind,
+ request.FromUtc,
+ request.ToUtc
+ );
+ }
+}
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/ClearResumePointsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/ClearResumePointsRequest.cs
new file mode 100644
index 00000000..596db58c
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/ClearResumePointsRequest.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request to delete the resume points of a user.
+///
+/// The Id of the media library to restrict the deletion to. Optional.
+[DebuggerDisplay("LibraryId: {LibraryId}")]
+public sealed record ClearResumePointsRequest(
+ string? LibraryId
+);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs
new file mode 100644
index 00000000..760da069
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request for getting the consumption statistics of every user.
+///
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
+public sealed record GetAllUsersConsumptionStatisticsRequest(
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs
new file mode 100644
index 00000000..58817188
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request for getting the consumption statistics of a user.
+///
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
+public sealed record GetConsumptionStatisticsRequest(
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs
new file mode 100644
index 00000000..24c85867
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs
@@ -0,0 +1,21 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request for getting a window of the most consumed media items of a user.
+///
+/// The Id of the media library to restrict the history to. Optional.
+/// The kind of media to restrict the history to. Optional.
+/// The one based page of media items to return. Optional.
+/// The number of media items per page. Optional.
+[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
+public sealed record GetMostConsumedRequest(
+ string? LibraryId,
+ MediaKind? MediaKind,
+ int? CurrentPage,
+ int? PerPage
+);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs
new file mode 100644
index 00000000..273a9897
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs
@@ -0,0 +1,21 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request for getting a window of the recently consumed media items of a user.
+///
+/// The Id of the media library to restrict the history to. Optional.
+/// The kind of media to restrict the history to. Optional.
+/// The one based page of media items to return. Optional.
+/// The number of media items per page. Optional.
+[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
+public sealed record GetRecentlyConsumedRequest(
+ string? LibraryId,
+ MediaKind? MediaKind,
+ int? CurrentPage,
+ int? PerPage
+);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs
new file mode 100644
index 00000000..dc4e93ab
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request for getting the consumption statistics of the tags and genres of a user.
+///
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// Whether to return genres or tags. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("MediaKind: {MediaKind}; TagKind: {TagKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
+public sealed record GetTagConsumptionRequest(
+ string? LibraryId,
+ MediaKind? MediaKind,
+ TagKind? TagKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs
new file mode 100644
index 00000000..9879ddf9
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs
@@ -0,0 +1,29 @@
+namespace Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+
+///
+/// Class for the collection of the library statistics routes of the API.
+///
+public static partial class ApiRoutes
+{
+ ///
+ /// Routes for the consumption history, consumption statistics, and resume points of the current user, of another user, and of every user.
+ ///
+ public static class LibraryStatistics
+ {
+ public const string GET_RECENTLY_CONSUMED = "/users/me/consumption-history/recently-consumed";
+ public const string GET_MOST_CONSUMED = "/users/me/consumption-history/most-consumed";
+ public const string GET_CONSUMPTION_STATISTICS = "/users/me/consumption-statistics";
+ public const string GET_TAG_CONSUMPTION = "/users/me/consumption-statistics/tags";
+ public const string GET_USER_RECENTLY_CONSUMED = "/users/{userId}/consumption-history/recently-consumed";
+ public const string GET_USER_MOST_CONSUMED = "/users/{userId}/consumption-history/most-consumed";
+ public const string GET_USER_CONSUMPTION_STATISTICS = "/users/{userId}/consumption-statistics";
+ public const string GET_USER_TAG_CONSUMPTION = "/users/{userId}/consumption-statistics/tags";
+ public const string GET_ALL_USERS_CONSUMPTION_STATISTICS = "/users/consumption-statistics";
+ public const string DELETE_CONSUMPTION_RECORD = "/users/me/consumption-history/{recordId}";
+ public const string DELETE_USER_CONSUMPTION_RECORD = "/users/{userId}/consumption-history/{recordId}";
+ public const string CLEAR_CONSUMPTION_HISTORY = "/users/me/consumption-history";
+ public const string CLEAR_USER_CONSUMPTION_HISTORY = "/users/{userId}/consumption-history";
+ public const string CLEAR_RESUME_POINTS = "/users/me/media-resume-points";
+ public const string CLEAR_USER_RESUME_POINTS = "/users/{userId}/media-resume-points";
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs
new file mode 100644
index 00000000..671c8363
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs
@@ -0,0 +1,58 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.ClearConsumptionHistory;
+
+///
+/// API endpoint for the /users/me/consumption-history route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class ClearConsumptionHistoryEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _clearConsumptionHistoryCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling clear consumption history commands.
+ public ClearConsumptionHistoryEndpoint(ICommandHandler> clearConsumptionHistoryCommandHandler)
+ {
+ _clearConsumptionHistoryCommandHandler = clearConsumptionHistoryCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes every consumption record of the current user.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption history belongs to the authenticated user, so no intermediary may store any response of this route, including its problem
+ // responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result result = await _clearConsumptionHistoryCommandHandler.HandleAsync(new ClearConsumptionHistoryCommand(TargetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs
new file mode 100644
index 00000000..0f448eab
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs
@@ -0,0 +1,70 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class ClearConsumptionHistoryEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ClearConsumptionHistoryEndpointSummary()
+ {
+ Summary = "Deletes every consumption record of the current user.";
+ Description = "Deletes every recorded consumption session of the current user. The deletion is a hard delete, so the statistics and the history lists are empty as soon as it completes. Clearing an already empty history changes nothing and is not an error, so a retried clearance is safe; a concurrent write can still be rejected with a conflict. The resume points are not deleted: clearing the history and removing items from continue watching are separate user actions, and a user can keep their resume points after deleting their history. The history of another user is never deleted by this route.";
+
+ Response(200, "The consumption history was successfully cleared.");
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-history"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-history"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-history",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/me/consumption-history",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpoint.cs
new file mode 100644
index 00000000..f99a9a1b
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpoint.cs
@@ -0,0 +1,58 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.ClearConsumptionHistory;
+
+///
+/// API endpoint for the /users/{userId}/consumption-history route.
+///
+public class ClearUserConsumptionHistoryEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _clearConsumptionHistoryCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling clear consumption history commands.
+ public ClearUserConsumptionHistoryEndpoint(ICommandHandler> clearConsumptionHistoryCommandHandler)
+ {
+ _clearConsumptionHistoryCommandHandler = clearConsumptionHistoryCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.CLEAR_USER_CONSUMPTION_HISTORY);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes every consumption record of a user.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption history belongs to the target user, and only that user or an Admin may read or delete it, so no intermediary may store any
+ // response of this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the target user from the route. The access policy in the command decides whether the caller is the target user or an admin, and a
+ // regular user targeting another user receives the same not authorized result as a route that names no accessible user.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result result = await _clearConsumptionHistoryCommandHandler.HandleAsync(new ClearConsumptionHistoryCommand(targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointSummary.cs
new file mode 100644
index 00000000..fe217434
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointSummary.cs
@@ -0,0 +1,94 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class ClearUserConsumptionHistoryEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ClearUserConsumptionHistoryEndpointSummary()
+ {
+ Summary = "Deletes every consumption record of a user.";
+ Description = "Deletes every recorded consumption session of a user. A user can clear only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. The deletion is a hard delete, so the statistics and the history lists are empty as soon as it completes. Clearing an already empty history changes nothing and is not an error, so a retried clearance is safe; a concurrent write can still be rejected with a conflict. The resume points are not deleted: clearing the history and removing items from continue watching are separate user actions, and a user can keep their resume points after deleting their history.";
+
+ Params["userId"] = "The Id of the user whose history is cleared. An Admin can name any user; a regular user can only name themselves.";
+
+ Response(200, "The consumption history of the user was successfully cleared.");
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/{userId}/consumption-history"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/consumption-history"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/consumption-history",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/{userId}/consumption-history",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/{userId}/consumption-history",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs
new file mode 100644
index 00000000..6dfb746e
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.ClearResumePoints;
+
+///
+/// API endpoint for the /users/me/media-resume-points route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class ClearResumePointsEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _clearResumePointsCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling clear resume points commands.
+ public ClearResumePointsEndpoint(ICommandHandler> clearResumePointsCommandHandler)
+ {
+ _clearResumePointsCommandHandler = clearResumePointsCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.CLEAR_RESUME_POINTS);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes the resume points of the current user.
+ ///
+ /// The request containing the optional library filter.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(ClearResumePointsRequest request, CancellationToken cancellationToken)
+ {
+ // The resume points belong to the authenticated user, so no intermediary may store any response of this route, including its problem
+ // responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result result = await _clearResumePointsCommandHandler.HandleAsync(request.ToCommand(targetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs
new file mode 100644
index 00000000..d3ba9809
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs
@@ -0,0 +1,95 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class ClearResumePointsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ClearResumePointsEndpointSummary()
+ {
+ Summary = "Deletes the resume points of the current user.";
+ Description = "Deletes the resume points of the current user, optionally limited to one media library with the libraryId query parameter. This only clears the continue watching list, while the recorded consumption history is kept, so the statistics and the history lists do not change. Deleting absent resume points changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume points of another user are never deleted by this route.";
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the deletion to. Optional.");
+
+ Response(200, "The resume points were successfully deleted.");
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/me/media-resume-points"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/media-resume-points"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/media-resume-points",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/me/media-resume-points",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/me/media-resume-points",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpoint.cs
new file mode 100644
index 00000000..478b01d8
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpoint.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.ClearResumePoints;
+
+///
+/// API endpoint for the /users/{userId}/media-resume-points route.
+///
+public class ClearUserResumePointsEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _clearResumePointsCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling clear resume points commands.
+ public ClearUserResumePointsEndpoint(ICommandHandler> clearResumePointsCommandHandler)
+ {
+ _clearResumePointsCommandHandler = clearResumePointsCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.CLEAR_USER_RESUME_POINTS);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes the resume points of a user.
+ ///
+ /// The request containing the optional library filter.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(ClearResumePointsRequest request, CancellationToken cancellationToken)
+ {
+ // The resume points belong to the target user, and only that user or an Admin may read or delete them, so no intermediary may store any
+ // response of this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the target user from the route. The access policy in the command decides whether the caller is the target user or an admin, and a
+ // regular user targeting another user receives the same not authorized result as a route that names no accessible user.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result result = await _clearResumePointsCommandHandler.HandleAsync(request.ToCommand(targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointSummary.cs
new file mode 100644
index 00000000..ecab050c
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointSummary.cs
@@ -0,0 +1,97 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class ClearUserResumePointsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ClearUserResumePointsEndpointSummary()
+ {
+ Summary = "Deletes the resume points of a user.";
+ Description = "Deletes the resume points of a user, optionally limited to one media library with the libraryId query parameter. A user can clear only their own resume points, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. This only clears the continue watching list, while the recorded consumption history is kept, so the statistics and the history lists do not change. Deleting absent resume points changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict.";
+
+ Params["userId"] = "The Id of the user whose resume points are deleted. An Admin can name any user; a regular user can only name themselves.";
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the deletion to. Optional.");
+
+ Response(200, "The resume points of the user were successfully deleted.");
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/{userId}/media-resume-points"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/media-resume-points"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/media-resume-points",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/{userId}/media-resume-points",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/{userId}/media-resume-points",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "LibraryIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpoint.cs
new file mode 100644
index 00000000..1fdb3c56
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpoint.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.DeleteConsumptionRecord;
+
+///
+/// API endpoint for the /users/me/consumption-history/{recordId} route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class DeleteConsumptionRecordEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _deleteConsumptionRecordCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling delete consumption record commands.
+ public DeleteConsumptionRecordEndpoint(ICommandHandler> deleteConsumptionRecordCommandHandler)
+ {
+ _deleteConsumptionRecordCommandHandler = deleteConsumptionRecordCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.DELETE_CONSUMPTION_RECORD);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes one consumption record of the current user.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem
+ // responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the unique identifier from the route, so that it cannot be replaced by a value supplied in the query string.
+ string? consumptionRecordId = HttpContext.Request.RouteValues["recordId"]?.ToString();
+ Result result = await _deleteConsumptionRecordCommandHandler.HandleAsync(new DeleteConsumptionRecordCommand(consumptionRecordId, TargetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointSummary.cs
new file mode 100644
index 00000000..87795baa
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointSummary.cs
@@ -0,0 +1,94 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionRecordEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteConsumptionRecordEndpointSummary()
+ {
+ Summary = "Deletes one consumption record of the current user.";
+ Description = "Deletes one recorded consumption session of the current user, named by the route. The deletion is a hard delete, so the session stops contributing to the statistics and to the history lists immediately. Deleting an absent record, or a record that was already deleted in another tab, changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing a record from the history and removing an item from continue watching are separate user actions. The record of another user is never deleted by this route.";
+
+ Params["recordId"] = "The Id of the consumption record to delete.";
+
+ Response(200, "The consumption record was successfully deleted.");
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "ConsumptionRecordIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpoint.cs
new file mode 100644
index 00000000..5b12acf5
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpoint.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.DeleteConsumptionRecord;
+
+///
+/// API endpoint for the /users/{userId}/consumption-history/{recordId} route.
+///
+public class DeleteUserConsumptionRecordEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _deleteConsumptionRecordCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling delete consumption record commands.
+ public DeleteUserConsumptionRecordEndpoint(ICommandHandler> deleteConsumptionRecordCommandHandler)
+ {
+ _deleteConsumptionRecordCommandHandler = deleteConsumptionRecordCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.DELETE_USER_CONSUMPTION_RECORD);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes one consumption record of a user.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption record belongs to the target user, and only that user or an Admin may read or delete it, so no intermediary may store any
+ // response of this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the unique identifiers from the route, so that they cannot be replaced by values supplied in the query string.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ string? consumptionRecordId = HttpContext.Request.RouteValues["recordId"]?.ToString();
+ // The access policy in the command decides whether the caller is the target user or an admin, and a regular user targeting another user
+ // receives the same not authorized result as a route that names no accessible user.
+ Result result = await _deleteConsumptionRecordCommandHandler.HandleAsync(new DeleteConsumptionRecordCommand(consumptionRecordId, targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointSummary.cs
new file mode 100644
index 00000000..279c0bcb
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointSummary.cs
@@ -0,0 +1,96 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteUserConsumptionRecordEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteUserConsumptionRecordEndpointSummary()
+ {
+ Summary = "Deletes one consumption record of a user.";
+ Description = "Deletes one recorded consumption session of a user, named by the route. A user can delete only their own records, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. The deletion is a hard delete, so the session stops contributing to the statistics and to the history lists immediately. Deleting an absent record, or a record that was already deleted in another tab, changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing a record from the history and removing an item from continue watching are separate user actions.";
+
+ Params["userId"] = "The Id of the user whose record is deleted. An Admin can name any user; a regular user can only name themselves.";
+ Params["recordId"] = "The Id of the consumption record to delete.";
+
+ Response(200, "The consumption record was successfully deleted.");
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "ConsumptionRecordIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs
new file mode 100644
index 00000000..5bfacbd2
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs
@@ -0,0 +1,59 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.GetAllUsersConsumptionStatistics;
+
+///
+/// API endpoint for the /users/consumption-statistics route.
+///
+public class GetAllUsersConsumptionStatisticsEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler> _getAllUsersConsumptionStatisticsQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get all users consumption statistics queries.
+ public GetAllUsersConsumptionStatisticsEndpoint(IQueryHandler> getAllUsersConsumptionStatisticsQueryHandler)
+ {
+ _getAllUsersConsumptionStatisticsQueryHandler = getAllUsersConsumptionStatisticsQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_ALL_USERS_CONSUMPTION_STATISTICS);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the consumption statistics of every user.
+ ///
+ /// The request containing the optional filters and the date range.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetAllUsersConsumptionStatisticsRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption statistics belong to every user of the server, so no intermediary may store any response of this route, including its
+ // problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // The handler is the only place that checks the admin role, so a regular user receives the same not authorized result as any other protected administration route.
+ Result result = await _getAllUsersConsumptionStatisticsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs
new file mode 100644
index 00000000..e080174a
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs
@@ -0,0 +1,185 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetAllUsersConsumptionStatisticsEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of every user.";
+ Description = "Gets the consumption statistics of every user of the server, together with their combined totals, across every kind of media or restricted to one kind, one library, and a date range. Only an Admin can call this route; a regular user receives the same not authorized result as any other administration route. A session counts only when it completed, or when it reached the counting threshold of its media kind: 30 consecutive seconds of a music track or a podcast episode, 60 consecutive seconds of an audiobook, 3 consecutive minutes of a movie, a TV episode or a video, more than 5 consecutive pages of a book, or every view of a photo. The consumed duration totals every recorded session, including the sessions that do not count, while the counted, completed, and stopped session counts follow the counting rules. Each user summary carries its own breakdown by media kind, and the combined totals are derived from those summaries, so they can never disagree with the sum of the users.";
+
+ ExampleRequest = new GetAllUsersConsumptionStatisticsRequest(
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam(response => response.Total, "The combined consumption statistics of every user.");
+ ResponseParam(response => response.Users, "The consumption statistics of each user, ordered by user Id. Each summary carries the user Id and the same fields as a single user summary.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of every user, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of every user that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of every user that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of every user that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session.");
+ ResponseParam(response => response.MediaKindSummaries, "The combined consumption statistics broken down by media kind.");
+
+ Response(statusCode: 200, description: "The consumption statistics of every user are returned.", contentType: "application/json",
+ example: new AllUsersConsumptionStatisticsResponse(
+ Total: new ConsumptionTotalsResponse(
+ TotalConsumedDurationInSeconds: 12874.5,
+ CountedSessionCount: 9,
+ CompletedSessionCount: 6,
+ StoppedSessionCount: 3,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 5554.5,
+ CountedSessionCount: 7,
+ CompletedSessionCount: 5,
+ StoppedSessionCount: 2,
+ CompletionRate: 0.7143
+ ),
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.Book,
+ TotalConsumedDurationInSeconds: 7320,
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.5
+ )
+ ]
+ ),
+ Users:
+ [
+ new ConsumptionSummaryResponse(
+ UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"),
+ TotalConsumedDurationInSeconds: 8744.5,
+ CountedSessionCount: 6,
+ CompletedSessionCount: 4,
+ StoppedSessionCount: 2,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 1424.5,
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.75
+ ),
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.Book,
+ TotalConsumedDurationInSeconds: 7320,
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.5
+ )
+ ]
+ ),
+ new ConsumptionSummaryResponse(
+ UserId: Guid.Parse("2b3c4d5e-6f70-4a1b-9c3d-4e5f6a7b8c9d"),
+ TotalConsumedDurationInSeconds: 4130,
+ CountedSessionCount: 3,
+ CompletedSessionCount: 2,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 4130,
+ CountedSessionCount: 3,
+ CompletedSessionCount: 2,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.6667
+ )
+ ]
+ )
+ ]
+ )
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/consumption-statistics"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/consumption-statistics"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is not an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/consumption-statistics",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/consumption-statistics",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind",
+ "ConsumptionDateRangeIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs
new file mode 100644
index 00000000..2fa63318
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.GetConsumptionStatistics;
+
+///
+/// API endpoint for the /users/me/consumption-statistics route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetConsumptionStatisticsEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler> _getConsumptionStatisticsQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get consumption statistics queries.
+ public GetConsumptionStatisticsEndpoint(IQueryHandler> getConsumptionStatisticsQueryHandler)
+ {
+ _getConsumptionStatisticsQueryHandler = getConsumptionStatisticsQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_CONSUMPTION_STATISTICS);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the consumption statistics of the current user.
+ ///
+ /// The request containing the optional filters and the date range.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetConsumptionStatisticsRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption statistics belong to the authenticated user, so no intermediary may store any response of this route, including its
+ // problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result result = await _getConsumptionStatisticsQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs
new file mode 100644
index 00000000..18bb140c
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs
@@ -0,0 +1,134 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetConsumptionStatisticsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetConsumptionStatisticsEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of the current user.";
+ Description = "Gets the consolidated consumption statistics of the current user, across every kind of media or restricted to one kind, one library, and a date range. A session counts only when it completed, or when it reached the counting threshold of its media kind: 30 consecutive seconds of a music track or a podcast episode, 60 consecutive seconds of an audiobook, 3 consecutive minutes of a movie, a TV episode or a video, more than 5 consecutive pages of a book, or every view of a photo. The consumed duration totals every recorded session, including the sessions that do not count, while the counted, completed, and stopped session counts follow the counting rules. The completion rate is the fraction of the counted sessions that completed. Music and book consumption are reported in the same summary, broken down by media kind. The statistics are derived from the recorded sessions, so deleting history changes them immediately. The statistics of another user are never returned by this route.";
+
+ ExampleRequest = new GetConsumptionStatisticsRequest(
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam(response => response.UserId, "The Id of the user the statistics belong to.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session.");
+ ResponseParam(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind. Each entry carries the media kind, the consumed duration, the counted, completed and stopped session counts, and the completion rate of that kind.");
+
+ Response(statusCode: 200, description: "The consumption statistics of the current user are returned.", contentType: "application/json",
+ example: new ConsumptionSummaryResponse(
+ UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"),
+ TotalConsumedDurationInSeconds: 8744.5,
+ CountedSessionCount: 6,
+ CompletedSessionCount: 4,
+ StoppedSessionCount: 2,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 1424.5,
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.75
+ ),
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.Book,
+ TotalConsumedDurationInSeconds: 7320,
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.5
+ )
+ ]
+ )
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-statistics"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-statistics"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-statistics",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/me/consumption-statistics",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind",
+ "ConsumptionDateRangeIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpoint.cs
new file mode 100644
index 00000000..2ddfb9f0
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpoint.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.GetConsumptionStatistics;
+
+///
+/// API endpoint for the /users/{userId}/consumption-statistics route.
+///
+public class GetUserConsumptionStatisticsEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler> _getConsumptionStatisticsQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get consumption statistics queries.
+ public GetUserConsumptionStatisticsEndpoint(IQueryHandler> getConsumptionStatisticsQueryHandler)
+ {
+ _getConsumptionStatisticsQueryHandler = getConsumptionStatisticsQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_USER_CONSUMPTION_STATISTICS);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the consumption statistics of a user.
+ ///
+ /// The request containing the optional filters and the date range.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetConsumptionStatisticsRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption statistics belong to the target user, and only that user or an Admin may read them, so no intermediary may store any response
+ // of this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a
+ // regular user targeting another user receives the same not authorized result as a route that names no accessible user.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result result = await _getConsumptionStatisticsQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs
new file mode 100644
index 00000000..0afceca6
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs
@@ -0,0 +1,136 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetUserConsumptionStatisticsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetUserConsumptionStatisticsEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of a user.";
+ Description = "Gets the consolidated consumption statistics of a user, across every kind of media or restricted to one kind, one library, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. A session counts only when it completed, or when it reached the counting threshold of its media kind: 30 consecutive seconds of a music track or a podcast episode, 60 consecutive seconds of an audiobook, 3 consecutive minutes of a movie, a TV episode or a video, more than 5 consecutive pages of a book, or every view of a photo. The consumed duration totals every recorded session, including the sessions that do not count, while the counted, completed, and stopped session counts follow the counting rules. The completion rate is the fraction of the counted sessions that completed. Music and book consumption are reported in the same summary, broken down by media kind. The statistics are derived from the recorded sessions, so deleting history changes them immediately.";
+
+ ExampleRequest = new GetConsumptionStatisticsRequest(
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves.";
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam(response => response.UserId, "The Id of the user the statistics belong to.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session.");
+ ResponseParam(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind. Each entry carries the media kind, the consumed duration, the counted, completed and stopped session counts, and the completion rate of that kind.");
+
+ Response(statusCode: 200, description: "The consumption statistics of the user are returned.", contentType: "application/json",
+ example: new ConsumptionSummaryResponse(
+ UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"),
+ TotalConsumedDurationInSeconds: 8744.5,
+ CountedSessionCount: 6,
+ CompletedSessionCount: 4,
+ StoppedSessionCount: 2,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 1424.5,
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.75
+ ),
+ new MediaKindConsumptionSummaryResponse(
+ MediaKind: MediaKind.Book,
+ TotalConsumedDurationInSeconds: 7320,
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.5
+ )
+ ]
+ )
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/{userId}/consumption-statistics"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/consumption-statistics"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/consumption-statistics",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/{userId}/consumption-statistics",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind",
+ "ConsumptionDateRangeIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs
new file mode 100644
index 00000000..8c0e4117
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.GetMostConsumed;
+
+///
+/// API endpoint for the /users/me/consumption-history/most-consumed route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetMostConsumedEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getMostConsumedQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get most consumed queries.
+ public GetMostConsumedEndpoint(IQueryHandler>> getMostConsumedQueryHandler)
+ {
+ _getMostConsumedQueryHandler = getMostConsumedQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_MOST_CONSUMED);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the most consumed media items of the current user.
+ ///
+ /// The request containing the optional filters and the page bounds.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetMostConsumedRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption history belongs to the authenticated user, so no intermediary may store any response of this route, including its problem
+ // responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result> result = await _getMostConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs
new file mode 100644
index 00000000..51cc7d80
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs
@@ -0,0 +1,155 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetMostConsumedEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetMostConsumedEndpointSummary()
+ {
+ Summary = "Gets the most consumed media items of the current user.";
+ Description = "Gets one page of the media items the current user consumed the most, across every kind of media or restricted to one kind and one library. The items are ordered by the number of sessions that count towards statistics, then by the consumed duration, then by the last consumption date, and finally by the media item Id so the order is stable. Music and book sessions appear in the same list, and an item consumed many times appears once. An item whose sessions all fall below the counting threshold of its kind still appears in this list with a countedSessionCount of zero, but it is ordered after every item that has at least one counted session, so it normally appears on a later page. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item whose media item was deleted, or whose media library the user can no longer access, is still returned, with isAvailable set to false and empty display details, so the user can see it and delete the session. The history of another user is never returned by this route.";
+
+ ExampleRequest = new GetMostConsumedRequest(
+ LibraryId: null,
+ MediaKind: MediaKind.MusicTrack,
+ CurrentPage: 1,
+ PerPage: 50
+ );
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
+ RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
+ RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+
+ ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, and last consumption date.");
+ ResponseParam>(response => response.CurrentPage, "The current page number.");
+ ResponseParam>(response => response.PerPage, "The number of media items retrieved per page.");
+ ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters.");
+ ResponseParam>(response => response.NumberOfPages, "The total number of pages.");
+ ResponseParam(response => response.MediaKind, "The kind of the consumed media item.");
+ ResponseParam(response => response.MediaItemId, "The Id of the consumed media item.");
+ ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item.");
+ ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user.");
+ ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available.");
+ ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available.");
+ ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed.");
+ ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
+
+ Response(statusCode: 200, description: "The most consumed media items of the current user are returned.", contentType: "application/json",
+ example: new PaginatedResponse
+ {
+ Data =
+ [
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.MusicTrack,
+ MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
+ LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
+ IsAvailable: true,
+ Title: "The Show Must Go On",
+ CollectionTitle: "Innuendo",
+ CreatorName: "Queen",
+ CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc),
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ ConsumedDurationInSeconds: 1424.5
+ ),
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.Book,
+ MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"),
+ LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"),
+ IsAvailable: true,
+ Title: "The Fellowship of the Ring",
+ CollectionTitle: string.Empty,
+ CreatorName: "J. R. R. Tolkien",
+ CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc),
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ ConsumedDurationInSeconds: 7320
+ )
+ ],
+ CurrentPage = 1,
+ PerPage = 50,
+ Count = 2,
+ NumberOfPages = 1
+ }
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-history/most-consumed"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-history/most-consumed"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-history/most-consumed",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/me/consumption-history/most-consumed",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpoint.cs
new file mode 100644
index 00000000..ebb7a090
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.GetMostConsumed;
+
+///
+/// API endpoint for the /users/{userId}/consumption-history/most-consumed route.
+///
+public class GetUserMostConsumedEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getMostConsumedQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get most consumed queries.
+ public GetUserMostConsumedEndpoint(IQueryHandler>> getMostConsumedQueryHandler)
+ {
+ _getMostConsumedQueryHandler = getMostConsumedQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_USER_MOST_CONSUMED);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the most consumed media items of a user.
+ ///
+ /// The request containing the optional filters and the page bounds.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetMostConsumedRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption history belongs to the target user, and only that user or an Admin may read it, so no intermediary may store any response of
+ // this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a
+ // regular user targeting another user receives the same not authorized result as a route that names no accessible user.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result> result = await _getMostConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs
new file mode 100644
index 00000000..b97cee97
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs
@@ -0,0 +1,157 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetUserMostConsumedEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetUserMostConsumedEndpointSummary()
+ {
+ Summary = "Gets the most consumed media items of a user.";
+ Description = "Gets one page of the media items a user consumed the most, across every kind of media or restricted to one kind and one library. A user can read only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. The items are ordered by the number of sessions that count towards statistics, then by the consumed duration, then by the last consumption date, and finally by the media item Id so the order is stable. Music and book sessions appear in the same list, and an item consumed many times appears once. An item whose sessions all fall below the counting threshold of its kind still appears in this list with a countedSessionCount of zero, but it is ordered after every item that has at least one counted session, so it normally appears on a later page. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item whose media item was deleted, or whose media library the user can no longer access, is still returned, with isAvailable set to false and empty display details, so the user can see it and delete the session.";
+
+ ExampleRequest = new GetMostConsumedRequest(
+ LibraryId: null,
+ MediaKind: MediaKind.MusicTrack,
+ CurrentPage: 1,
+ PerPage: 50
+ );
+
+ Params["userId"] = "The Id of the user whose history is retrieved. An Admin can name any user; a regular user can only name themselves.";
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
+ RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
+ RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+
+ ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, and last consumption date.");
+ ResponseParam>(response => response.CurrentPage, "The current page number.");
+ ResponseParam>(response => response.PerPage, "The number of media items retrieved per page.");
+ ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters.");
+ ResponseParam>(response => response.NumberOfPages, "The total number of pages.");
+ ResponseParam(response => response.MediaKind, "The kind of the consumed media item.");
+ ResponseParam(response => response.MediaItemId, "The Id of the consumed media item.");
+ ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item.");
+ ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user.");
+ ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available.");
+ ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available.");
+ ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed.");
+ ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
+
+ Response(statusCode: 200, description: "The most consumed media items of the user are returned.", contentType: "application/json",
+ example: new PaginatedResponse
+ {
+ Data =
+ [
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.MusicTrack,
+ MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
+ LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
+ IsAvailable: true,
+ Title: "The Show Must Go On",
+ CollectionTitle: "Innuendo",
+ CreatorName: "Queen",
+ CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc),
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ ConsumedDurationInSeconds: 1424.5
+ ),
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.Book,
+ MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"),
+ LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"),
+ IsAvailable: true,
+ Title: "The Fellowship of the Ring",
+ CollectionTitle: string.Empty,
+ CreatorName: "J. R. R. Tolkien",
+ CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc),
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ ConsumedDurationInSeconds: 7320
+ )
+ ],
+ CurrentPage = 1,
+ PerPage = 50,
+ Count = 2,
+ NumberOfPages = 1
+ }
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/{userId}/consumption-history/most-consumed"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/consumption-history/most-consumed"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/consumption-history/most-consumed",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/{userId}/consumption-history/most-consumed",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs
new file mode 100644
index 00000000..763e19df
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.GetRecentlyConsumed;
+
+///
+/// API endpoint for the /users/me/consumption-history/recently-consumed route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetRecentlyConsumedEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getRecentlyConsumedQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get recently consumed queries.
+ public GetRecentlyConsumedEndpoint(IQueryHandler>> getRecentlyConsumedQueryHandler)
+ {
+ _getRecentlyConsumedQueryHandler = getRecentlyConsumedQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the recently consumed media items of the current user.
+ ///
+ /// The request containing the optional filters and the page bounds.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetRecentlyConsumedRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption history belongs to the authenticated user, so no intermediary may store any response of this route, including its problem
+ // responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result> result = await _getRecentlyConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs
new file mode 100644
index 00000000..20ae2644
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs
@@ -0,0 +1,155 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetRecentlyConsumedEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetRecentlyConsumedEndpointSummary()
+ {
+ Summary = "Gets the recently consumed media items of the current user.";
+ Description = "Gets one page of the media items the current user consumed, from the most recently consumed, across every kind of media or restricted to one kind and one library. Music and book sessions appear in the same list. An item whose sessions fall below the counting threshold of its kind is still listed, because the list shows the sessions that were really recorded; countedSessionCount reports only the sessions that count towards the statistics. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item whose media item was deleted, or whose media library the user can no longer access, is still returned, with isAvailable set to false and empty display details, so the user can see it and delete the session. The history of another user is never returned by this route.";
+
+ ExampleRequest = new GetRecentlyConsumedRequest(
+ LibraryId: null,
+ MediaKind: MediaKind.MusicTrack,
+ CurrentPage: 1,
+ PerPage: 50
+ );
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
+ RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
+ RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+
+ ResponseParam>(response => response.Data, "The recently consumed media items of the requested page, from the most recently consumed.");
+ ResponseParam>(response => response.CurrentPage, "The current page number.");
+ ResponseParam>(response => response.PerPage, "The number of media items retrieved per page.");
+ ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters.");
+ ResponseParam>(response => response.NumberOfPages, "The total number of pages.");
+ ResponseParam(response => response.MediaKind, "The kind of the consumed media item.");
+ ResponseParam(response => response.MediaItemId, "The Id of the consumed media item.");
+ ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item.");
+ ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user.");
+ ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available.");
+ ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available.");
+ ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed.");
+ ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
+
+ Response(statusCode: 200, description: "The recently consumed media items of the current user are returned.", contentType: "application/json",
+ example: new PaginatedResponse
+ {
+ Data =
+ [
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.MusicTrack,
+ MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
+ LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
+ IsAvailable: true,
+ Title: "The Show Must Go On",
+ CollectionTitle: "Innuendo",
+ CreatorName: "Queen",
+ CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc),
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ ConsumedDurationInSeconds: 1424.5
+ ),
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.Book,
+ MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"),
+ LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"),
+ IsAvailable: true,
+ Title: "The Fellowship of the Ring",
+ CollectionTitle: string.Empty,
+ CreatorName: "J. R. R. Tolkien",
+ CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc),
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ ConsumedDurationInSeconds: 7320
+ )
+ ],
+ CurrentPage = 1,
+ PerPage = 50,
+ Count = 2,
+ NumberOfPages = 1
+ }
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-history/recently-consumed"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-history/recently-consumed"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-history/recently-consumed",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/me/consumption-history/recently-consumed",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpoint.cs
new file mode 100644
index 00000000..5a880db5
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Statistics.GetRecentlyConsumed;
+
+///
+/// API endpoint for the /users/{userId}/consumption-history/recently-consumed route.
+///
+public class GetUserRecentlyConsumedEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getRecentlyConsumedQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get recently consumed queries.
+ public GetUserRecentlyConsumedEndpoint(IQueryHandler>> getRecentlyConsumedQueryHandler)
+ {
+ _getRecentlyConsumedQueryHandler = getRecentlyConsumedQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_USER_RECENTLY_CONSUMED);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the recently consumed media items of a user.
+ ///
+ /// The request containing the optional filters and the page bounds.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetRecentlyConsumedRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption history belongs to the target user, and only that user or an Admin may read it, so no intermediary may store any response of
+ // this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a
+ // regular user targeting another user receives the same not authorized result as a route that names no accessible user.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result> result = await _getRecentlyConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs
new file mode 100644
index 00000000..3b460525
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs
@@ -0,0 +1,157 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetUserRecentlyConsumedEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetUserRecentlyConsumedEndpointSummary()
+ {
+ Summary = "Gets the recently consumed media items of a user.";
+ Description = "Gets one page of the media items a user consumed, from the most recently consumed, across every kind of media or restricted to one kind and one library. A user can read only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Music and book sessions appear in the same list. An item whose sessions fall below the counting threshold of its kind is still listed, because the list shows the sessions that were really recorded; countedSessionCount reports only the sessions that count towards the statistics. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item whose media item was deleted, or whose media library the user can no longer access, is still returned, with isAvailable set to false and empty display details, so the user can see it and delete the session.";
+
+ ExampleRequest = new GetRecentlyConsumedRequest(
+ LibraryId: null,
+ MediaKind: MediaKind.MusicTrack,
+ CurrentPage: 1,
+ PerPage: 50
+ );
+
+ Params["userId"] = "The Id of the user whose history is retrieved. An Admin can name any user; a regular user can only name themselves.";
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
+ RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
+ RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+
+ ResponseParam>(response => response.Data, "The recently consumed media items of the requested page, from the most recently consumed.");
+ ResponseParam>(response => response.CurrentPage, "The current page number.");
+ ResponseParam>(response => response.PerPage, "The number of media items retrieved per page.");
+ ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters.");
+ ResponseParam>(response => response.NumberOfPages, "The total number of pages.");
+ ResponseParam(response => response.MediaKind, "The kind of the consumed media item.");
+ ResponseParam(response => response.MediaItemId, "The Id of the consumed media item.");
+ ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item.");
+ ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user.");
+ ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available.");
+ ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none.");
+ ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available.");
+ ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed.");
+ ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
+
+ Response(statusCode: 200, description: "The recently consumed media items of the user are returned.", contentType: "application/json",
+ example: new PaginatedResponse
+ {
+ Data =
+ [
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.MusicTrack,
+ MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
+ LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
+ IsAvailable: true,
+ Title: "The Show Must Go On",
+ CollectionTitle: "Innuendo",
+ CreatorName: "Queen",
+ CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc),
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ ConsumedDurationInSeconds: 1424.5
+ ),
+ new ConsumedItemResponse(
+ MediaKind: MediaKind.Book,
+ MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"),
+ LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"),
+ IsAvailable: true,
+ Title: "The Fellowship of the Ring",
+ CollectionTitle: string.Empty,
+ CreatorName: "J. R. R. Tolkien",
+ CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg",
+ LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc),
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ ConsumedDurationInSeconds: 7320
+ )
+ ],
+ CurrentPage = 1,
+ PerPage = 50,
+ Count = 2,
+ NumberOfPages = 1
+ }
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/{userId}/consumption-history/recently-consumed"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/consumption-history/recently-consumed"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/consumption-history/recently-consumed",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/{userId}/consumption-history/recently-consumed",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs
new file mode 100644
index 00000000..fb6759d7
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Library.Statistics.GetTagConsumption;
+
+///
+/// API endpoint for the /users/me/consumption-statistics/tags route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetTagConsumptionEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getTagConsumptionQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get tag consumption queries.
+ public GetTagConsumptionEndpoint(IQueryHandler>> getTagConsumptionQueryHandler)
+ {
+ _getTagConsumptionQueryHandler = getTagConsumptionQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_TAG_CONSUMPTION);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the consumption statistics of the tags and genres of the current user.
+ ///
+ /// The request containing the optional filters and the date range.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetTagConsumptionRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption statistics belong to the authenticated user, so no intermediary may store any response of this route, including its
+ // problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result> result = await _getTagConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs
new file mode 100644
index 00000000..ef95b6af
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs
@@ -0,0 +1,128 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetTagConsumptionEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetTagConsumptionEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of the tags and genres of the current user.";
+ Description = "Gets the tags and genres carried by the media items the current user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, one term kind, and a date range. Only an item with at least one session that counts towards statistics contributes, and each item contributes its terms once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a tag or genre that is shared by a book and a track appears in one bucket. Tags and genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their terms cannot be resolved, while their sessions still count in the summary. The statistics of another user are never returned by this route.";
+
+ ExampleRequest = new GetTagConsumptionRequest(
+ LibraryId: null,
+ MediaKind: null,
+ TagKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.TagKind, "Whether to return genres or tags. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam(response => response.Name, "The lowercase name of the tag or genre.");
+ ResponseParam(response => response.TagKind, "Whether the entry is a genre or a tag.");
+ ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the term and were consumed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the term, in seconds.");
+
+ Response>(statusCode: 200, description: "The consumption statistics of the tags and genres of the current user are returned.", contentType: "application/json",
+ example:
+ [
+ new TagConsumptionResponse(
+ Name: "horror",
+ TagKind: TagKind.Genre,
+ ConsumedItemCount: 3,
+ ConsumedDurationInSeconds: 5400
+ ),
+ new TagConsumptionResponse(
+ Name: "fantasy",
+ TagKind: TagKind.Genre,
+ ConsumedItemCount: 2,
+ ConsumedDurationInSeconds: 7320
+ ),
+ new TagConsumptionResponse(
+ Name: "favourite",
+ TagKind: TagKind.Tag,
+ ConsumedItemCount: 1,
+ ConsumedDurationInSeconds: 1424.5
+ )
+ ]
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-statistics/tags"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-statistics/tags"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-statistics/tags",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/me/consumption-statistics/tags",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind",
+ "TagKindIsInvalid",
+ "ConsumptionDateRangeIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpoint.cs
new file mode 100644
index 00000000..c11068b1
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+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.Library.Statistics.GetTagConsumption;
+
+///
+/// API endpoint for the /users/{userId}/consumption-statistics/tags route.
+///
+public class GetUserTagConsumptionEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getTagConsumptionQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get tag consumption queries.
+ public GetUserTagConsumptionEndpoint(IQueryHandler>> getTagConsumptionQueryHandler)
+ {
+ _getTagConsumptionQueryHandler = getTagConsumptionQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_USER_TAG_CONSUMPTION);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the consumption statistics of the tags and genres of a user.
+ ///
+ /// The request containing the optional filters and the date range.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetTagConsumptionRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption statistics belong to the target user, and only that user or an Admin may read them, so no intermediary may store any response
+ // of this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a
+ // regular user targeting another user receives the same not authorized result as a route that names no accessible user.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result> result = await _getTagConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs
new file mode 100644
index 00000000..df006d73
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs
@@ -0,0 +1,130 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetUserTagConsumptionEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetUserTagConsumptionEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of the tags and genres of a user.";
+ Description = "Gets the tags and genres carried by the media items a user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, one term kind, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Only an item with at least one session that counts towards statistics contributes, and each item contributes its terms once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a tag or genre that is shared by a book and a track appears in one bucket. Tags and genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their terms cannot be resolved, while their sessions still count in the summary.";
+
+ ExampleRequest = new GetTagConsumptionRequest(
+ LibraryId: null,
+ MediaKind: null,
+ TagKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves.";
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.TagKind, "Whether to return genres or tags. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam(response => response.Name, "The lowercase name of the tag or genre.");
+ ResponseParam(response => response.TagKind, "Whether the entry is a genre or a tag.");
+ ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the term and were consumed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the term, in seconds.");
+
+ Response>(statusCode: 200, description: "The consumption statistics of the tags and genres of the user are returned.", contentType: "application/json",
+ example:
+ [
+ new TagConsumptionResponse(
+ Name: "horror",
+ TagKind: TagKind.Genre,
+ ConsumedItemCount: 3,
+ ConsumedDurationInSeconds: 5400
+ ),
+ new TagConsumptionResponse(
+ Name: "fantasy",
+ TagKind: TagKind.Genre,
+ ConsumedItemCount: 2,
+ ConsumedDurationInSeconds: 7320
+ ),
+ new TagConsumptionResponse(
+ Name: "favourite",
+ TagKind: TagKind.Tag,
+ ConsumedItemCount: 1,
+ ConsumedDurationInSeconds: 1424.5
+ )
+ ]
+ );
+
+ 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 = "Authentication failed",
+ instance = "/api/v1/users/{userId}/consumption-statistics/tags"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/consumption-statistics/tags"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/consumption-statistics/tags",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/users/{userId}/consumption-statistics/tags",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind",
+ "TagKindIsInvalid",
+ "ConsumptionDateRangeIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}