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
);
}