Adds music play history persistence and reporting endpoints

This commit is contained in:
BinaryAlley committed 2026-10-19 22:16:09 +03:00
1 parent 9919965a73
commit 009a0c8156
55 files changed
+6426 -3

No files matched your search

@@ -0,0 +1,19 @@
namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
/// <summary>
/// Class for the collection of the music play history routes of the API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the music play history of the current user.
/// </summary>
public static class PlayHistory
{
public const string START_PLAY = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/plays";
public const string GET_PLAY = "/users/me/music-play-history/plays/{playRecordId}";
public const string REPORT_PLAY_PROGRESS = "/users/me/music-play-history/plays/{playRecordId}/progress";
public const string COMPLETE_PLAY = "/users/me/music-play-history/plays/{playRecordId}/complete";
public const string STOP_PLAY = "/users/me/music-play-history/plays/{playRecordId}/stop";
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
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.AudioLibrary.MusicLibrary.PlayHistory.CompletePlay;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}/complete</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class CompletePlayEndpoint : BaseEndpoint<CompletePlayRequest, IResult>
{
private readonly ICommandHandler<CompletePlayCommand, Result<Updated>> _completePlayCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="CompletePlayEndpoint"/> class.
/// </summary>
/// <param name="completePlayCommandHandler">Injected service for handling complete play commands.</param>
public CompletePlayEndpoint(ICommandHandler<CompletePlayCommand, Result<Updated>> completePlayCommandHandler)
{
_completePlayCommandHandler = completePlayCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.PlayHistory.COMPLETE_PLAY);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Reports that a play of a track by the current user reached its end.
/// </summary>
/// <param name="request">The request containing the last position and the listened duration.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CompletePlayRequest request, CancellationToken cancellationToken)
{
// Take the unique identifier from the route.
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
Result<Updated> result = await _completePlayCommandHandler.HandleAsync(request.ToCommand(playRecordId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.CompletePlay;
/// <summary>
/// Class used for providing a textual description for the <see cref="CompletePlayEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class CompletePlayEndpointSummary : Summary<CompletePlayEndpoint, CompletePlayRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CompletePlayEndpointSummary"/> class.
/// </summary>
public CompletePlayEndpointSummary()
{
Summary = "Reports that a play of a track by the current user reached its end.";
Description = "Reports that a play of a track by the current user reached its end, together with the last position and the listened duration. Only an in-progress play of the current user can be completed, and the listened duration can never decrease. The reports are stored so that the play history, statistics and recommendations can be built from them.";
ExampleRequest = new CompletePlayRequest(
PositionInSeconds: 354,
ListenedDurationInSeconds: 354
);
RequestParam(request => request.PositionInSeconds, "The last position reported by the player, in seconds. Required.");
RequestParam(request => request.ListenedDurationInSeconds, "The duration the user listened to, in seconds. Required.");
Response(200, "The completion of the play was reported.", example: new { });
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/music-play-history/plays/{Guid.NewGuid()}/complete"
},
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/music-play-history/plays/{Guid.NewGuid()}/complete"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete"
}
}
);
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "MusicPlayRecordNotFound",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(409, "The request failed because the play is not in progress anymore, or because another report changed it after this request read it.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "PlayIsNotInProgress",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "ConcurrencyConflict",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete",
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/music-play-history/plays/{Guid.NewGuid()}/complete",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"PlayRecordIdCannotBeEmpty",
"PlaybackPositionCannotBeNull",
"PlaybackPositionMustBeNonNegative",
"PlaybackPositionIsOutOfRange",
"ListenedDurationCannotBeNull",
"ListenedDurationMustBeNonNegative",
"ListenedDurationIsOutOfRange",
"ListenedDurationCannotDecrease"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
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.AudioLibrary.MusicLibrary.PlayHistory.GetPlayRecord;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetPlayRecordEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetPlayRecordQuery, Result<PlayRecordResponse>> _getPlayRecordQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetPlayRecordEndpoint"/> class.
/// </summary>
/// <param name="getPlayRecordQueryHandler">Injected service for handling get play record queries.</param>
public GetPlayRecordEndpoint(IQueryHandler<GetPlayRecordQuery, Result<PlayRecordResponse>> getPlayRecordQueryHandler)
{
_getPlayRecordQueryHandler = getPlayRecordQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.PlayHistory.GET_PLAY);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets a recorded play of a track by the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// The play 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["Vary"] = "Authorization";
// Take the unique identifier from the route.
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
Result<PlayRecordResponse> result = await _getPlayRecordQueryHandler.HandleAsync(new GetPlayRecordQuery(playRecordId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,117 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetPlayRecord;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPlayRecordEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlayRecordEndpointSummary : Summary<GetPlayRecordEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPlayRecordEndpointSummary"/> class.
/// </summary>
public GetPlayRecordEndpointSummary()
{
Summary = "Retrieves a recorded play of a track by the current user.";
Description = "Retrieves the play record identified by the route, when it belongs to the current user. The record carries the last reported position, the listened duration and whether the play is in progress, completed or stopped. It never carries a queue, a current index, a repeat or shuffle state, or a playback session.";
ResponseParam<PlayRecordResponse>(r => r.Id, "The Id of the play record.");
ResponseParam<PlayRecordResponse>(r => r.TrackId, "The Id of the track that was played.");
ResponseParam<PlayRecordResponse>(r => r.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayRecordResponse>(r => r.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayRecordResponse>(r => r.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayRecordResponse>(r => r.Status, "The state of the recorded play.");
ResponseParam<PlayRecordResponse>(r => r.LastPositionInSeconds, "The last position reported by the player, in seconds.");
ResponseParam<PlayRecordResponse>(r => r.ListenedDurationInSeconds, "The duration the user has listened to, in seconds.");
ResponseParam<PlayRecordResponse>(r => r.StartedOnUtc, "The date and time when the play started.");
ResponseParam<PlayRecordResponse>(r => r.EndedOnUtc, "The date and time when the play completed or stopped, if it has ended.");
ResponseParam<PlayRecordResponse>(r => r.UpdatedOnUtc, "The date and time when the play record was last updated, if applicable.");
Response(200, "The play record is returned.",
example: new PlayRecordResponse(
Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"),
TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
Status: PlaybackRecordStatus.Stopped,
LastPositionInSeconds: 92.5,
ListenedDurationInSeconds: 92.5,
StartedOnUtc: new DateTime(2026, 10, 19, 12, 0, 0, DateTimeKind.Utc),
EndedOnUtc: new DateTime(2026, 10, 19, 12, 1, 32, 500, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2026, 10, 19, 12, 1, 32, 500, DateTimeKind.Utc)
)
);
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/music-play-history/plays/{Guid.NewGuid()}"
},
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/music-play-history/plays/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}"
}
}
);
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "MusicPlayRecordNotFound",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"PlayRecordIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
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.AudioLibrary.MusicLibrary.PlayHistory.ReportPlayProgress;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}/progress</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class ReportPlayProgressEndpoint : BaseEndpoint<ReportPlayProgressRequest, IResult>
{
private readonly ICommandHandler<ReportPlayProgressCommand, Result<Updated>> _reportPlayProgressCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="ReportPlayProgressEndpoint"/> class.
/// </summary>
/// <param name="reportPlayProgressCommandHandler">Injected service for handling report play progress commands.</param>
public ReportPlayProgressEndpoint(ICommandHandler<ReportPlayProgressCommand, Result<Updated>> reportPlayProgressCommandHandler)
{
_reportPlayProgressCommandHandler = reportPlayProgressCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.PlayHistory.REPORT_PLAY_PROGRESS);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Reports the progress of a play of a track by the current user.
/// </summary>
/// <param name="request">The request containing the last position and the listened duration.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ReportPlayProgressRequest request, CancellationToken cancellationToken)
{
// Take the unique identifier from the route.
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
Result<Updated> result = await _reportPlayProgressCommandHandler.HandleAsync(request.ToCommand(playRecordId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.ReportPlayProgress;
/// <summary>
/// Class used for providing a textual description for the <see cref="ReportPlayProgressEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReportPlayProgressEndpointSummary : Summary<ReportPlayProgressEndpoint, ReportPlayProgressRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReportPlayProgressEndpointSummary"/> class.
/// </summary>
public ReportPlayProgressEndpointSummary()
{
Summary = "Reports the progress of a play of a track by the current user.";
Description = "Reports the last position and the listened duration of a play of a track by the current user. Only an in-progress play of the current user can be progressed, and the listened duration can never decrease. The reports are stored so that the play history, statistics and recommendations can be built from them.";
ExampleRequest = new ReportPlayProgressRequest(
PositionInSeconds: 92.5,
ListenedDurationInSeconds: 92.5
);
RequestParam(request => request.PositionInSeconds, "The last position reported by the player, in seconds. Required.");
RequestParam(request => request.ListenedDurationInSeconds, "The duration the user has listened to, in seconds. Required.");
Response(200, "The progress of the play was reported.", example: new { });
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/music-play-history/plays/{Guid.NewGuid()}/progress"
},
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/music-play-history/plays/{Guid.NewGuid()}/progress"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress"
}
}
);
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "MusicPlayRecordNotFound",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(409, "The request failed because the play is not in progress anymore, or because another report changed it after this request read it.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "PlayIsNotInProgress",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "ConcurrencyConflict",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress",
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/music-play-history/plays/{Guid.NewGuid()}/progress",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"PlayRecordIdCannotBeEmpty",
"PlaybackPositionCannotBeNull",
"PlaybackPositionMustBeNonNegative",
"PlaybackPositionIsOutOfRange",
"ListenedDurationCannotBeNull",
"ListenedDurationMustBeNonNegative",
"ListenedDurationIsOutOfRange",
"ListenedDurationCannotDecrease"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
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.AudioLibrary.MusicLibrary.PlayHistory.StartPlay;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/plays</c> route.
/// </summary>
public class StartPlayEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<StartPlayCommand, Result<PlayRecordResponse>> _startPlayCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="StartPlayEndpoint"/> class.
/// </summary>
/// <param name="startPlayCommandHandler">Injected service for handling start play commands.</param>
public StartPlayEndpoint(ICommandHandler<StartPlayCommand, Result<PlayRecordResponse>> startPlayCommandHandler)
{
_startPlayCommandHandler = startPlayCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.POST);
Routes(ApiRoutes.PlayHistory.START_PLAY);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Records the start of a play of a track by the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// Take the unique identifiers from the route, so that they cannot be replaced by values posted in a body.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString();
Result<PlayRecordResponse> result = await _startPlayCommandHandler
.HandleAsync(new StartPlayCommand(libraryId, artistId, albumId, trackId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,144 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.StartPlay;
/// <summary>
/// Class used for providing a textual description for the <see cref="StartPlayEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartPlayEndpointSummary : Summary<StartPlayEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="StartPlayEndpointSummary"/> class.
/// </summary>
public StartPlayEndpointSummary()
{
Summary = "Records the start of a play of a track by the current user.";
Description = "Records the start of a play of a track by the current user, so that the play history, statistics and recommendations can be built from it. The track must belong to the named library, album and artist. The play record is returned with its identifier, which the player uses to report its progress, completion or stop. The play record belongs to the current user, and it never stores a queue, a current index, a repeat or shuffle state, or a playback session.";
ResponseParam<PlayRecordResponse>(r => r.Id, "The Id of the play record.");
ResponseParam<PlayRecordResponse>(r => r.TrackId, "The Id of the track that was played.");
ResponseParam<PlayRecordResponse>(r => r.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayRecordResponse>(r => r.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayRecordResponse>(r => r.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayRecordResponse>(r => r.Status, "The state of the recorded play.");
ResponseParam<PlayRecordResponse>(r => r.LastPositionInSeconds, "The last position reported by the player, in seconds.");
ResponseParam<PlayRecordResponse>(r => r.ListenedDurationInSeconds, "The duration the user has listened to, in seconds.");
ResponseParam<PlayRecordResponse>(r => r.StartedOnUtc, "The date and time when the play started.");
ResponseParam<PlayRecordResponse>(r => r.EndedOnUtc, "The date and time when the play completed or stopped, if it has ended.");
ResponseParam<PlayRecordResponse>(r => r.UpdatedOnUtc, "The date and time when the play record was last updated, if applicable.");
Response(200, "The play was recorded and its play record is returned.",
example: new PlayRecordResponse(
Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"),
TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
Status: PlaybackRecordStatus.InProgress,
LastPositionInSeconds: 0,
ListenedDurationInSeconds: 0,
StartedOnUtc: new DateTime(2026, 10, 19, 12, 0, 0, DateTimeKind.Utc),
EndedOnUtc: null,
UpdatedOnUtc: null
)
);
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/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the album or the track does not exist, or they do not belong to the library, artist and album named by the request.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "AlbumNotFound",
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "TrackNotFound",
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"ArtistIdCannotBeEmpty",
"AlbumIdCannotBeEmpty",
"TrackIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
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.AudioLibrary.MusicLibrary.PlayHistory.StopPlay;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}/stop</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class StopPlayEndpoint : BaseEndpoint<StopPlayRequest, IResult>
{
private readonly ICommandHandler<StopPlayCommand, Result<Updated>> _stopPlayCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="StopPlayEndpoint"/> class.
/// </summary>
/// <param name="stopPlayCommandHandler">Injected service for handling stop play commands.</param>
public StopPlayEndpoint(ICommandHandler<StopPlayCommand, Result<Updated>> stopPlayCommandHandler)
{
_stopPlayCommandHandler = stopPlayCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.PlayHistory.STOP_PLAY);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Reports that a play of a track by the current user stopped before the track completed.
/// </summary>
/// <param name="request">The request containing the last position and the listened duration.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(StopPlayRequest request, CancellationToken cancellationToken)
{
// Take the unique identifier from the route.
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
Result<Updated> result = await _stopPlayCommandHandler.HandleAsync(request.ToCommand(playRecordId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.StopPlay;
/// <summary>
/// Class used for providing a textual description for the <see cref="StopPlayEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopPlayEndpointSummary : Summary<StopPlayEndpoint, StopPlayRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="StopPlayEndpointSummary"/> class.
/// </summary>
public StopPlayEndpointSummary()
{
Summary = "Reports that a play of a track by the current user stopped before the track completed.";
Description = "Reports that a play of a track by the current user stopped before the track completed, together with the last position and the listened duration. Only an in-progress play of the current user can be stopped, and the listened duration can never decrease. The reports are stored so that the play history, statistics and recommendations can be built from them.";
ExampleRequest = new StopPlayRequest(
PositionInSeconds: 92.5,
ListenedDurationInSeconds: 92.5
);
RequestParam(request => request.PositionInSeconds, "The last position reported by the player, in seconds. Required.");
RequestParam(request => request.ListenedDurationInSeconds, "The duration the user listened to, in seconds. Required.");
Response(200, "The stop of the play was reported.", example: new { });
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/music-play-history/plays/{Guid.NewGuid()}/stop"
},
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/music-play-history/plays/{Guid.NewGuid()}/stop"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop"
}
}
);
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "MusicPlayRecordNotFound",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(409, "The request failed because the play is not in progress anymore, or because another report changed it after this request read it.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "PlayIsNotInProgress",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "ConcurrencyConflict",
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop",
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/music-play-history/plays/{Guid.NewGuid()}/stop",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"PlayRecordIdCannotBeEmpty",
"PlaybackPositionCannotBeNull",
"PlaybackPositionMustBeNonNegative",
"PlaybackPositionIsOutOfRange",
"ListenedDurationCannotBeNull",
"ListenedDurationMustBeNonNegative",
"ListenedDurationIsOutOfRange",
"ListenedDurationCannotDecrease"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}