Adds playback preferences and auto-persisted playback state to user settings

This commit is contained in:
BinaryAlley committed 2026-10-15 21:09:38 +03:00
1 parent aab36dcd29
commit dd76309ded
81 files changed
+6102 -173

No files matched your search

@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Diagnostics;
#endregion
@@ -65,6 +66,41 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
/// </summary>
public bool ShouldPreserveBookStyles { get; set; }
/// <summary>
/// Gets or sets whether the player keeps downloading a track while playback is paused, or not, up to the entire file.
/// </summary>
public bool ShouldKeepDownloadingWhilePaused { get; set; } = true;
/// <summary>
/// Gets or sets whether the player continues playback at the end of an album or artist, or not.
/// </summary>
public bool ShouldAutoplay { get; set; } = true;
/// <summary>
/// Gets or sets whether the player transitions between consecutive tracks without a gap, or not.
/// </summary>
public bool IsGaplessPlaybackEnabled { get; set; } = true;
/// <summary>
/// Gets or sets the way ReplayGain normalization is applied to the tracks the user plays.
/// </summary>
public ReplayGainMode ReplayGainMode { get; set; }
/// <summary>
/// Gets or sets the quality cap applied to the audio the server normalizes for the user.
/// </summary>
public PlaybackStreamingQuality StreamingQuality { get; set; }
/// <summary>
/// Gets or sets the last volume the player reported for the user. Written automatically by the player, and not part of the settings the user edits.
/// </summary>
public double Volume { get; set; } = 1.0;
/// <summary>
/// Gets or sets the last mute state the player reported for the user. Written automatically by the player, and not part of the settings the user edits.
/// </summary>
public bool IsMuted { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
using Lumina.Contracts.Requests.UsersManagement.Settings;
#endregion
namespace Lumina.Application.Common.Mapping.UsersManagement.Users;
/// <summary>
/// Extension methods for converting <see cref="UpdatePlaybackStateRequest"/>.
/// </summary>
public static class UpdatePlaybackStateRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="UpdatePlaybackStateCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static UpdatePlaybackStateCommand ToCommand(this UpdatePlaybackStateRequest request)
{
return new UpdatePlaybackStateCommand(
request.Volume,
request.IsMuted
);
}
}
@@ -25,7 +25,12 @@ public static class UpdateUserSettingsRequestMapping
request.ShouldAggregateMetadataWhenMissing,
request.ShouldAggregateArtworkWhenMissing,
request.ShouldRenderPdfAsImages,
request.ShouldPreserveBookStyles
request.ShouldPreserveBookStyles,
request.ShouldKeepDownloadingWhilePaused,
request.ShouldAutoplay,
request.IsGaplessPlaybackEnabled,
request.ReplayGainMode,
request.StreamingQuality
);
}
}
@@ -33,7 +33,14 @@ public static class UserSettingsEntityMapping
repositoryEntity.ShouldAggregateMetadataWhenMissing,
repositoryEntity.ShouldAggregateArtworkWhenMissing,
repositoryEntity.ShouldRenderPdfAsImages,
repositoryEntity.ShouldPreserveBookStyles
repositoryEntity.ShouldPreserveBookStyles,
repositoryEntity.ShouldKeepDownloadingWhilePaused,
repositoryEntity.ShouldAutoplay,
repositoryEntity.IsGaplessPlaybackEnabled,
repositoryEntity.ReplayGainMode,
repositoryEntity.StreamingQuality,
repositoryEntity.Volume,
repositoryEntity.IsMuted
);
}
@@ -53,7 +60,12 @@ public static class UserSettingsEntityMapping
repositoryEntity.ShouldAggregateMetadataWhenMissing,
repositoryEntity.ShouldAggregateArtworkWhenMissing,
repositoryEntity.ShouldRenderPdfAsImages,
repositoryEntity.ShouldPreserveBookStyles
repositoryEntity.ShouldPreserveBookStyles,
repositoryEntity.ShouldKeepDownloadingWhilePaused,
repositoryEntity.ShouldAutoplay,
repositoryEntity.IsGaplessPlaybackEnabled,
repositoryEntity.ReplayGainMode,
repositoryEntity.StreamingQuality
);
}
}
@@ -29,7 +29,14 @@ public static class UserSettingsMapping
ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing,
ShouldAggregateArtworkWhenMissing = domainEntity.ShouldAggregateArtworkWhenMissing,
ShouldRenderPdfAsImages = domainEntity.ShouldRenderPdfAsImages,
ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles
ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles,
ShouldKeepDownloadingWhilePaused = domainEntity.ShouldKeepDownloadingWhilePaused,
ShouldAutoplay = domainEntity.ShouldAutoplay,
IsGaplessPlaybackEnabled = domainEntity.IsGaplessPlaybackEnabled,
ReplayGainMode = domainEntity.ReplayGainMode,
StreamingQuality = domainEntity.StreamingQuality,
Volume = domainEntity.Volume,
IsMuted = domainEntity.IsMuted
};
}
@@ -49,7 +56,12 @@ public static class UserSettingsMapping
domainEntity.ShouldAggregateMetadataWhenMissing,
domainEntity.ShouldAggregateArtworkWhenMissing,
domainEntity.ShouldRenderPdfAsImages,
domainEntity.ShouldPreserveBookStyles
domainEntity.ShouldPreserveBookStyles,
domainEntity.ShouldKeepDownloadingWhilePaused,
domainEntity.ShouldAutoplay,
domainEntity.IsGaplessPlaybackEnabled,
domainEntity.ReplayGainMode,
domainEntity.StreamingQuality
);
}
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
/// <summary>
/// Command for updating the playback state the player reports for the current user automatically. These values are not part of the settings the user edits.
/// </summary>
/// <param name="Volume">The last volume the player reported, as a value between 0 and 1.</param>
/// <param name="IsMuted">The last mute state the player reported.</param>
public record UpdatePlaybackStateCommand(
double? Volume,
bool? IsMuted
) : ICommand;
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.UsersManagement.Users;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
/// <summary>
/// Handler for the command to update the playback state the player reports for the current user automatically.
/// </summary>
public class UpdatePlaybackStateCommandHandler : ICommandHandler<UpdatePlaybackStateCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdatePlaybackStateCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaybackStateCommandHandler"/> class.
/// </summary>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdatePlaybackStateCommandHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<UpdatePlaybackStateCommand> validator)
{
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to update the playback state the player reports for the current user automatically.
/// </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(UpdatePlaybackStateCommand 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 Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Get the existing settings of the current user, if any.
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getSettingsResult.IsFailure)
return getSettingsResult.Errors;
if (getSettingsResult.Value is null)
{
// Create the settings of the current user, since they are not stored yet, keeping the settings the user edits by hand at their default.
Result<UserSettings> createSettingsResult = UserSettings.Create(UserId.Create(userId));
if (createSettingsResult.IsFailure)
return createSettingsResult.Errors;
Result<Updated> applyResult = createSettingsResult.Value.UpdatePlaybackState(command.Volume!.Value, command.IsMuted!.Value);
if (applyResult.IsFailure)
return applyResult.Errors;
Result<Created> insertResult = await _unitOfWork.UserSettingsRepository.InsertAsync(createSettingsResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
return insertResult.Errors;
}
else
{
// Update the stored settings of the current user.
Result<UserSettings> toDomainEntityResult = getSettingsResult.Value.ToDomainEntity();
if (toDomainEntityResult.IsFailure)
return toDomainEntityResult.Errors;
Result<Updated> applyResult = toDomainEntityResult.Value.UpdatePlaybackState(command.Volume!.Value, command.IsMuted!.Value);
if (applyResult.IsFailure)
return applyResult.Errors;
Result<Updated> updateResult = await _unitOfWork.UserSettingsRepository.UpdateAsync(toDomainEntityResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
}
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Updated;
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdatePlaybackStateCommand"/>.
/// </summary>
public class UpdatePlaybackStateCommandValidator : AbstractValidator<UpdatePlaybackStateCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaybackStateCommandValidator"/> class.
/// </summary>
public UpdatePlaybackStateCommandValidator()
{
RuleFor(command => command.Volume)
.NotNull()
.WithError(Errors.UserSettings.VolumeCannotBeNull);
RuleFor(command => command.Volume)
.Must(volume => volume is null || (volume.Value >= 0.0 && volume.Value <= 1.0))
.WithError(Errors.UserSettings.VolumeMustBeBetweenZeroAndOne);
RuleFor(command => command.IsMuted)
.NotNull()
.WithError(Errors.UserSettings.IsMutedCannotBeNull);
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
#endregion
namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
@@ -15,6 +16,11 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
/// <param name="ShouldAggregateArtworkWhenMissing">Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not.</param>
/// <param name="ShouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
/// <param name="ShouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
/// <param name="ShouldKeepDownloadingWhilePaused">Whether the player keeps downloading a track while playback is paused, or not.</param>
/// <param name="ShouldAutoplay">Whether the player continues playback at the end of an album or artist, or not.</param>
/// <param name="IsGaplessPlaybackEnabled">Whether the player transitions between consecutive tracks without a gap, or not.</param>
/// <param name="ReplayGainMode">The way ReplayGain normalization is applied to the tracks the user plays.</param>
/// <param name="StreamingQuality">The quality cap applied to the audio the server normalizes for the user.</param>
public record UpdateUserSettingsCommand(
bool IsPaginationEnabled,
int ItemsPerPage,
@@ -23,5 +29,10 @@ public record UpdateUserSettingsCommand(
bool ShouldAggregateMetadataWhenMissing,
bool ShouldAggregateArtworkWhenMissing,
bool ShouldRenderPdfAsImages,
bool ShouldPreserveBookStyles
bool ShouldPreserveBookStyles,
bool? ShouldKeepDownloadingWhilePaused,
bool? ShouldAutoplay,
bool? IsGaplessPlaybackEnabled,
ReplayGainMode? ReplayGainMode,
PlaybackStreamingQuality? StreamingQuality
) : ICommand;
@@ -66,20 +66,16 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
if (getSettingsResult.Value is null)
{
// Create the settings of the current user, since they are not stored yet.
Result<UserSettings> createSettingsResult = UserSettings.Create(
UserId.Create(userId),
command.IsPaginationEnabled,
command.ItemsPerPage,
command.ShouldIgnoreThePrefixForAlphaPicker,
command.IsThemeCachingEnabled,
command.ShouldAggregateMetadataWhenMissing,
command.ShouldAggregateArtworkWhenMissing,
command.ShouldRenderPdfAsImages,
command.ShouldPreserveBookStyles);
// Create the settings of the current user, since they are not stored yet. The playback state the player reports automatically is left
// at its default, because this command only carries the settings the user edits by hand.
Result<UserSettings> createSettingsResult = UserSettings.Create(UserId.Create(userId));
if (createSettingsResult.IsFailure)
return createSettingsResult.Errors;
Result<Updated> applySettingsResult = ApplySettings(createSettingsResult.Value, command);
if (applySettingsResult.IsFailure)
return applySettingsResult.Errors;
Result<Created> insertResult = await _unitOfWork.UserSettingsRepository.InsertAsync(createSettingsResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
return insertResult.Errors;
@@ -91,15 +87,7 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
if (toDomainEntityResult.IsFailure)
return toDomainEntityResult.Errors;
Result<Updated> updateSettingsResult = toDomainEntityResult.Value.UpdateSettings(
command.IsPaginationEnabled,
command.ItemsPerPage,
command.ShouldIgnoreThePrefixForAlphaPicker,
command.IsThemeCachingEnabled,
command.ShouldAggregateMetadataWhenMissing,
command.ShouldAggregateArtworkWhenMissing,
command.ShouldRenderPdfAsImages,
command.ShouldPreserveBookStyles);
Result<Updated> updateSettingsResult = ApplySettings(toDomainEntityResult.Value, command);
if (updateSettingsResult.IsFailure)
return updateSettingsResult.Errors;
@@ -114,4 +102,28 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
return Result.Updated;
}
/// <summary>
/// Applies the values carried by <paramref name="command"/> to the settings of the current user.
/// </summary>
/// <param name="settings">The settings of the current user to update.</param>
/// <param name="command">The command carrying the new values of the settings.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
private static Result<Updated> ApplySettings(UserSettings settings, UpdateUserSettingsCommand command)
{
return settings.UpdateSettings(
command.IsPaginationEnabled,
command.ItemsPerPage,
command.ShouldIgnoreThePrefixForAlphaPicker,
command.IsThemeCachingEnabled,
command.ShouldAggregateMetadataWhenMissing,
command.ShouldAggregateArtworkWhenMissing,
command.ShouldRenderPdfAsImages,
command.ShouldPreserveBookStyles,
command.ShouldKeepDownloadingWhilePaused!.Value,
command.ShouldAutoplay!.Value,
command.IsGaplessPlaybackEnabled!.Value,
command.ReplayGainMode!.Value,
command.StreamingQuality!.Value);
}
}
@@ -19,5 +19,35 @@ public class UpdateUserSettingsCommandValidator : AbstractValidator<UpdateUserSe
RuleFor(command => command.ItemsPerPage)
.GreaterThan(0)
.WithError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero);
RuleFor(command => command.ShouldKeepDownloadingWhilePaused)
.NotNull()
.WithError(Errors.UserSettings.ShouldKeepDownloadingWhilePausedCannotBeNull);
RuleFor(command => command.ShouldAutoplay)
.NotNull()
.WithError(Errors.UserSettings.ShouldAutoplayCannotBeNull);
RuleFor(command => command.IsGaplessPlaybackEnabled)
.NotNull()
.WithError(Errors.UserSettings.IsGaplessPlaybackEnabledCannotBeNull);
RuleFor(command => command.ReplayGainMode)
.NotNull()
.WithError(Errors.UserSettings.ReplayGainModeCannotBeNull);
RuleFor(command => command.ReplayGainMode)
.IsInEnum()
.WithError(Errors.UserSettings.InvalidReplayGainMode)
.When(command => command.ReplayGainMode is not null);
RuleFor(command => command.StreamingQuality)
.NotNull()
.WithError(Errors.UserSettings.StreamingQualityCannotBeNull);
RuleFor(command => command.StreamingQuality)
.IsInEnum()
.WithError(Errors.UserSettings.InvalidStreamingQuality)
.When(command => command.StreamingQuality is not null);
}
}
@@ -0,0 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState;
/// <summary>
/// Query for getting the playback state the player reported for the current user automatically. These values are not part of the settings the user edits.
/// </summary>
public record GetPlaybackStateQuery : IQuery;
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState;
/// <summary>
/// Handler for the query to get the playback state the player reported for the current user automatically.
/// </summary>
public class GetPlaybackStateQueryHandler : IQueryHandler<GetPlaybackStateQuery, Result<PlaybackStateResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackStateQueryHandler"/> class.
/// </summary>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetPlaybackStateQueryHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to get the playback state the player reported for the current user automatically.
/// </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 a successfully retrieved <see cref="PlaybackStateResponse"/>, or an error message.
/// </returns>
public async Task<Result<PlaybackStateResponse>> HandleAsync(GetPlaybackStateQuery query, CancellationToken cancellationToken)
{
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Get the settings of the current user from the repository.
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getSettingsResult.IsFailure)
return getSettingsResult.Errors;
// When no settings are stored for the current user yet, return the default playback state.
if (getSettingsResult.Value is null)
{
Result<UserSettings> defaultSettingsResult = UserSettings.Create();
if (defaultSettingsResult.IsFailure)
return defaultSettingsResult.Errors;
return new PlaybackStateResponse(defaultSettingsResult.Value.Volume, defaultSettingsResult.Value.IsMuted);
}
return new PlaybackStateResponse(getSettingsResult.Value.Volume, getSettingsResult.Value.IsMuted);
}
}
@@ -46,18 +46,18 @@ public class GetUserSettingsQueryHandler : IQueryHandler<GetUserSettingsQuery, R
/// </returns>
public async Task<Result<UserSettingsResponse>> HandleAsync(GetUserSettingsQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the settings of the current user from the repository
// Get the settings of the current user from the repository.
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getSettingsResult.IsFailure)
return getSettingsResult.Errors;
// when no settings are stored for the current user yet, return the default settings
// When no settings are stored for the current user yet, return the default settings.
if (getSettingsResult.Value is null)
{
Result<UserSettings> defaultSettingsResult = UserSettings.Create();