Removes the old music play history surface and drops its table

This commit is contained in:
BinaryAlley committed 2026-10-26 18:06:04 +02:00
1 parent 0b5b65391c
commit bc619679e8
83 files changed
+3955 -4893

No files matched your search

@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Data transfer object for the listening statistics of the current user.
/// </summary>
/// <param name="TotalListeningDurationMilliseconds">The total duration the user listened to, over every recorded play, in milliseconds.</param>
/// <param name="TotalPlayCount">The number of recorded plays that count as plays. An in-progress play counts once it reaches the threshold, so this total can exceed the completed and stopped plays together.</param>
/// <param name="CompletedPlayCount">The number of recorded plays that completed.</param>
/// <param name="StoppedPlayCount">The number of recorded plays that stopped before the track completed and count as plays.</param>
/// <param name="CompletionRate">The fraction of the plays that count as plays that completed, between 0 and 1, or 0 when there is no counted play.</param>
[DebuggerDisplay("TotalPlayCount: {TotalPlayCount}; CompletedPlayCount: {CompletedPlayCount}")]
public sealed record MusicPlayStatisticsDto(
long TotalListeningDurationMilliseconds,
int TotalPlayCount,
int CompletedPlayCount,
int StoppedPlayCount,
double CompletionRate
);
@@ -1,37 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Data transfer object for a track of the listening statistics of the current user, together with its aggregated play counts.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="Title">The title of the track, if it still exists and the user can access its library.</param>
/// <param name="AlbumTitle">The title of the album that contains the track, if it still exists and the user can access its library.</param>
/// <param name="ArtistName">The name of the artist that produced the track, if it still exists and the user can access its library.</param>
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
/// <param name="LastPlayedOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationMilliseconds">The duration the user listened to the track, over all of its counted plays, in milliseconds.</param>
[DebuggerDisplay("TrackId: {TrackId}; PlayCount: {PlayCount}")]
public sealed record PlayedTrackDto(
Guid TrackId,
Guid LibraryId,
Guid AlbumId,
Guid ArtistId,
string? Title,
string? AlbumTitle,
string? ArtistName,
string? CoverPath,
DateTime LastPlayedOnUtc,
int PlayCount,
int CompletedPlayCount,
long ListenedDurationMilliseconds
);
@@ -1,93 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for a recorded play of a track.
/// </summary>
[DebuggerDisplay("Id: {Id}; TrackId: {TrackId}; Status: {Status}")]
public class MusicPlayRecordEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the play record.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the user that started the play.
/// </summary>
public required Guid UserId { get; set; }
/// <summary>
/// Gets or sets the Id of the track that was played.
/// </summary>
public required Guid TrackId { get; set; }
/// <summary>
/// Gets or sets the Id of the media library that contains the track.
/// </summary>
public required Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the Id of the album that contains the track.
/// </summary>
public required Guid AlbumId { get; set; }
/// <summary>
/// Gets or sets the Id of the artist that produced the track.
/// </summary>
public required Guid ArtistId { get; set; }
/// <summary>
/// Gets or sets the state of the recorded play.
/// </summary>
public PlaybackRecordStatus Status { get; set; }
/// <summary>
/// Gets or sets the last position reported by the player, in milliseconds. It is stored as a whole number of milliseconds so that the
/// stored value is independent of the persistence medium's support for time values.
/// </summary>
public long LastPositionMilliseconds { get; set; }
/// <summary>
/// Gets or sets the duration the user has listened to, in milliseconds. It is stored as a whole number of milliseconds so that the
/// stored value is independent of the persistence medium's support for time values.
/// </summary>
public long ListenedDurationMilliseconds { get; set; }
/// <summary>
/// Gets or sets the date and time when the play completed or stopped, if it has ended.
/// </summary>
public DateTime? EndedOnUtc { get; set; }
/// <summary>
/// Gets or sets the version of the stored row. It is used as an optimistic concurrency token, so that a report that read the play
/// before another report ended it can never overwrite the newer state.
/// </summary>
public long Version { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added. It is also the date and time when the play started.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -1,50 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
/// <summary>
/// Interface for the repository for recorded music plays.
/// </summary>
public interface IMusicPlayRecordRepository : IRepository<MusicPlayRecordEntity>,
IInsertRepositoryAction<MusicPlayRecordEntity>
{
/// <summary>
/// Gets the play record identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>, if it exists.
/// </summary>
/// <param name="id">The Id of the play record to get.</param>
/// <param name="userId">The Id of the user the play record must belong to.</param>
/// <param name="shouldTrackEntities">Whether the retrieved record should be tracked by the persistence medium, so that changes to it can be saved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the play record identified by <paramref name="id"/> and owned by <paramref name="userId"/>,
/// <see langword="null"/> when no such record exists, or an error.
/// </returns>
Task<Result<MusicPlayRecordEntity?>> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the play records of the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose play records are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the play records of the user, or an error.</returns>
Task<Result<IReadOnlyList<MusicPlayRecordEntity>>> GetForUserAsync(Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Updates the play record of the user identified by <paramref name="userId"/>, when the record belongs to that user and still holds the
/// version it was read with.
/// </summary>
/// <param name="data">The play record whose editable values are applied to the stored record.</param>
/// <param name="userId">The Id of the user the play record must belong to.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
Task<Result<Updated>> UpdateForUserAsync(MusicPlayRecordEntity data, Guid userId, CancellationToken cancellationToken);
}
@@ -153,11 +153,6 @@ public interface IUnitOfWork
/// </summary>
IUserSettingsRepository UserSettingsRepository { get; }
/// <summary>
/// Gets the music play record repository.
/// </summary>
IMusicPlayRecordRepository MusicPlayRecordRepository { get; }
/// <summary>
/// Gets the playlist repository.
/// </summary>
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="CompletePlayRequest"/>.
/// </summary>
public static class CompletePlayRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="CompletePlayCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="playRecordId">The Id of the play record, taken from the route.</param>
/// <returns>The converted command.</returns>
public static CompletePlayCommand ToCommand(this CompletePlayRequest request, string? playRecordId)
{
return new CompletePlayCommand(
playRecordId,
request.PositionInSeconds,
request.ListenedDurationInSeconds
);
}
}
@@ -1,31 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="GetMostPlayedRequest"/>.
/// </summary>
public static class GetMostPlayedRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetMostPlayedQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetMostPlayedQuery ToQuery(this GetMostPlayedRequest request)
{
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 GetMostPlayedQuery(paginationData);
}
}
@@ -1,31 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="GetRecentlyPlayedRequest"/>.
/// </summary>
public static class GetRecentlyPlayedRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetRecentlyPlayedQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetRecentlyPlayedQuery ToQuery(this GetRecentlyPlayedRequest request)
{
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 GetRecentlyPlayedQuery(paginationData);
}
}
@@ -1,67 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="MusicPlayRecordEntity"/>.
/// </summary>
public static class MusicPlayRecordEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="MusicPlayRecord"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="MusicPlayRecord"/>, or an error message.
/// </returns>
public static Result<MusicPlayRecord> ToDomainEntity(this MusicPlayRecordEntity repositoryEntity)
{
return MusicPlayRecord.Create(
MusicPlayRecordId.Create(repositoryEntity.Id),
UserId.Create(repositoryEntity.UserId),
TrackId.Create(repositoryEntity.TrackId),
LibraryId.Create(repositoryEntity.LibraryId),
AlbumId.Create(repositoryEntity.AlbumId),
ArtistId.Create(repositoryEntity.ArtistId),
repositoryEntity.Status,
MusicPlayPosition.Create(repositoryEntity.LastPositionMilliseconds.ToClampedTimeSpan()),
repositoryEntity.ListenedDurationMilliseconds.ToClampedTimeSpan(),
Optional<DateTime>.FromNullable(repositoryEntity.EndedOnUtc),
repositoryEntity.CreatedOnUtc,
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc)
);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="PlayRecordResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static PlayRecordResponse ToResponse(this MusicPlayRecordEntity repositoryEntity)
{
return new PlayRecordResponse(
repositoryEntity.Id,
repositoryEntity.TrackId,
repositoryEntity.LibraryId,
repositoryEntity.AlbumId,
repositoryEntity.ArtistId,
repositoryEntity.Status,
repositoryEntity.LastPositionMilliseconds.ToClampedTimeSpan().TotalSeconds,
repositoryEntity.ListenedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
repositoryEntity.CreatedOnUtc,
repositoryEntity.EndedOnUtc,
repositoryEntity.UpdatedOnUtc
);
}
}
@@ -1,43 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="MusicPlayRecord"/>.
/// </summary>
public static class MusicPlayRecordMapping
{
/// <summary>
/// Converts <paramref name="domainEntity"/> to <see cref="MusicPlayRecordEntity"/>.
/// </summary>
/// <param name="domainEntity">The domain entity to be converted.</param>
/// <returns>The converted repository entity.</returns>
public static MusicPlayRecordEntity ToRepositoryEntity(this MusicPlayRecord domainEntity)
{
return new MusicPlayRecordEntity
{
Id = domainEntity.Id.Value,
UserId = domainEntity.UserId.Value,
TrackId = domainEntity.TrackId.Value,
LibraryId = domainEntity.LibraryId.Value,
AlbumId = domainEntity.AlbumId.Value,
ArtistId = domainEntity.ArtistId.Value,
Status = domainEntity.Status,
// Stored time is truncated to whole milliseconds instead of rounded, so a retried report of the same fractional second maps to
// the same stored value and is not rejected as a decrease by the domain.
LastPositionMilliseconds = (long)domainEntity.LastPosition.Offset.TotalMilliseconds,
ListenedDurationMilliseconds = (long)domainEntity.ListenedDuration.TotalMilliseconds,
EndedOnUtc = domainEntity.EndedOnUtc.HasValue ? domainEntity.EndedOnUtc.Value : null,
Version = 1,
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
};
}
}
@@ -1,29 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="MusicPlayStatisticsDto"/>.
/// </summary>
public static class MusicPlayStatisticsDtoMapping
{
/// <summary>
/// Converts <paramref name="data"/> to <see cref="MusicPlayStatisticsResponse"/>.
/// </summary>
/// <param name="data">The listening statistics data to be converted.</param>
/// <returns>The converted response.</returns>
public static MusicPlayStatisticsResponse ToResponse(this MusicPlayStatisticsDto data)
{
return new MusicPlayStatisticsResponse(
data.TotalListeningDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
data.TotalPlayCount,
data.CompletedPlayCount,
data.StoppedPlayCount,
data.CompletionRate
);
}
}
@@ -1,59 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using System;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="PlayedTrackDto"/>.
/// </summary>
public static class PlayedTrackDtoMapping
{
/// <summary>
/// Converts <paramref name="data"/> to <see cref="PlayedTrackResponse"/>.
/// </summary>
/// <param name="data">The played track data to be converted.</param>
/// <returns>The converted response.</returns>
public static PlayedTrackResponse ToResponse(this PlayedTrackDto data)
{
return new PlayedTrackResponse(
data.TrackId,
data.LibraryId,
data.AlbumId,
data.ArtistId,
data.Title,
data.AlbumTitle,
data.ArtistName,
data.CoverPath,
// The repository reads the stored play time through SQLite, which returns it as an unspecified kind, and the JSON response must not
// present a UTC wall clock as a local time. The value is UTC when it was stored, so it is marked as such before it is serialized.
DateTime.SpecifyKind(data.LastPlayedOnUtc, DateTimeKind.Utc),
data.PlayCount,
data.CompletedPlayCount,
data.ListenedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
);
}
/// <summary>
/// Converts <paramref name="data"/> to a paginated collection of <see cref="PlayedTrackResponse"/>.
/// </summary>
/// <param name="data">The paginated played track data to be converted.</param>
/// <returns>The converted paginated responses.</returns>
public static PaginatedResponse<PlayedTrackResponse> ToResponses(this PaginatedResultDto<PlayedTrackDto> data)
{
return new PaginatedResponse<PlayedTrackResponse>
{
Data = [.. data.Data.Select(track => track.ToResponse())],
CurrentPage = data.CurrentPage,
PerPage = data.PerPage,
Count = data.Count,
NumberOfPages = data.NumberOfPages
};
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="ReportPlayProgressRequest"/>.
/// </summary>
public static class ReportPlayProgressRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="ReportPlayProgressCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="playRecordId">The Id of the play record, taken from the route.</param>
/// <returns>The converted command.</returns>
public static ReportPlayProgressCommand ToCommand(this ReportPlayProgressRequest request, string? playRecordId)
{
return new ReportPlayProgressCommand(
playRecordId,
request.PositionInSeconds,
request.ListenedDurationInSeconds
);
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Extension methods for converting <see cref="StopPlayRequest"/>.
/// </summary>
public static class StopPlayRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="StopPlayCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="playRecordId">The Id of the play record, taken from the route.</param>
/// <returns>The converted command.</returns>
public static StopPlayCommand ToCommand(this StopPlayRequest request, string? playRecordId)
{
return new StopPlayCommand(
playRecordId,
request.PositionInSeconds,
request.ListenedDurationInSeconds
);
}
}
@@ -1,19 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
/// <summary>
/// Command for reporting that a play of a track by the current user reached its end.
/// </summary>
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
/// <param name="PositionInSeconds">The last position reported by the player, in seconds.</param>
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds.</param>
[DebuggerDisplay("PlayRecordId: {PlayRecordId}; PositionInSeconds: {PositionInSeconds}")]
public record CompletePlayCommand(
string? PlayRecordId,
double? PositionInSeconds,
double? ListenedDurationInSeconds
) : ICommand;
@@ -1,107 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
/// <summary>
/// Handler for the command to report that a play of a track by the current user reached its end.
/// </summary>
public class CompletePlayCommandHandler : ICommandHandler<CompletePlayCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<CompletePlayCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="CompletePlayCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public CompletePlayCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IValidator<CompletePlayCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to report that a play of a track by the current user reached its end.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error message.</returns>
public async Task<Result<Updated>> HandleAsync(CompletePlayCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifier and the reported times are valid before this point.
Guid playRecordId = Guid.Parse(command.PlayRecordId!);
// The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one.
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
.GetByIdForUserAsync(playRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPlayRecordResult.IsFailure)
return getPlayRecordResult.Errors;
if (getPlayRecordResult.Value is null)
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
Result<MusicPlayRecord> toDomainEntityResult = getPlayRecordResult.Value.ToDomainEntity();
if (toDomainEntityResult.IsFailure)
return toDomainEntityResult.Errors;
MusicPlayRecord playRecord = toDomainEntityResult.Value;
Result<Updated> completeResult = playRecord.Complete(
MusicPlayPosition.Create(TimeSpan.FromSeconds(command.PositionInSeconds!.Value)),
TimeSpan.FromSeconds(command.ListenedDurationInSeconds!.Value));
if (completeResult.IsFailure)
return completeResult.Errors;
Result<Updated> updateResult = await _unitOfWork.MusicPlayRecordRepository
.UpdateForUserAsync(playRecord.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Queue any domain events, to be published after the request has completed successfully.
foreach (IDomainEvent domainEvent in playRecord.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return Result.Updated;
}
}
@@ -1,53 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
/// <summary>
/// Validates the needed validation rules for <see cref="CompletePlayCommand"/>.
/// </summary>
public class CompletePlayCommandValidator : AbstractValidator<CompletePlayCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="CompletePlayCommandValidator"/> class.
/// </summary>
public CompletePlayCommandValidator()
{
RuleFor(command => command.PlayRecordId)
.NotEmpty()
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
RuleFor(command => command.PlayRecordId)
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
.When(command => command.PlayRecordId is not null && command.PlayRecordId.Length > 0)
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
RuleFor(command => command.PositionInSeconds)
.NotNull()
.WithError(Errors.MusicPlayHistory.PlaybackPositionCannotBeNull);
RuleFor(command => command.PositionInSeconds)
.Must(position => position is null || (double.IsFinite(position.Value) && position.Value >= 0))
.WithError(Errors.MusicPlayHistory.PlaybackPositionMustBeNonNegative);
RuleFor(command => command.PositionInSeconds)
.Must(position => position is null || position.Value <= TimeSpan.MaxValue.TotalSeconds)
.WithError(Errors.MusicPlayHistory.PlaybackPositionIsOutOfRange);
RuleFor(command => command.ListenedDurationInSeconds)
.NotNull()
.WithError(Errors.MusicPlayHistory.ListenedDurationCannotBeNull);
RuleFor(command => command.ListenedDurationInSeconds)
.Must(listenedDuration => listenedDuration is null || (double.IsFinite(listenedDuration.Value) && listenedDuration.Value >= 0))
.WithError(Errors.MusicPlayHistory.ListenedDurationMustBeNonNegative);
RuleFor(command => command.ListenedDurationInSeconds)
.Must(listenedDuration => listenedDuration is null || listenedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
.WithError(Errors.MusicPlayHistory.ListenedDurationIsOutOfRange);
}
}
@@ -1,19 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
/// <summary>
/// Command for reporting the progress of a play of a track by the current user.
/// </summary>
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
/// <param name="PositionInSeconds">The last position reported by the player, in seconds.</param>
/// <param name="ListenedDurationInSeconds">The duration the user has listened to, in seconds.</param>
[DebuggerDisplay("PlayRecordId: {PlayRecordId}; PositionInSeconds: {PositionInSeconds}")]
public record ReportPlayProgressCommand(
string? PlayRecordId,
double? PositionInSeconds,
double? ListenedDurationInSeconds
) : ICommand;
@@ -1,107 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
/// <summary>
/// Handler for the command to report the progress of a play of a track by the current user.
/// </summary>
public class ReportPlayProgressCommandHandler : ICommandHandler<ReportPlayProgressCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<ReportPlayProgressCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ReportPlayProgressCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public ReportPlayProgressCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IValidator<ReportPlayProgressCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to report the progress of a play of a track by the current user.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error message.</returns>
public async Task<Result<Updated>> HandleAsync(ReportPlayProgressCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifier and the reported times are valid before this point.
Guid playRecordId = Guid.Parse(command.PlayRecordId!);
// The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one.
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
.GetByIdForUserAsync(playRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPlayRecordResult.IsFailure)
return getPlayRecordResult.Errors;
if (getPlayRecordResult.Value is null)
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
Result<MusicPlayRecord> toDomainEntityResult = getPlayRecordResult.Value.ToDomainEntity();
if (toDomainEntityResult.IsFailure)
return toDomainEntityResult.Errors;
MusicPlayRecord playRecord = toDomainEntityResult.Value;
Result<Updated> reportProgressResult = playRecord.ReportProgress(
MusicPlayPosition.Create(TimeSpan.FromSeconds(command.PositionInSeconds!.Value)),
TimeSpan.FromSeconds(command.ListenedDurationInSeconds!.Value));
if (reportProgressResult.IsFailure)
return reportProgressResult.Errors;
Result<Updated> updateResult = await _unitOfWork.MusicPlayRecordRepository
.UpdateForUserAsync(playRecord.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Queue any domain events, to be published after the request has completed successfully.
foreach (IDomainEvent domainEvent in playRecord.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return Result.Updated;
}
}
@@ -1,53 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
/// <summary>
/// Validates the needed validation rules for <see cref="ReportPlayProgressCommand"/>.
/// </summary>
public class ReportPlayProgressCommandValidator : AbstractValidator<ReportPlayProgressCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReportPlayProgressCommandValidator"/> class.
/// </summary>
public ReportPlayProgressCommandValidator()
{
RuleFor(command => command.PlayRecordId)
.NotEmpty()
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
RuleFor(command => command.PlayRecordId)
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
.When(command => command.PlayRecordId is not null && command.PlayRecordId.Length > 0)
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
RuleFor(command => command.PositionInSeconds)
.NotNull()
.WithError(Errors.MusicPlayHistory.PlaybackPositionCannotBeNull);
RuleFor(command => command.PositionInSeconds)
.Must(position => position is null || (double.IsFinite(position.Value) && position.Value >= 0))
.WithError(Errors.MusicPlayHistory.PlaybackPositionMustBeNonNegative);
RuleFor(command => command.PositionInSeconds)
.Must(position => position is null || position.Value <= TimeSpan.MaxValue.TotalSeconds)
.WithError(Errors.MusicPlayHistory.PlaybackPositionIsOutOfRange);
RuleFor(command => command.ListenedDurationInSeconds)
.NotNull()
.WithError(Errors.MusicPlayHistory.ListenedDurationCannotBeNull);
RuleFor(command => command.ListenedDurationInSeconds)
.Must(listenedDuration => listenedDuration is null || (double.IsFinite(listenedDuration.Value) && listenedDuration.Value >= 0))
.WithError(Errors.MusicPlayHistory.ListenedDurationMustBeNonNegative);
RuleFor(command => command.ListenedDurationInSeconds)
.Must(listenedDuration => listenedDuration is null || listenedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
.WithError(Errors.MusicPlayHistory.ListenedDurationIsOutOfRange);
}
}
@@ -1,21 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
/// <summary>
/// Command for recording the start of a play of a track by the current user.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library that contains the track, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist that produced the track, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album that contains the track, taken from the route.</param>
/// <param name="TrackId">The unique identifier of the track that started playing, taken from the route.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record StartPlayCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? TrackId
) : ICommand;
@@ -1,148 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
/// <summary>
/// Handler for the command to record the start of a play of a track by the current user.
/// </summary>
public class StartPlayCommandHandler : ICommandHandler<StartPlayCommand, Result<PlayRecordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<StartPlayCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="StartPlayCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public StartPlayCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IDomainEventsQueue domainEventsQueue,
IValidator<StartPlayCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to record the start of a play of a track by the current user.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the created <see cref="PlayRecordResponse"/>, or an error message.
/// </returns>
public async Task<Result<PlayRecordResponse>> HandleAsync(StartPlayCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
Guid trackId = Guid.Parse(command.TrackId!);
// Admins can report plays of the tracks of all libraries; for everyone else, only the tracks of the libraries they own. Authorization
// is evaluated before any album or track is read, so an unauthorized caller cannot tell whether the route's album or track exists.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// The album is loaded first, so that the artist and the library named by the request are enforced before the track itself is read. This is
// the same resource scoping the track read uses, so a play can never reference a track through another library, artist or album.
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository
.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return DomainErrors.Music.AlbumNotFound;
AlbumEntity existingAlbum = getAlbumResult.Value;
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
return DomainErrors.Music.AlbumNotFound;
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository
.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return DomainErrors.Music.TrackNotFound;
TrackEntity existingTrack = getTrackResult.Value;
if (existingTrack.AlbumId != albumId || existingTrack.LibraryId != libraryId)
return DomainErrors.Music.TrackNotFound;
// Create the play record, which also raises the domain event announcing the start of the play.
MusicPlayRecord playRecord = MusicPlayRecord.Create(
UserId.Create(userId),
TrackId.Create(trackId),
LibraryId.Create(libraryId),
AlbumId.Create(albumId),
ArtistId.Create(artistId));
Result<Created> insertResult = await _unitOfWork.MusicPlayRecordRepository
.InsertAsync(playRecord.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
return insertResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Queue any domain events, to be published after the request has completed successfully.
foreach (IDomainEvent domainEvent in playRecord.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
// Reading does not need the aggregate: the persisted row is read directly and mapped to the response, so the response carries the
// timestamps the auditing interceptor actually stored instead of the in-memory aggregate's values.
Result<MusicPlayRecordEntity?> getPersistedPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
.GetByIdForUserAsync(playRecord.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedPlayRecordResult.IsFailure)
return getPersistedPlayRecordResult.Errors;
if (getPersistedPlayRecordResult.Value is null)
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
return getPersistedPlayRecordResult.Value.ToResponse();
}
}
@@ -1,60 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
/// <summary>
/// Validates the needed validation rules for <see cref="StartPlayCommand"/>.
/// </summary>
public class StartPlayCommandValidator : AbstractValidator<StartPlayCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="StartPlayCommandValidator"/> class.
/// </summary>
public StartPlayCommandValidator()
{
// Validates the identifier of the media library that contains the track, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the artist that produced the track, taken from the route.
RuleFor(command => command.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(command => command.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
// Validates the identifier of the album that contains the track, taken from the route.
RuleFor(command => command.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
RuleFor(command => command.AlbumId)
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
.When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
// Validates the identifier of the track that started playing, taken from the route.
RuleFor(command => command.TrackId)
.NotEmpty()
.WithError(Errors.Music.TrackIdCannotBeEmpty);
RuleFor(command => command.TrackId)
.Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty)
.When(command => command.TrackId is not null && command.TrackId.Length > 0)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
}
}
@@ -1,19 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
/// <summary>
/// Command for reporting that a play of a track by the current user stopped before the track completed.
/// </summary>
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
/// <param name="PositionInSeconds">The last position reported by the player, in seconds.</param>
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds.</param>
[DebuggerDisplay("PlayRecordId: {PlayRecordId}; PositionInSeconds: {PositionInSeconds}")]
public record StopPlayCommand(
string? PlayRecordId,
double? PositionInSeconds,
double? ListenedDurationInSeconds
) : ICommand;
@@ -1,107 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
/// <summary>
/// Handler for the command to report that a play of a track by the current user stopped before the track completed.
/// </summary>
public class StopPlayCommandHandler : ICommandHandler<StopPlayCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<StopPlayCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="StopPlayCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public StopPlayCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IValidator<StopPlayCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to report that a play of a track by the current user stopped before the track completed.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error message.</returns>
public async Task<Result<Updated>> HandleAsync(StopPlayCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifier and the reported times are valid before this point.
Guid playRecordId = Guid.Parse(command.PlayRecordId!);
// The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one.
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
.GetByIdForUserAsync(playRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPlayRecordResult.IsFailure)
return getPlayRecordResult.Errors;
if (getPlayRecordResult.Value is null)
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
Result<MusicPlayRecord> toDomainEntityResult = getPlayRecordResult.Value.ToDomainEntity();
if (toDomainEntityResult.IsFailure)
return toDomainEntityResult.Errors;
MusicPlayRecord playRecord = toDomainEntityResult.Value;
Result<Updated> stopResult = playRecord.Stop(
MusicPlayPosition.Create(TimeSpan.FromSeconds(command.PositionInSeconds!.Value)),
TimeSpan.FromSeconds(command.ListenedDurationInSeconds!.Value));
if (stopResult.IsFailure)
return stopResult.Errors;
Result<Updated> updateResult = await _unitOfWork.MusicPlayRecordRepository
.UpdateForUserAsync(playRecord.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Queue any domain events, to be published after the request has completed successfully.
foreach (IDomainEvent domainEvent in playRecord.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return Result.Updated;
}
}
@@ -1,53 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
/// <summary>
/// Validates the needed validation rules for <see cref="StopPlayCommand"/>.
/// </summary>
public class StopPlayCommandValidator : AbstractValidator<StopPlayCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="StopPlayCommandValidator"/> class.
/// </summary>
public StopPlayCommandValidator()
{
RuleFor(command => command.PlayRecordId)
.NotEmpty()
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
RuleFor(command => command.PlayRecordId)
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
.When(command => command.PlayRecordId is not null && command.PlayRecordId.Length > 0)
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
RuleFor(command => command.PositionInSeconds)
.NotNull()
.WithError(Errors.MusicPlayHistory.PlaybackPositionCannotBeNull);
RuleFor(command => command.PositionInSeconds)
.Must(position => position is null || (double.IsFinite(position.Value) && position.Value >= 0))
.WithError(Errors.MusicPlayHistory.PlaybackPositionMustBeNonNegative);
RuleFor(command => command.PositionInSeconds)
.Must(position => position is null || position.Value <= TimeSpan.MaxValue.TotalSeconds)
.WithError(Errors.MusicPlayHistory.PlaybackPositionIsOutOfRange);
RuleFor(command => command.ListenedDurationInSeconds)
.NotNull()
.WithError(Errors.MusicPlayHistory.ListenedDurationCannotBeNull);
RuleFor(command => command.ListenedDurationInSeconds)
.Must(listenedDuration => listenedDuration is null || (double.IsFinite(listenedDuration.Value) && listenedDuration.Value >= 0))
.WithError(Errors.MusicPlayHistory.ListenedDurationMustBeNonNegative);
RuleFor(command => command.ListenedDurationInSeconds)
.Must(listenedDuration => listenedDuration is null || listenedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
.WithError(Errors.MusicPlayHistory.ListenedDurationIsOutOfRange);
}
}
@@ -1,16 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Pagination;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
/// <summary>
/// Query for getting the most played tracks of the current user, from the most played.
/// </summary>
/// <param name="PaginationData">The object containing the requested pagination data, or <see langword="null"/> to return every matching track.</param>
[DebuggerDisplay("PaginationData: {PaginationData}")]
public record GetMostPlayedQuery(
PaginationDataDto? PaginationData
) : IQuery;
@@ -1,256 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
/// <summary>
/// Handler for the query to get the most played tracks of the current user.
/// </summary>
public class GetMostPlayedQueryHandler : IQueryHandler<GetMostPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
public GetMostPlayedQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the most played tracks of the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the requested page of most played tracks, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<PlayedTrackResponse>>> HandleAsync(GetMostPlayedQuery query, CancellationToken cancellationToken)
{
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
Result<IReadOnlyList<MusicPlayRecordEntity>> getRecordsResult = await _unitOfWork.MusicPlayRecordRepository.GetForUserAsync(userId, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
// Only the plays that count as plays are aggregated. The last activity of a track is the end of its most recent play, or the last
// progress update while that play is still in progress.
List<PlayedTrackAggregate> aggregates = [.. getRecordsResult.Value
.Where(record => MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()))
.GroupBy(record => new { record.TrackId, record.LibraryId, record.AlbumId, record.ArtistId })
.Select(group => new PlayedTrackAggregate(
group.Key.TrackId,
group.Key.LibraryId,
group.Key.AlbumId,
group.Key.ArtistId,
group.Max(record => record.EndedOnUtc ?? record.UpdatedOnUtc ?? record.CreatedOnUtc),
group.Count(),
group.Count(record => record.Status == PlaybackRecordStatus.Completed),
group.Sum(record => record.ListenedDurationMilliseconds)))
.OrderByDescending(aggregate => aggregate.PlayCount)
.ThenByDescending(aggregate => aggregate.ListenedDurationMilliseconds)
.ThenByDescending(aggregate => aggregate.LastActivityOnUtc)
.ThenBy(aggregate => aggregate.TrackId)];
return await ToResponsePageAsync(aggregates, query.PaginationData, userId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Pages the aggregated tracks, resolves their display data, and converts them to the response of the query.
/// </summary>
/// <param name="aggregates">The aggregated tracks, already ordered for this query.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the requested page of played tracks, or an error.</returns>
private async Task<Result<PaginatedResponse<PlayedTrackResponse>>> ToResponsePageAsync(
List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData, Guid userId, CancellationToken cancellationToken)
{
PaginatedResultDto<PlayedTrackAggregate> page = Paginate(aggregates, paginationData);
Result<List<PlayedTrackDto>> getDtosResult = await ToPlayedTrackDtosAsync(page.Data, userId, cancellationToken).ConfigureAwait(false);
if (getDtosResult.IsFailure)
return getDtosResult.Errors;
return Result.From(new PaginatedResultDto<PlayedTrackDto>
{
Data = getDtosResult.Value,
CurrentPage = page.CurrentPage,
PerPage = page.PerPage,
Count = page.Count,
NumberOfPages = page.NumberOfPages
}.ToResponses());
}
/// <summary>
/// Applies the requested pagination to the ordered aggregated tracks.
/// </summary>
/// <param name="aggregates">The ordered aggregated tracks.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <returns>The requested page of aggregated tracks.</returns>
private static PaginatedResultDto<PlayedTrackAggregate> Paginate(List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData)
{
if (paginationData is null)
return new PaginatedResultDto<PlayedTrackAggregate>
{
Data = aggregates,
CurrentPage = 1,
PerPage = aggregates.Count,
Count = aggregates.Count,
NumberOfPages = 1
};
int count = aggregates.Count;
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
List<PlayedTrackAggregate> page = [.. aggregates
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)];
return new PaginatedResultDto<PlayedTrackAggregate>
{
Data = page,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Resolves the display data of the tracks of <paramref name="aggregates"/> for the libraries the user can access, and builds their DTOs.
/// </summary>
/// <param name="aggregates">The aggregated tracks of the requested page.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the played tracks, with blank display data for missing or inaccessible tracks, or an error.</returns>
private async Task<Result<List<PlayedTrackDto>>> ToPlayedTrackDtosAsync(IReadOnlyList<PlayedTrackAggregate> aggregates, Guid userId, CancellationToken cancellationToken)
{
if (aggregates.Count == 0)
return new List<PlayedTrackDto>();
// The access decision only needs the library Id that the play record already carries, so it is made once per distinct library before any
// track or artwork is loaded. Display data from a library the user cannot access is never read.
Dictionary<Guid, bool> libraryAccess = [];
foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
List<Guid> accessibleTrackIds = [.. aggregates
.Where(aggregate => libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.TrackId)
.Distinct()];
Dictionary<Guid, TrackEntity> tracks = [];
if (accessibleTrackIds.Count > 0)
{
Result<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository.GetByIdsAsync(accessibleTrackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getTracksResult.IsFailure)
return getTracksResult.Errors;
tracks = getTracksResult.Value.ToDictionary(track => track.Id);
}
List<Guid> albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
Dictionary<Guid, string?> albumCovers = [];
if (albumIds.Count > 0)
{
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
albumCovers = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(
group => group.Key,
group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
}
List<PlayedTrackDto> playedTracks = [];
foreach (PlayedTrackAggregate aggregate in aggregates)
{
if (libraryAccess[aggregate.LibraryId] && tracks.TryGetValue(aggregate.TrackId, out TrackEntity? foundTrack) && foundTrack.LibraryId == aggregate.LibraryId)
playedTracks.Add(new PlayedTrackDto(
aggregate.TrackId,
aggregate.LibraryId,
aggregate.AlbumId,
aggregate.ArtistId,
foundTrack.Title,
foundTrack.Album?.Title,
foundTrack.Album?.Artist?.Name,
albumCovers.TryGetValue(foundTrack.AlbumId, out string? coverFileName) ? coverFileName : null,
aggregate.LastActivityOnUtc,
aggregate.PlayCount,
aggregate.CompletedPlayCount,
aggregate.ListenedDurationMilliseconds));
else // Keep the row so the play counts stay accurate, but blank the display data of a missing or inaccessible track.
playedTracks.Add(new PlayedTrackDto(
aggregate.TrackId,
aggregate.LibraryId,
aggregate.AlbumId,
aggregate.ArtistId,
null,
null,
null,
null,
aggregate.LastActivityOnUtc,
aggregate.PlayCount,
aggregate.CompletedPlayCount,
aggregate.ListenedDurationMilliseconds));
}
return playedTracks;
}
/// <summary>
/// The aggregated counted plays of one track in one library.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="LastActivityOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationMilliseconds">The duration the user listened to the track, over all of its counted plays, in milliseconds.</param>
private sealed record PlayedTrackAggregate(
Guid TrackId,
Guid LibraryId,
Guid AlbumId,
Guid ArtistId,
DateTime LastActivityOnUtc,
int PlayCount,
int CompletedPlayCount,
long ListenedDurationMilliseconds
);
}
@@ -1,12 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMusicPlayStatistics;
/// <summary>
/// Query for getting the listening statistics of the current user.
/// </summary>
[DebuggerDisplay("Music play statistics")]
public record GetMusicPlayStatisticsQuery() : IQuery;
@@ -1,79 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMusicPlayStatistics;
/// <summary>
/// Handler for the query to get the listening statistics of the current user.
/// </summary>
public class GetMusicPlayStatisticsQueryHandler : IQueryHandler<GetMusicPlayStatisticsQuery, Result<MusicPlayStatisticsResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
public GetMusicPlayStatisticsQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
}
/// <summary>
/// Handles the query to get the listening statistics of the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the listening statistics of the current user, or an error message.
/// </returns>
public async Task<Result<MusicPlayStatisticsResponse>> HandleAsync(GetMusicPlayStatisticsQuery query, CancellationToken cancellationToken)
{
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
Result<IReadOnlyList<MusicPlayRecordEntity>> getRecordsResult = await _unitOfWork.MusicPlayRecordRepository.GetForUserAsync(userId, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
IReadOnlyList<MusicPlayRecordEntity> records = getRecordsResult.Value;
// The total listening time includes the listened duration of every recorded play, including the plays that do not count.
long totalListeningDurationMilliseconds = records.Sum(record => record.ListenedDurationMilliseconds);
// A play counts when it completed or when it reached the threshold. An in-progress play that already reached the threshold is counted,
// so the counted total need not equal the completed and stopped plays together.
int totalPlayCount = records.Count(record => MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()));
int completedPlayCount = records.Count(record => record.Status == PlaybackRecordStatus.Completed);
int stoppedPlayCount = records.Count(record => record.Status == PlaybackRecordStatus.Stopped && MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()));
double completionRate = totalPlayCount == 0 ? 0 : (double)completedPlayCount / totalPlayCount;
return new MusicPlayStatisticsDto(
totalListeningDurationMilliseconds,
totalPlayCount,
completedPlayCount,
stoppedPlayCount,
completionRate).ToResponse();
}
}
@@ -1,15 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
/// <summary>
/// Query for getting a recorded play of a track by the current user.
/// </summary>
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
[DebuggerDisplay("PlayRecordId: {PlayRecordId}")]
public record GetPlayRecordQuery(
string? PlayRecordId
) : IQuery;
@@ -1,78 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
/// <summary>
/// Handler for the query to get a recorded play of a track by the current user.
/// </summary>
public class GetPlayRecordQueryHandler : IQueryHandler<GetPlayRecordQuery, Result<PlayRecordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetPlayRecordQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetPlayRecordQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetPlayRecordQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IValidator<GetPlayRecordQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get a recorded play of a track by the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the requested <see cref="PlayRecordResponse"/>, or an error message.
/// </returns>
public async Task<Result<PlayRecordResponse>> HandleAsync(GetPlayRecordQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifier is a non-empty Guid before this point.
Guid playRecordId = Guid.Parse(query.PlayRecordId!);
// The record is read without tracking and scoped to the current user, so a record of another user is indistinguishable from a missing one.
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
.GetByIdForUserAsync(playRecordId, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPlayRecordResult.IsFailure)
return getPlayRecordResult.Errors;
if (getPlayRecordResult.Value is null)
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
return getPlayRecordResult.Value.ToResponse();
}
}
@@ -1,29 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
/// <summary>
/// Validates the needed validation rules for <see cref="GetPlayRecordQuery"/>.
/// </summary>
public class GetPlayRecordQueryValidator : AbstractValidator<GetPlayRecordQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPlayRecordQueryValidator"/> class.
/// </summary>
public GetPlayRecordQueryValidator()
{
RuleFor(query => query.PlayRecordId)
.NotEmpty()
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
RuleFor(query => query.PlayRecordId)
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
.When(query => query.PlayRecordId is not null && query.PlayRecordId.Length > 0)
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
}
}
@@ -1,16 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Pagination;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
/// <summary>
/// Query for getting the recently played tracks of the current user, from the most recently played.
/// </summary>
/// <param name="PaginationData">The object containing the requested pagination data, or <see langword="null"/> to return every matching track.</param>
[DebuggerDisplay("PaginationData: {PaginationData}")]
public record GetRecentlyPlayedQuery(
PaginationDataDto? PaginationData
) : IQuery;
@@ -1,254 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
/// <summary>
/// Handler for the query to get the recently played tracks of the current user.
/// </summary>
public class GetRecentlyPlayedQueryHandler : IQueryHandler<GetRecentlyPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
public GetRecentlyPlayedQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the recently played tracks of the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the requested page of recently played tracks, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<PlayedTrackResponse>>> HandleAsync(GetRecentlyPlayedQuery query, CancellationToken cancellationToken)
{
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
Result<IReadOnlyList<MusicPlayRecordEntity>> getRecordsResult = await _unitOfWork.MusicPlayRecordRepository.GetForUserAsync(userId, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
// Only the plays that count as plays are aggregated. The last activity of a track is the end of its most recent play, or the last
// progress update while that play is still in progress.
List<PlayedTrackAggregate> aggregates = [.. getRecordsResult.Value
.Where(record => MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()))
.GroupBy(record => new { record.TrackId, record.LibraryId, record.AlbumId, record.ArtistId })
.Select(group => new PlayedTrackAggregate(
group.Key.TrackId,
group.Key.LibraryId,
group.Key.AlbumId,
group.Key.ArtistId,
group.Max(record => record.EndedOnUtc ?? record.UpdatedOnUtc ?? record.CreatedOnUtc),
group.Count(),
group.Count(record => record.Status == PlaybackRecordStatus.Completed),
group.Sum(record => record.ListenedDurationMilliseconds)))
.OrderByDescending(aggregate => aggregate.LastActivityOnUtc)
.ThenBy(aggregate => aggregate.TrackId)];
return await ToResponsePageAsync(aggregates, query.PaginationData, userId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Pages the aggregated tracks, resolves their display data, and converts them to the response of the query.
/// </summary>
/// <param name="aggregates">The aggregated tracks, already ordered for this query.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the requested page of played tracks, or an error.</returns>
private async Task<Result<PaginatedResponse<PlayedTrackResponse>>> ToResponsePageAsync(
List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData, Guid userId, CancellationToken cancellationToken)
{
PaginatedResultDto<PlayedTrackAggregate> page = Paginate(aggregates, paginationData);
Result<List<PlayedTrackDto>> getDtosResult = await ToPlayedTrackDtosAsync(page.Data, userId, cancellationToken).ConfigureAwait(false);
if (getDtosResult.IsFailure)
return getDtosResult.Errors;
return Result.From(new PaginatedResultDto<PlayedTrackDto>
{
Data = getDtosResult.Value,
CurrentPage = page.CurrentPage,
PerPage = page.PerPage,
Count = page.Count,
NumberOfPages = page.NumberOfPages
}.ToResponses());
}
/// <summary>
/// Applies the requested pagination to the ordered aggregated tracks.
/// </summary>
/// <param name="aggregates">The ordered aggregated tracks.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <returns>The requested page of aggregated tracks.</returns>
private static PaginatedResultDto<PlayedTrackAggregate> Paginate(List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData)
{
if (paginationData is null)
return new PaginatedResultDto<PlayedTrackAggregate>
{
Data = aggregates,
CurrentPage = 1,
PerPage = aggregates.Count,
Count = aggregates.Count,
NumberOfPages = 1
};
int count = aggregates.Count;
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
List<PlayedTrackAggregate> page = [.. aggregates
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)];
return new PaginatedResultDto<PlayedTrackAggregate>
{
Data = page,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Resolves the display data of the tracks of <paramref name="aggregates"/> for the libraries the user can access, and builds their DTOs.
/// </summary>
/// <param name="aggregates">The aggregated tracks of the requested page.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the played tracks, with blank display data for missing or inaccessible tracks, or an error.</returns>
private async Task<Result<List<PlayedTrackDto>>> ToPlayedTrackDtosAsync(IReadOnlyList<PlayedTrackAggregate> aggregates, Guid userId, CancellationToken cancellationToken)
{
if (aggregates.Count == 0)
return new List<PlayedTrackDto>();
// The access decision only needs the library Id that the play record already carries, so it is made once per distinct library before any
// track or artwork is loaded. Display data from a library the user cannot access is never read.
Dictionary<Guid, bool> libraryAccess = [];
foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
List<Guid> accessibleTrackIds = [.. aggregates
.Where(aggregate => libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.TrackId)
.Distinct()];
Dictionary<Guid, TrackEntity> tracks = [];
if (accessibleTrackIds.Count > 0)
{
Result<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository.GetByIdsAsync(accessibleTrackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getTracksResult.IsFailure)
return getTracksResult.Errors;
tracks = getTracksResult.Value.ToDictionary(track => track.Id);
}
List<Guid> albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
Dictionary<Guid, string?> albumCovers = [];
if (albumIds.Count > 0)
{
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
albumCovers = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(
group => group.Key,
group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
}
List<PlayedTrackDto> playedTracks = [];
foreach (PlayedTrackAggregate aggregate in aggregates)
{
if (libraryAccess[aggregate.LibraryId] && tracks.TryGetValue(aggregate.TrackId, out TrackEntity? foundTrack) && foundTrack.LibraryId == aggregate.LibraryId)
playedTracks.Add(new PlayedTrackDto(
aggregate.TrackId,
aggregate.LibraryId,
aggregate.AlbumId,
aggregate.ArtistId,
foundTrack.Title,
foundTrack.Album?.Title,
foundTrack.Album?.Artist?.Name,
albumCovers.TryGetValue(foundTrack.AlbumId, out string? coverFileName) ? coverFileName : null,
aggregate.LastActivityOnUtc,
aggregate.PlayCount,
aggregate.CompletedPlayCount,
aggregate.ListenedDurationMilliseconds));
else // Keep the row so the play counts stay accurate, but blank the display data of a missing or inaccessible track.
playedTracks.Add(new PlayedTrackDto(
aggregate.TrackId,
aggregate.LibraryId,
aggregate.AlbumId,
aggregate.ArtistId,
null,
null,
null,
null,
aggregate.LastActivityOnUtc,
aggregate.PlayCount,
aggregate.CompletedPlayCount,
aggregate.ListenedDurationMilliseconds));
}
return playedTracks;
}
/// <summary>
/// The aggregated counted plays of one track in one library.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="LastActivityOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationMilliseconds">The duration the user listened to the track, over all of its counted plays, in milliseconds.</param>
private sealed record PlayedTrackAggregate(
Guid TrackId,
Guid LibraryId,
Guid AlbumId,
Guid ArtistId,
DateTime LastActivityOnUtc,
int PlayCount,
int CompletedPlayCount,
long ListenedDurationMilliseconds
);
}
@@ -1,16 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request to report that a play of a track by the current user reached its end.
/// </summary>
/// <param name="PositionInSeconds">The last position reported by the player, in seconds. Required.</param>
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds. Required.</param>
[DebuggerDisplay("PositionInSeconds: {PositionInSeconds}; ListenedDurationInSeconds: {ListenedDurationInSeconds}")]
public sealed record CompletePlayRequest(
double? PositionInSeconds,
double? ListenedDurationInSeconds
);
@@ -1,16 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request for getting a window of the most played tracks of the current user.
/// </summary>
/// <param name="CurrentPage">The one based page of tracks to return. Optional; defaults to 1 when a page size is provided.</param>
/// <param name="PerPage">The number of tracks per page. Optional; defaults to 50 when a page is provided. When both pagination parameters are omitted, every matching track is returned.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetMostPlayedRequest(
int? CurrentPage,
int? PerPage
);
@@ -1,16 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request for getting a window of the recently played tracks of the current user.
/// </summary>
/// <param name="CurrentPage">The one based page of tracks to return. Optional; defaults to 1 when a page size is provided.</param>
/// <param name="PerPage">The number of tracks per page. Optional; defaults to 50 when a page is provided. When both pagination parameters are omitted, every matching track is returned.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetRecentlyPlayedRequest(
int? CurrentPage,
int? PerPage
);
@@ -1,16 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request to report the progress of a play of a track by the current user.
/// </summary>
/// <param name="PositionInSeconds">The last position reported by the player, in seconds. Required.</param>
/// <param name="ListenedDurationInSeconds">The duration the user has listened to, in seconds. Required.</param>
[DebuggerDisplay("PositionInSeconds: {PositionInSeconds}; ListenedDurationInSeconds: {ListenedDurationInSeconds}")]
public sealed record ReportPlayProgressRequest(
double? PositionInSeconds,
double? ListenedDurationInSeconds
);
@@ -1,16 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request to report that a play of a track by the current user stopped before the track completed.
/// </summary>
/// <param name="PositionInSeconds">The last position reported by the player, in seconds. Required.</param>
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds. Required.</param>
[DebuggerDisplay("PositionInSeconds: {PositionInSeconds}; ListenedDurationInSeconds: {ListenedDurationInSeconds}")]
public sealed record StopPlayRequest(
double? PositionInSeconds,
double? ListenedDurationInSeconds
);
@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents the listening statistics of the current user.
/// </summary>
/// <param name="TotalListeningDurationInSeconds">The total duration the user listened to, over every recorded play, in seconds.</param>
/// <param name="TotalPlayCount">The number of recorded plays that count as plays. An in-progress play counts once it reaches the threshold, so this total can exceed the completed and stopped plays together.</param>
/// <param name="CompletedPlayCount">The number of recorded plays that completed.</param>
/// <param name="StoppedPlayCount">The number of recorded plays that stopped before the track completed and count as plays.</param>
/// <param name="CompletionRate">The fraction of the plays that count as plays that completed, between 0 and 1, or 0 when there is no counted play.</param>
[DebuggerDisplay("TotalPlayCount: {TotalPlayCount}; CompletedPlayCount: {CompletedPlayCount}")]
public sealed record MusicPlayStatisticsResponse(
double TotalListeningDurationInSeconds,
int TotalPlayCount,
int CompletedPlayCount,
int StoppedPlayCount,
double CompletionRate
);
@@ -1,36 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a recorded play of a track by the current user.
/// </summary>
/// <param name="Id">The Id of the play record.</param>
/// <param name="TrackId">The Id of the track that was played.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="Status">The state of the recorded play.</param>
/// <param name="LastPositionInSeconds">The last position reported by the player, in seconds.</param>
/// <param name="ListenedDurationInSeconds">The duration the user has listened to, in seconds.</param>
/// <param name="StartedOnUtc">The date and time when the play started.</param>
/// <param name="EndedOnUtc">The date and time when the play completed or stopped, if it has ended.</param>
/// <param name="UpdatedOnUtc">The date and time when the play record was last updated, if applicable.</param>
[DebuggerDisplay("Id: {Id}; TrackId: {TrackId}; Status: {Status}")]
public sealed record PlayRecordResponse(
Guid Id,
Guid TrackId,
Guid LibraryId,
Guid AlbumId,
Guid ArtistId,
PlaybackRecordStatus Status,
double LastPositionInSeconds,
double ListenedDurationInSeconds,
DateTime StartedOnUtc,
DateTime? EndedOnUtc,
DateTime? UpdatedOnUtc
);
@@ -1,37 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a track of the listening statistics of the current user, together with its aggregated play counts.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="Title">The title of the track, if it still exists and the user can access its library.</param>
/// <param name="AlbumTitle">The title of the album that contains the track, if it still exists and the user can access its library.</param>
/// <param name="ArtistName">The name of the artist that produced the track, if it still exists and the user can access its library.</param>
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
/// <param name="LastPlayedOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationInSeconds">The duration the user listened to the track, over all of its counted plays, in seconds.</param>
[DebuggerDisplay("TrackId: {TrackId}; PlayCount: {PlayCount}")]
public sealed record PlayedTrackResponse(
Guid TrackId,
Guid LibraryId,
Guid AlbumId,
Guid ArtistId,
string? Title,
string? AlbumTitle,
string? ArtistName,
string? CoverPath,
DateTime LastPlayedOnUtc,
int PlayCount,
int CompletedPlayCount,
double ListenedDurationInSeconds
);
@@ -1,95 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="MusicPlayRecordEntity"/> entity.
/// </summary>
public class MusicPlayRecordConfiguration : IEntityTypeConfiguration<MusicPlayRecordEntity>
{
/// <summary>
/// Configures the <see cref="MusicPlayRecordEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<MusicPlayRecordEntity> builder)
{
builder.ToTable("MusicPlayRecords");
builder.HasKey(playRecord => playRecord.Id);
builder.Property(playRecord => playRecord.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(playRecord => playRecord.UserId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(playRecord => playRecord.TrackId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(playRecord => playRecord.LibraryId)
.IsRequired()
.HasColumnOrder(3);
builder.Property(playRecord => playRecord.AlbumId)
.IsRequired()
.HasColumnOrder(4);
builder.Property(playRecord => playRecord.ArtistId)
.IsRequired()
.HasColumnOrder(5);
builder.Property(playRecord => playRecord.Status)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(6);
builder.Property(playRecord => playRecord.LastPositionMilliseconds)
.IsRequired()
.HasColumnOrder(7);
builder.Property(playRecord => playRecord.ListenedDurationMilliseconds)
.IsRequired()
.HasColumnOrder(8);
builder.Property(playRecord => playRecord.EndedOnUtc)
.HasColumnOrder(9);
// The version is the optimistic concurrency token: every update increments it, and an update whose loaded version no longer matches
// the stored one affects no row and fails, instead of reverting a play that another report already completed or stopped.
builder.Property(playRecord => playRecord.Version)
.IsRequired()
.IsConcurrencyToken()
.HasColumnOrder(10);
// Audit.
builder.Property(playRecord => playRecord.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(11);
builder.Property(playRecord => playRecord.CreatedBy)
.IsRequired()
.HasColumnOrder(12);
builder.Property(playRecord => playRecord.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(13);
builder.Property(playRecord => playRecord.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(14);
// The referenced entities are kept by Id only, without foreign keys, so a play survives the deletion of the track it references and the
// statistics of the listening history still count it.
// Enables the chronological reads of the plays of a user, which the statistics are built from.
builder.HasIndex(playRecord => new { playRecord.UserId, playRecord.CreatedOnUtc });
// Enables the reads of the plays of a track, which the per track statistics are built from.
builder.HasIndex(playRecord => playRecord.TrackId);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,57 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class DropsMusicPlayRecords : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MusicPlayRecords");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "MusicPlayRecords",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
TrackId = table.Column<Guid>(type: "TEXT", nullable: false),
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
AlbumId = table.Column<Guid>(type: "TEXT", nullable: false),
ArtistId = table.Column<Guid>(type: "TEXT", nullable: false),
Status = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
LastPositionMilliseconds = table.Column<long>(type: "INTEGER", nullable: false),
ListenedDurationMilliseconds = table.Column<long>(type: "INTEGER", nullable: false),
EndedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
Version = table.Column<long>(type: "INTEGER", nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_MusicPlayRecords", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_MusicPlayRecords_TrackId",
table: "MusicPlayRecords",
column: "TrackId");
migrationBuilder.CreateIndex(
name: "IX_MusicPlayRecords_UserId_CreatedOnUtc",
table: "MusicPlayRecords",
columns: new[] { "UserId", "CreatedOnUtc" });
}
}
}
@@ -1184,80 +1184,6 @@ namespace Lumina.DataAccess.Common.Migrations
b.ToTable("MusicLibraryScanItemMetadata", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("AlbumId")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid>("ArtistId")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(12);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<DateTime?>("EndedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<long>("LastPositionMilliseconds")
.HasColumnType("INTEGER")
.HasColumnOrder(7);
b.Property<Guid>("LibraryId")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<long>("ListenedDurationMilliseconds")
.HasColumnType("INTEGER")
.HasColumnOrder(8);
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<Guid>("TrackId")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(14);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(13);
b.Property<Guid>("UserId")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<long>("Version")
.IsConcurrencyToken()
.HasColumnType("INTEGER")
.HasColumnOrder(10);
b.HasKey("Id");
b.HasIndex("TrackId");
b.HasIndex("UserId", "CreatedOnUtc");
b.ToTable("MusicPlayRecords", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b =>
{
b.Property<Guid>("Id")
@@ -1,135 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
/// <summary>
/// Repository for recorded music plays.
/// </summary>
internal sealed class MusicPlayRecordRepository : IMusicPlayRecordRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="MusicPlayRecordRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public MusicPlayRecordRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets the play record identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>, if it exists.
/// </summary>
/// <param name="id">The Id of the play record to get.</param>
/// <param name="userId">The Id of the user the play record must belong to.</param>
/// <param name="shouldTrackEntities">Whether the retrieved record should be tracked by the persistence medium, so that changes to it can be saved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the play record identified by <paramref name="id"/> and owned by <paramref name="userId"/>,
/// <see langword="null"/> when no such record exists, or an error.
/// </returns>
public async Task<Result<MusicPlayRecordEntity?>> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a record that
// belongs to another user in the first place.
IQueryable<MusicPlayRecordEntity> query = _luminaDbContext.MusicPlayRecords
.Where(playRecord => playRecord.Id == id && playRecord.UserId == userId);
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the play records of the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose play records are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the play records of the user, or an error.</returns>
public async Task<Result<IReadOnlyList<MusicPlayRecordEntity>>> GetForUserAsync(Guid userId, CancellationToken cancellationToken)
{
// The user is part of the query, so the storage medium never returns the plays of another user.
List<MusicPlayRecordEntity> playRecords = await _luminaDbContext.MusicPlayRecords
.AsNoTracking()
.Where(playRecord => playRecord.UserId == userId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From<IReadOnlyList<MusicPlayRecordEntity>>(playRecords);
}
/// <summary>
/// Adds a new play record.
/// </summary>
/// <param name="data">The play record to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(MusicPlayRecordEntity data, CancellationToken cancellationToken)
{
bool doesPlayRecordExist = await _luminaDbContext.MusicPlayRecords
.AnyAsync(playRecord => playRecord.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (doesPlayRecordExist)
return DomainErrors.MusicPlayHistory.MusicPlayRecordAlreadyExists;
_luminaDbContext.MusicPlayRecords.Add(data);
return Result.Created;
}
/// <summary>
/// Updates the play record of the user identified by <paramref name="userId"/>, when the record belongs to that user and still holds the
/// version it was read with.
/// </summary>
/// <param name="data">The play record whose editable values are applied to the stored record.</param>
/// <param name="userId">The Id of the user the play record must belong to.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
public async Task<Result<Updated>> UpdateForUserAsync(MusicPlayRecordEntity data, Guid userId, CancellationToken cancellationToken)
{
// The user is part of both the tracked and the stored lookup, so a future caller can never update a record that belongs to another
// user merely by knowing its Id.
MusicPlayRecordEntity? foundPlayRecord = _luminaDbContext.MusicPlayRecords.Local
.FirstOrDefault(playRecord => playRecord.Id == data.Id && playRecord.UserId == userId)
?? await _luminaDbContext.MusicPlayRecords
.FirstOrDefaultAsync(playRecord => playRecord.Id == data.Id && playRecord.UserId == userId, cancellationToken).ConfigureAwait(false);
if (foundPlayRecord is null)
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
// A report that carries the values that are already stored is a no-op: writing it would bump the version for nothing, and a
// concurrent stop or complete that read the same version could then fail for a report that changed no data.
bool hasEditableChanges = foundPlayRecord.Status != data.Status ||
foundPlayRecord.LastPositionMilliseconds != data.LastPositionMilliseconds ||
foundPlayRecord.ListenedDurationMilliseconds != data.ListenedDurationMilliseconds ||
foundPlayRecord.EndedOnUtc != data.EndedOnUtc;
if (!hasEditableChanges)
return Result.Updated;
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
// The version is captured before the copy and incremented after it, so the update is only applied when the row still holds the
// version the report read; a later progress report can therefore never overwrite a completed or stopped play.
Guid storedUserId = foundPlayRecord.UserId;
Guid trackId = foundPlayRecord.TrackId;
Guid libraryId = foundPlayRecord.LibraryId;
Guid albumId = foundPlayRecord.AlbumId;
Guid artistId = foundPlayRecord.ArtistId;
long version = foundPlayRecord.Version;
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundPlayRecord, data);
foundPlayRecord.UserId = storedUserId;
foundPlayRecord.TrackId = trackId;
foundPlayRecord.LibraryId = libraryId;
foundPlayRecord.AlbumId = albumId;
foundPlayRecord.ArtistId = artistId;
foundPlayRecord.Version = version + 1;
return Result.Updated;
}
}
@@ -53,7 +53,6 @@ public class LuminaDbContext : DbContext
public virtual DbSet<ScheduledJobEntity> ScheduledJobs { get; set; } = null!;
public virtual DbSet<ScheduledJobExecutionEntity> ScheduledJobExecutions { get; set; } = null!;
public virtual DbSet<SchedulerDisplayPreferencesEntity> SchedulerDisplayPreferences { get; set; } = null!;
public virtual DbSet<MusicPlayRecordEntity> MusicPlayRecords { get; set; } = null!;
public virtual DbSet<PlaylistEntity> Playlists { get; set; } = null!;
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
public virtual DbSet<FavoriteEntity> Favorites { get; set; } = null!;
@@ -70,7 +70,6 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private IThemeRepository? _themeRepository;
private IUserRepository? _userRepository;
private IUserSettingsRepository? _userSettingsRepository;
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
private IPlaylistRepository? _playlistRepository;
private IFavoriteRepository? _favoriteRepository;
private IMediaConsumptionRecordRepository? _mediaConsumptionRecordRepository;
@@ -386,18 +385,6 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
/// <summary>
/// Gets the music play record repository.
/// </summary>
public IMusicPlayRecordRepository MusicPlayRecordRepository
{
get
{
_musicPlayRecordRepository ??= new MusicPlayRecordRepository(_luminaDbContext);
return _musicPlayRecordRepository;
}
}
/// <summary>
/// Gets the playlist repository.
/// </summary>
@@ -1,22 +0,0 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
/// <summary>
/// Enumeration for the states of a recorded playback.
/// </summary>
public enum PlaybackRecordStatus
{
/// <summary>
/// The playback was recorded as started and has not ended yet.
/// </summary>
InProgress,
/// <summary>
/// The playback reached the end of the media item.
/// </summary>
Completed,
/// <summary>
/// The playback ended before the media item completed.
/// </summary>
Stopped,
}
@@ -1,28 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
#endregion
namespace Lumina.Domain.Common.Errors;
/// <summary>
/// Music play history error types.
/// </summary>
public static partial class Errors
{
public static class MusicPlayHistory
{
public static Error MusicPlayRecordNotFound => Error.NotFound(description: nameof(MusicPlayRecordNotFound));
public static Error MusicPlayRecordAlreadyExists => Error.Conflict(description: nameof(MusicPlayRecordAlreadyExists));
public static Error PlayRecordIdCannotBeEmpty => Error.Validation(description: nameof(PlayRecordIdCannotBeEmpty));
public static Error PlaybackPositionCannotBeNull => Error.Validation(description: nameof(PlaybackPositionCannotBeNull));
public static Error PlaybackPositionMustBeNonNegative => Error.Validation(description: nameof(PlaybackPositionMustBeNonNegative));
public static Error PlaybackPositionIsOutOfRange => Error.Validation(description: nameof(PlaybackPositionIsOutOfRange));
public static Error ListenedDurationCannotBeNull => Error.Validation(description: nameof(ListenedDurationCannotBeNull));
public static Error ListenedDurationMustBeNonNegative => Error.Validation(description: nameof(ListenedDurationMustBeNonNegative));
public static Error ListenedDurationIsOutOfRange => Error.Validation(description: nameof(ListenedDurationIsOutOfRange));
public static Error PlayIsNotInProgress => Error.Conflict(description: nameof(PlayIsNotInProgress));
public static Error ListenedDurationCannotDecrease => Error.Validation(description: nameof(ListenedDurationCannotDecrease));
public static Error InProgressPlayCannotHaveEndTime => Error.Validation(description: nameof(InProgressPlayCannotHaveEndTime));
public static Error EndedPlayMustHaveEndTime => Error.Validation(description: nameof(EndedPlayMustHaveEndTime));
}
}
@@ -1,51 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
/// <summary>
/// Value Object for the Id of an album, duplicated from the AudioLibrary bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class AlbumId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="AlbumId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private AlbumId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="AlbumId"/> class.
/// </summary>
/// <returns>The created <see cref="AlbumId"/> instance.</returns>
public static AlbumId CreateUnique()
{
return new AlbumId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="AlbumId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="AlbumId"/> instance.</param>
/// <returns>The created <see cref="AlbumId"/> instance.</returns>
public static AlbumId Create(Guid value)
{
return new AlbumId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -1,51 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
/// <summary>
/// Value Object for the Id of an artist, duplicated from the AudioLibrary bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class ArtistId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="ArtistId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private ArtistId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="ArtistId"/> class.
/// </summary>
/// <returns>The created <see cref="ArtistId"/> instance.</returns>
public static ArtistId CreateUnique()
{
return new ArtistId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="ArtistId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="ArtistId"/> instance.</param>
/// <returns>The created <see cref="ArtistId"/> instance.</returns>
public static ArtistId Create(Guid value)
{
return new ArtistId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -1,51 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
/// <summary>
/// Value Object for the Id of a track, duplicated from the AudioLibrary bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class TrackId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="TrackId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private TrackId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="TrackId"/> class.
/// </summary>
/// <returns>The created <see cref="TrackId"/> instance.</returns>
public static TrackId CreateUnique()
{
return new TrackId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="TrackId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="TrackId"/> instance.</param>
/// <returns>The created <see cref="TrackId"/> instance.</returns>
public static TrackId Create(Guid value)
{
return new TrackId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -1,51 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
/// <summary>
/// Value Object for the Id of a media library, duplicated from the LibraryManagement bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class LibraryId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private LibraryId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId CreateUnique()
{
return new LibraryId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="LibraryId"/> instance.</param>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId Create(Guid value)
{
return new LibraryId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -1,51 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
/// <summary>
/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class UserId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private UserId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId CreateUnique()
{
return new UserId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="UserId"/> instance.</param>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId Create(Guid value)
{
return new UserId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -1,31 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.Events;
/// <summary>
/// Domain event raised when a music play completes.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="MusicPlayRecordId">The unique identifier of the play record.</param>
/// <param name="UserId">The unique identifier of the user that owns the play record.</param>
/// <param name="TrackId">The unique identifier of the track that completed.</param>
/// <param name="Position">The last position reported by the player.</param>
/// <param name="ListenedDuration">The duration that the user listened to.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("MusicPlayRecordId: {MusicPlayRecordId.Value}; TrackId: {TrackId.Value}")]
public record MusicPlayCompletedDomainEvent(
Guid Id,
MusicPlayRecordId MusicPlayRecordId,
UserId UserId,
TrackId TrackId,
MusicPlayPosition Position,
TimeSpan ListenedDuration,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -1,31 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.Events;
/// <summary>
/// Domain event raised when a player reports the progress of a music play.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="MusicPlayRecordId">The unique identifier of the play record.</param>
/// <param name="UserId">The unique identifier of the user that owns the play record.</param>
/// <param name="TrackId">The unique identifier of the track that is being played.</param>
/// <param name="Position">The last position reported by the player.</param>
/// <param name="ListenedDuration">The duration that the user has listened to so far.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("MusicPlayRecordId: {MusicPlayRecordId.Value}; Position: {Position.Offset}")]
public record MusicPlayProgressedDomainEvent(
Guid Id,
MusicPlayRecordId MusicPlayRecordId,
UserId UserId,
TrackId TrackId,
MusicPlayPosition Position,
TimeSpan ListenedDuration,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -1,34 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.Events;
/// <summary>
/// Domain event raised when a music play starts.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="MusicPlayRecordId">The unique identifier of the play record.</param>
/// <param name="UserId">The unique identifier of the user that started the play.</param>
/// <param name="TrackId">The unique identifier of the track that was played.</param>
/// <param name="LibraryId">The unique identifier of the media library that contains the track.</param>
/// <param name="AlbumId">The unique identifier of the album that contains the track.</param>
/// <param name="ArtistId">The unique identifier of the artist that produced the track.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("MusicPlayRecordId: {MusicPlayRecordId.Value}; TrackId: {TrackId.Value}")]
public record MusicPlayStartedDomainEvent(
Guid Id,
MusicPlayRecordId MusicPlayRecordId,
UserId UserId,
TrackId TrackId,
LibraryId LibraryId,
AlbumId AlbumId,
ArtistId ArtistId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -1,31 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.Events;
/// <summary>
/// Domain event raised when a music play stops before the track completes.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="MusicPlayRecordId">The unique identifier of the play record.</param>
/// <param name="UserId">The unique identifier of the user that owns the play record.</param>
/// <param name="TrackId">The unique identifier of the track that was stopped.</param>
/// <param name="Position">The last position reported by the player.</param>
/// <param name="ListenedDuration">The duration that the user listened to.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("MusicPlayRecordId: {MusicPlayRecordId.Value}; TrackId: {TrackId.Value}")]
public record MusicPlayStoppedDomainEvent(
Guid Id,
MusicPlayRecordId MusicPlayRecordId,
UserId UserId,
TrackId TrackId,
MusicPlayPosition Position,
TimeSpan ListenedDuration,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -1,319 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
/// <summary>
/// Aggregate root for a recorded music play.
/// </summary>
/// <remarks>
/// A record is created when a player starts a track and is updated by the progress, completion and stop reports of that player. It logs what was
/// played, how far it reached and how long the user listened, so statistics and recommendations can be built from it. The record is created when the
/// play starts, so <see cref="CreatedOnUtc"/> is the start time.
/// </remarks>
[DebuggerDisplay("Id: {Id.Value}; TrackId: {TrackId.Value}; Status: {Status}")]
public sealed class MusicPlayRecord : AggregateRoot<MusicPlayRecordId>
{
/// <summary>
/// The minimum number of seconds a user must listen to a track for the play to count, unless the play completed first.
/// </summary>
private const int MINIMUM_COUNTED_LISTENED_DURATION_SECONDS = 30;
/// <summary>
/// Gets the object representing the unique identifier of the user that started the play.
/// </summary>
public UserId UserId { get; private set; }
/// <summary>
/// Gets the Id of the track that was played.
/// </summary>
public TrackId TrackId { get; private set; }
/// <summary>
/// Gets the Id of the media library that contains the track.
/// </summary>
public LibraryId LibraryId { get; private set; }
/// <summary>
/// Gets the Id of the album that contains the track.
/// </summary>
public AlbumId AlbumId { get; private set; }
/// <summary>
/// Gets the Id of the artist that produced the track.
/// </summary>
public ArtistId ArtistId { get; private set; }
/// <summary>
/// Gets the state of the recorded play.
/// </summary>
public PlaybackRecordStatus Status { get; private set; }
/// <summary>
/// Gets the last position reported by the player.
/// </summary>
public MusicPlayPosition LastPosition { get; private set; }
/// <summary>
/// Gets the duration that the user has listened to.
/// </summary>
public TimeSpan ListenedDuration { get; private set; }
/// <summary>
/// Gets the date and time when the play completed or stopped, if it has ended.
/// </summary>
public Optional<DateTime> EndedOnUtc { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="MusicPlayRecord"/> class.
/// </summary>
/// <param name="id">The object representing the unique identifier of the play record.</param>
/// <param name="userId">The object representing the unique identifier of the user that started the play.</param>
/// <param name="trackId">The Id of the track that was played.</param>
/// <param name="libraryId">The Id of the media library that contains the track.</param>
/// <param name="albumId">The Id of the album that contains the track.</param>
/// <param name="artistId">The Id of the artist that produced the track.</param>
/// <param name="status">The state of the recorded play.</param>
/// <param name="lastPosition">The last position reported by the player.</param>
/// <param name="listenedDuration">The duration that the user has listened to.</param>
/// <param name="endedOnUtc">The date and time when the play completed or stopped, if it has ended.</param>
/// <param name="createdOnUtc">The date and time when the play started.</param>
/// <param name="updatedOnUtc">The date and time when the play record was last updated.</param>
private MusicPlayRecord(
MusicPlayRecordId id,
UserId userId,
TrackId trackId,
LibraryId libraryId,
AlbumId albumId,
ArtistId artistId,
PlaybackRecordStatus status,
MusicPlayPosition lastPosition,
TimeSpan listenedDuration,
Optional<DateTime> endedOnUtc,
DateTime createdOnUtc,
Optional<DateTime> updatedOnUtc) : base(id)
{
Id = id;
UserId = userId;
TrackId = trackId;
LibraryId = libraryId;
AlbumId = albumId;
ArtistId = artistId;
Status = status;
LastPosition = lastPosition;
ListenedDuration = listenedDuration;
EndedOnUtc = endedOnUtc;
CreatedOnUtc = createdOnUtc;
UpdatedOnUtc = updatedOnUtc;
}
/// <summary>
/// Creates a new play record for a track that started playing.
/// </summary>
/// <param name="userId">The object representing the unique identifier of the user that started the play.</param>
/// <param name="trackId">The Id of the track that was played.</param>
/// <param name="libraryId">The Id of the media library that contains the track.</param>
/// <param name="albumId">The Id of the album that contains the track.</param>
/// <param name="artistId">The Id of the artist that produced the track.</param>
/// <returns>The created <see cref="MusicPlayRecord"/> instance.</returns>
public static MusicPlayRecord Create(
UserId userId,
TrackId trackId,
LibraryId libraryId,
AlbumId albumId,
ArtistId artistId)
{
DateTime occurredOnUtc = DateTime.UtcNow;
MusicPlayRecord playRecord = new(
MusicPlayRecordId.CreateUnique(),
userId,
trackId,
libraryId,
albumId,
artistId,
PlaybackRecordStatus.InProgress,
MusicPlayPosition.Zero,
TimeSpan.Zero,
Optional<DateTime>.None(),
occurredOnUtc,
Optional<DateTime>.None());
playRecord._domainEvents.Add(new MusicPlayStartedDomainEvent(
Guid.NewGuid(),
playRecord.Id,
userId,
trackId,
libraryId,
albumId,
artistId,
occurredOnUtc));
return playRecord;
}
/// <summary>
/// Creates a new instance of the <see cref="MusicPlayRecord"/> class, with pre-existing data.
/// </summary>
/// <param name="id">The object representing the unique identifier of the play record.</param>
/// <param name="userId">The object representing the unique identifier of the user that started the play.</param>
/// <param name="trackId">The Id of the track that was played.</param>
/// <param name="libraryId">The Id of the media library that contains the track.</param>
/// <param name="albumId">The Id of the album that contains the track.</param>
/// <param name="artistId">The Id of the artist that produced the track.</param>
/// <param name="status">The state of the recorded play.</param>
/// <param name="lastPosition">The last position reported by the player.</param>
/// <param name="listenedDuration">The duration that the user has listened to.</param>
/// <param name="endedOnUtc">The date and time when the play completed or stopped, if it has ended.</param>
/// <param name="createdOnUtc">The date and time when the play started.</param>
/// <param name="updatedOnUtc">The date and time when the play record was last updated.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="MusicPlayRecord"/>, or an error message.
/// </returns>
public static Result<MusicPlayRecord> Create(
MusicPlayRecordId id,
UserId userId,
TrackId trackId,
LibraryId libraryId,
AlbumId albumId,
ArtistId artistId,
PlaybackRecordStatus status,
MusicPlayPosition lastPosition,
TimeSpan listenedDuration,
Optional<DateTime> endedOnUtc,
DateTime createdOnUtc,
Optional<DateTime> updatedOnUtc)
{
if (status == PlaybackRecordStatus.InProgress && endedOnUtc.HasValue)
return Errors.MusicPlayHistory.InProgressPlayCannotHaveEndTime;
if (status != PlaybackRecordStatus.InProgress && !endedOnUtc.HasValue)
return Errors.MusicPlayHistory.EndedPlayMustHaveEndTime;
return new MusicPlayRecord(
id,
userId,
trackId,
libraryId,
albumId,
artistId,
status,
lastPosition,
listenedDuration,
endedOnUtc,
createdOnUtc,
updatedOnUtc);
}
/// <summary>
/// Determines whether a play with the provided <paramref name="status"/> and <paramref name="listenedDuration"/> counts as a play for the listening statistics.
/// </summary>
/// <param name="status">The state of the recorded play.</param>
/// <param name="listenedDuration">The duration that the user has listened to.</param>
/// <returns><see langword="true"/> when the play counts, <see langword="false"/> otherwise.</returns>
public static bool DoesCountAsPlay(PlaybackRecordStatus status, TimeSpan listenedDuration)
{
return status == PlaybackRecordStatus.Completed || listenedDuration.TotalSeconds >= MINIMUM_COUNTED_LISTENED_DURATION_SECONDS;
}
/// <summary>
/// Updates the last reported position and the listened duration of an in-progress play.
/// </summary>
/// <param name="position">The last position reported by the player.</param>
/// <param name="listenedDuration">The duration that the user has listened to.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
public Result<Updated> ReportProgress(MusicPlayPosition position, TimeSpan listenedDuration)
{
if (Status != PlaybackRecordStatus.InProgress)
return Errors.MusicPlayHistory.PlayIsNotInProgress;
if (listenedDuration < ListenedDuration)
return Errors.MusicPlayHistory.ListenedDurationCannotDecrease;
if (LastPosition.Offset == position.Offset && ListenedDuration == listenedDuration)
return Result.Updated;
LastPosition = position;
ListenedDuration = listenedDuration;
DateTime occurredOnUtc = DateTime.UtcNow;
UpdatedOnUtc = Optional<DateTime>.Some(occurredOnUtc);
_domainEvents.Add(new MusicPlayProgressedDomainEvent(
Guid.NewGuid(),
Id,
UserId,
TrackId,
position,
listenedDuration,
occurredOnUtc));
return Result.Updated;
}
/// <summary>
/// Marks an in-progress play as completed.
/// </summary>
/// <param name="position">The last position reported by the player.</param>
/// <param name="listenedDuration">The duration that the user listened to.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
public Result<Updated> Complete(MusicPlayPosition position, TimeSpan listenedDuration)
{
if (Status != PlaybackRecordStatus.InProgress)
return Errors.MusicPlayHistory.PlayIsNotInProgress;
if (listenedDuration < ListenedDuration)
return Errors.MusicPlayHistory.ListenedDurationCannotDecrease;
LastPosition = position;
ListenedDuration = listenedDuration;
Status = PlaybackRecordStatus.Completed;
DateTime occurredOnUtc = DateTime.UtcNow;
EndedOnUtc = Optional<DateTime>.Some(occurredOnUtc);
UpdatedOnUtc = Optional<DateTime>.Some(occurredOnUtc);
_domainEvents.Add(new MusicPlayCompletedDomainEvent(
Guid.NewGuid(),
Id,
UserId,
TrackId,
position,
listenedDuration,
occurredOnUtc));
return Result.Updated;
}
/// <summary>
/// Marks an in-progress play as stopped before the track completed.
/// </summary>
/// <param name="position">The last position reported by the player.</param>
/// <param name="listenedDuration">The duration that the user listened to.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
public Result<Updated> Stop(MusicPlayPosition position, TimeSpan listenedDuration)
{
if (Status != PlaybackRecordStatus.InProgress)
return Errors.MusicPlayHistory.PlayIsNotInProgress;
if (listenedDuration < ListenedDuration)
return Errors.MusicPlayHistory.ListenedDurationCannotDecrease;
LastPosition = position;
ListenedDuration = listenedDuration;
Status = PlaybackRecordStatus.Stopped;
DateTime occurredOnUtc = DateTime.UtcNow;
EndedOnUtc = Optional<DateTime>.Some(occurredOnUtc);
UpdatedOnUtc = Optional<DateTime>.Some(occurredOnUtc);
_domainEvents.Add(new MusicPlayStoppedDomainEvent(
Guid.NewGuid(),
Id,
UserId,
TrackId,
position,
listenedDuration,
occurredOnUtc));
return Result.Updated;
}
}
@@ -1,51 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the last position reported by a player for a music play record.
/// </summary>
public sealed class MusicPlayPosition : ValueObject
{
/// <summary>
/// Gets the position reported by the player.
/// </summary>
public TimeSpan Offset { get; }
/// <summary>
/// Gets the position at the very start of a track.
/// </summary>
public static MusicPlayPosition Zero { get; } = new(TimeSpan.Zero);
/// <summary>
/// Initializes a new instance of the <see cref="MusicPlayPosition"/> class.
/// </summary>
/// <param name="offset">The position reported by the player.</param>
private MusicPlayPosition(TimeSpan offset)
{
Offset = offset;
}
/// <summary>
/// Creates a new instance of the <see cref="MusicPlayPosition"/> class.
/// </summary>
/// <param name="offset">The position reported by the player.</param>
/// <returns>The created <see cref="MusicPlayPosition"/> instance.</returns>
public static MusicPlayPosition Create(TimeSpan offset)
{
return new MusicPlayPosition(offset);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Offset;
}
}
@@ -1,51 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a music play record.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class MusicPlayRecordId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="MusicPlayRecordId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private MusicPlayRecordId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="MusicPlayRecordId"/> class.
/// </summary>
/// <returns>The created <see cref="MusicPlayRecordId"/> instance.</returns>
public static MusicPlayRecordId CreateUnique()
{
return new MusicPlayRecordId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="MusicPlayRecordId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="MusicPlayRecordId"/> instance.</param>
/// <returns>The created <see cref="MusicPlayRecordId"/> instance.</returns>
public static MusicPlayRecordId Create(Guid value)
{
return new MusicPlayRecordId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -1,19 +0,0 @@
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";
}
}
@@ -1,17 +0,0 @@
namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
/// <summary>
/// Class for the collection of the music play statistics routes of the API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the music play statistics of the current user.
/// </summary>
public static class PlayStatistics
{
public const string GET_RECENTLY_PLAYED = "/users/me/music-play-history/recently-played";
public const string GET_MOST_PLAYED = "/users/me/music-play-history/most-played";
public const string GET_MUSIC_PLAY_STATISTICS = "/users/me/music-play-history/statistics";
}
}
@@ -1,58 +0,0 @@
#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);
}
}
@@ -1,129 +0,0 @@
#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"
}
);
}
}
@@ -1,63 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Contracts.Responses.Common;
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.GetMostPlayed;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/most-played</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetMostPlayedEndpoint : BaseEndpoint<GetMostPlayedRequest, IResult>
{
private readonly IQueryHandler<GetMostPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> _getMostPlayedQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedEndpoint"/> class.
/// </summary>
/// <param name="getMostPlayedQueryHandler">Injected service for handling get most played queries.</param>
public GetMostPlayedEndpoint(IQueryHandler<GetMostPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> getMostPlayedQueryHandler)
{
_getMostPlayedQueryHandler = getMostPlayedQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.PlayStatistics.GET_MOST_PLAYED);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the most played tracks of the current user.
/// </summary>
/// <param name="request">The request containing the optional page bounds.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetMostPlayedRequest request, CancellationToken cancellationToken)
{
// The 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["Vary"] = "Authorization";
Result<PaginatedResponse<PlayedTrackResponse>> result = await _getMostPlayedQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -1,116 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetMostPlayed;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetMostPlayedEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMostPlayedEndpointSummary : Summary<GetMostPlayedEndpoint, GetMostPlayedRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedEndpointSummary"/> class.
/// </summary>
public GetMostPlayedEndpointSummary()
{
Summary = "Gets the most played tracks of the current user.";
Description = "Gets the tracks the current user played the most, from the most played. Only the plays that count as plays are included: a play counts when it completed or when the listened duration reached 30 seconds. Each track is returned once, with its counted plays, its completed plays, the duration the user listened to it and its last activity time. A track deleted from its library keeps its row, without display data. The response is private to the authenticated user.";
ExampleRequest = new GetMostPlayedRequest(CurrentPage: 1, PerPage: 50);
RequestParam(request => request.CurrentPage, "The one based page of tracks to return. Optional. Defaults to 1.");
RequestParam(request => request.PerPage, "The number of tracks per page. Optional. Defaults to 50. When both pagination parameters are omitted, every matching track is returned.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.Data, "The most played tracks of the requested page, ordered by counted plays, listened duration, last activity, and track Id.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.CurrentPage, "The current page number.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.PerPage, "The number of tracks retrieved per page.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.Count, "The total number of tracks that match the filters.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.NumberOfPages, "The total number of pages.");
ResponseParam<PlayedTrackResponse>(response => response.TrackId, "The Id of the track.");
ResponseParam<PlayedTrackResponse>(response => response.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayedTrackResponse>(response => response.Title, "The title of the track, if it still exists and the user can access its library.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumTitle, "The title of the album that contains the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistName, "The name of the artist that produced the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.CoverPath, "The path of the cover art of the album, if available.");
ResponseParam<PlayedTrackResponse>(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play.");
ResponseParam<PlayedTrackResponse>(response => response.PlayCount, "The number of plays of the track that count as plays.");
ResponseParam<PlayedTrackResponse>(response => response.CompletedPlayCount, "The number of plays of the track that completed.");
ResponseParam<PlayedTrackResponse>(response => response.ListenedDurationInSeconds, "The duration the user listened to the track, over all of its counted plays, in seconds.");
Response(200, "The requested page of most played tracks is returned.",
example: new PaginatedResponse<PlayedTrackResponse>
{
Data =
[
new PlayedTrackResponse(
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"),
Title: "Time",
AlbumTitle: "The Dark Side of the Moon",
ArtistName: "Pink Floyd",
CoverPath: "covers/dark-side-of-the-moon.jpg",
LastPlayedOnUtc: new DateTime(2026, 10, 20, 18, 30, 0, DateTimeKind.Utc),
PlayCount: 12,
CompletedPlayCount: 9,
ListenedDurationInSeconds: 4230.5)
],
CurrentPage = 1,
PerPage = 50,
Count = 1,
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/music-play-history/most-played"
},
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/most-played"
},
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/most-played"
}
}
);
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/music-play-history/most-played",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
}
}
@@ -1,60 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMusicPlayStatistics;
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.GetMusicPlayStatistics;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/statistics</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetMusicPlayStatisticsEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetMusicPlayStatisticsQuery, Result<MusicPlayStatisticsResponse>> _getMusicPlayStatisticsQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsEndpoint"/> class.
/// </summary>
/// <param name="getMusicPlayStatisticsQueryHandler">Injected service for handling get music play statistics queries.</param>
public GetMusicPlayStatisticsEndpoint(IQueryHandler<GetMusicPlayStatisticsQuery, Result<MusicPlayStatisticsResponse>> getMusicPlayStatisticsQueryHandler)
{
_getMusicPlayStatisticsQueryHandler = getMusicPlayStatisticsQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.PlayStatistics.GET_MUSIC_PLAY_STATISTICS);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the listening statistics of 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 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["Vary"] = "Authorization";
Result<MusicPlayStatisticsResponse> result = await _getMusicPlayStatisticsQueryHandler.HandleAsync(new GetMusicPlayStatisticsQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -1,80 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetMusicPlayStatistics;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetMusicPlayStatisticsEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMusicPlayStatisticsEndpointSummary : Summary<GetMusicPlayStatisticsEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsEndpointSummary"/> class.
/// </summary>
public GetMusicPlayStatisticsEndpointSummary()
{
Summary = "Gets the listening statistics of the current user.";
Description = "Gets the total listening time, the number of plays that count as plays, the number of completed plays, the number of stopped plays that count and the completion rate of the current user. A play counts when it completed or when the listened duration reached 30 seconds, and the total listening time includes the listened duration of every recorded play. A play that is still in progress counts once it reaches the threshold, so the counted total can exceed the completed and stopped plays together. The statistics are aggregated over the plays of the authenticated user, so the response is private to that user.";
ResponseParam<MusicPlayStatisticsResponse>(response => response.TotalListeningDurationInSeconds, "The total duration the user listened to, over every recorded play, in seconds.");
ResponseParam<MusicPlayStatisticsResponse>(response => response.TotalPlayCount, "The number of recorded plays that count as plays. It includes an in-progress play that has already reached the threshold, so it need not equal the completed and stopped plays together.");
ResponseParam<MusicPlayStatisticsResponse>(response => response.CompletedPlayCount, "The number of recorded plays that completed.");
ResponseParam<MusicPlayStatisticsResponse>(response => response.StoppedPlayCount, "The number of recorded plays that stopped before the track completed and count as plays.");
ResponseParam<MusicPlayStatisticsResponse>(response => response.CompletionRate, "The fraction of the counted plays that completed, between 0 and 1, or 0 when there is no counted play.");
Response(200, "The listening statistics of the current user are returned.",
example: new MusicPlayStatisticsResponse(
TotalListeningDurationInSeconds: 93840.5,
TotalPlayCount: 512,
CompletedPlayCount: 388,
StoppedPlayCount: 124,
CompletionRate: 0.7578125)
);
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/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/music-play-history/statistics"
},
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/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/music-play-history/statistics",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
}
}
@@ -1,62 +0,0 @@
#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);
}
}
@@ -1,117 +0,0 @@
#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"
}
);
}
}
@@ -1,63 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Contracts.Responses.Common;
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.GetRecentlyPlayed;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/recently-played</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetRecentlyPlayedEndpoint : BaseEndpoint<GetRecentlyPlayedRequest, IResult>
{
private readonly IQueryHandler<GetRecentlyPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> _getRecentlyPlayedQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedEndpoint"/> class.
/// </summary>
/// <param name="getRecentlyPlayedQueryHandler">Injected service for handling get recently played queries.</param>
public GetRecentlyPlayedEndpoint(IQueryHandler<GetRecentlyPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> getRecentlyPlayedQueryHandler)
{
_getRecentlyPlayedQueryHandler = getRecentlyPlayedQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.PlayStatistics.GET_RECENTLY_PLAYED);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the recently played tracks of the current user.
/// </summary>
/// <param name="request">The request containing the optional page bounds.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetRecentlyPlayedRequest request, CancellationToken cancellationToken)
{
// The 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["Vary"] = "Authorization";
Result<PaginatedResponse<PlayedTrackResponse>> result = await _getRecentlyPlayedQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -1,116 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetRecentlyPlayed;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetRecentlyPlayedEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRecentlyPlayedEndpointSummary : Summary<GetRecentlyPlayedEndpoint, GetRecentlyPlayedRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedEndpointSummary"/> class.
/// </summary>
public GetRecentlyPlayedEndpointSummary()
{
Summary = "Gets the recently played tracks of the current user.";
Description = "Gets the tracks the current user played recently, from the most recently played. Only the plays that count as plays are included: a play counts when it completed or when the listened duration reached 30 seconds. Each track is returned once, with its last activity time, its counted plays, its completed plays and the duration the user listened to it. A track deleted from its library keeps its row, without display data. The response is private to the authenticated user.";
ExampleRequest = new GetRecentlyPlayedRequest(CurrentPage: 1, PerPage: 50);
RequestParam(request => request.CurrentPage, "The one based page of tracks to return. Optional. Defaults to 1.");
RequestParam(request => request.PerPage, "The number of tracks per page. Optional. Defaults to 50. When both pagination parameters are omitted, every matching track is returned.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.Data, "The recently played tracks of the requested page, from the most recently played.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.CurrentPage, "The current page number.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.PerPage, "The number of tracks retrieved per page.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.Count, "The total number of tracks that match the filters.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.NumberOfPages, "The total number of pages.");
ResponseParam<PlayedTrackResponse>(response => response.TrackId, "The Id of the track.");
ResponseParam<PlayedTrackResponse>(response => response.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayedTrackResponse>(response => response.Title, "The title of the track, if it still exists and the user can access its library.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumTitle, "The title of the album that contains the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistName, "The name of the artist that produced the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.CoverPath, "The path of the cover art of the album, if available.");
ResponseParam<PlayedTrackResponse>(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play.");
ResponseParam<PlayedTrackResponse>(response => response.PlayCount, "The number of plays of the track that count as plays.");
ResponseParam<PlayedTrackResponse>(response => response.CompletedPlayCount, "The number of plays of the track that completed.");
ResponseParam<PlayedTrackResponse>(response => response.ListenedDurationInSeconds, "The duration the user listened to the track, over all of its counted plays, in seconds.");
Response(200, "The requested page of recently played tracks is returned.",
example: new PaginatedResponse<PlayedTrackResponse>
{
Data =
[
new PlayedTrackResponse(
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"),
Title: "Time",
AlbumTitle: "The Dark Side of the Moon",
ArtistName: "Pink Floyd",
CoverPath: "covers/dark-side-of-the-moon.jpg",
LastPlayedOnUtc: new DateTime(2026, 10, 20, 18, 30, 0, DateTimeKind.Utc),
PlayCount: 12,
CompletedPlayCount: 9,
ListenedDurationInSeconds: 4230.5)
],
CurrentPage = 1,
PerPage = 50,
Count = 1,
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/music-play-history/recently-played"
},
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/recently-played"
},
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/recently-played"
}
}
);
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/music-play-history/recently-played",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
}
}
@@ -1,58 +0,0 @@
#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);
}
}
@@ -1,129 +0,0 @@
#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"
}
);
}
}
@@ -1,58 +0,0 @@
#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);
}
}
@@ -1,144 +0,0 @@
#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"
}
);
}
}
@@ -1,58 +0,0 @@
#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);
}
}
@@ -1,129 +0,0 @@
#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"
}
);
}
}
@@ -48,7 +48,7 @@ public class LuminaDbContextTests : IDisposable
// Assert
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
Assert.Equal(67, tableNames.Length);
Assert.Equal(66, tableNames.Length);
Assert.Contains("Books", tableNames);
Assert.Contains("Users", tableNames);
Assert.Contains("UserSettings", tableNames);
@@ -108,7 +108,7 @@ public class LuminaDbContextTests : IDisposable
Assert.Contains("AlbumContributors", tableNames);
Assert.Contains("MusicArtwork", tableNames);
Assert.Contains("MusicLibraryScanItemMetadata", tableNames);
Assert.Contains("MusicPlayRecords", tableNames);
Assert.DoesNotContain("MusicPlayRecords", tableNames);
Assert.Contains("MediaConsumptionRecords", tableNames);
Assert.Contains("MediaResumePoints", tableNames);
Assert.Contains("Playlists", tableNames);