mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:21:10 +00:00
Adds favorites and aligns playlist and favorite pagination
This commit is contained in:
1 parent
2e9f7d8496
commit
525ac1348d
193 files changed
+10944
-643
No files matched your search
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the generic display data of a favorited media item.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For a music artist the title is the artist name and there is no collection or creator. For a music album the title is the album title,
|
||||
/// there is no collection, and the creator is the artist. For a music track the title is the track title, the collection is the album and
|
||||
/// the creator is the artist. For a book the title is the book title, there is no collection yet because the series of a book is not catalogued, and the creator is its
|
||||
/// first author.
|
||||
/// </remarks>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item.</param>
|
||||
/// <param name="Title">The title of the media item.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the media item, if available.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}; Title: {Title}")]
|
||||
public sealed record FavoriteItemDisplayDto(
|
||||
Guid LibraryId,
|
||||
string Title,
|
||||
Guid CollectionId,
|
||||
string CollectionTitle,
|
||||
Guid CreatorId,
|
||||
string CreatorName,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a stored favorite together with the display data of the media item it references.
|
||||
/// </summary>
|
||||
/// <param name="Favorite">The stored favorite.</param>
|
||||
/// <param name="Display">The display data of the referenced media item, or <see langword="null"/> when it no longer exists.</param>
|
||||
[DebuggerDisplay("Id: {Favorite.Id}; MediaKind: {Favorite.MediaKind}")]
|
||||
public sealed record FavoriteItemDto(
|
||||
FavoriteEntity Favorite,
|
||||
FavoriteItemDisplayDto? Display
|
||||
);
|
||||
@@ -1,16 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using System.Collections.Generic;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// A stored playlist together with a window of its entries and their display data.
|
||||
/// Data transfer object for a stored playlist together with a page of its entries and their display data.
|
||||
/// </summary>
|
||||
/// <param name="Playlist">The stored playlist.</param>
|
||||
/// <param name="Entries">The requested window of entries.</param>
|
||||
/// <param name="Entries">The requested page of entries.</param>
|
||||
[DebuggerDisplay("PlaylistId: {Playlist.Id}; Name: {Playlist.Name}; Entries: {Entries.Count}")]
|
||||
public sealed record PlaylistDetailsDto(
|
||||
PlaylistEntity Playlist,
|
||||
IReadOnlyList<PlaylistEntryDto> Entries
|
||||
PaginatedResultDto<PlaylistEntryDto> Entries
|
||||
);
|
||||
@@ -1,11 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Display data of the media item referenced by a playlist entry, together with its collection and creator.
|
||||
/// Data transfer object for the display data of the media item referenced by a playlist entry, together with its collection and creator.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track.</param>
|
||||
/// <param name="TrackTitle">The title of the track.</param>
|
||||
@@ -16,6 +17,7 @@ namespace Lumina.Application.Common.DTO.Playlists;
|
||||
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
|
||||
/// <param name="ArtistName">The name of the artist that produced the track.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}; TrackTitle: {TrackTitle}")]
|
||||
public sealed record PlaylistEntryDisplayDto(
|
||||
Guid TrackId,
|
||||
string TrackTitle,
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// A stored playlist entry together with the display data of the media item it references and its dense display position.
|
||||
/// Data transfer object for a stored playlist entry together with the display data of the media item it references and its dense display position.
|
||||
/// </summary>
|
||||
/// <param name="Entry">The stored entry.</param>
|
||||
/// <param name="Display">The display data of the referenced media item, or <see langword="null"/> when it no longer exists.</param>
|
||||
/// <param name="DisplayPosition">The dense zero based position shown to the client.</param>
|
||||
[DebuggerDisplay("EntryId: {Entry.Id}; MediaItemId: {Entry.MediaItemId}; Position: {DisplayPosition}")]
|
||||
public sealed record PlaylistEntryDto(
|
||||
PlaylistEntryEntity Entry,
|
||||
PlaylistEntryDisplayDto? Display,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
@@ -15,6 +16,7 @@ namespace Lumina.Application.Common.DTO.Playlists;
|
||||
/// <param name="EntryCount">The number of entries of the playlist.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the playlist was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}")]
|
||||
public sealed record PlaylistSummaryDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a favorite - the marker of a user on a media item of any media kind.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The favorite references the media item by its kind and its Id, without a foreign key, so the same table serves every media context and a
|
||||
/// favorite survives the deletion of the item it references, so its owner can still see and remove it.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public class FavoriteEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the favorite.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that owns the favorite.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind of the favorited media item.
|
||||
/// </summary>
|
||||
public required FavoriteMediaKind MediaKind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the favorited media item.
|
||||
/// </summary>
|
||||
public required Guid MediaItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </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; }
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for favorites.
|
||||
/// </summary>
|
||||
public interface IFavoriteRepository : IRepository<FavoriteEntity>,
|
||||
IInsertRepositoryAction<FavoriteEntity>,
|
||||
IDeleteByIdRepositoryAction<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the favorite of the user identified by <paramref name="userId"/> on the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user the favorite must belong to.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entity 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 favorite, <see langword="null"/> when the user has not favorited the media item, or an error.
|
||||
/// </returns>
|
||||
Task<Result<FavoriteEntity?>> GetByMediaItemIdForUserAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library that contains the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if the media item exists.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the Id of the library that contains the media item, <see langword="null"/> when the
|
||||
/// media item does not exist or its kind has no catalogued library yet, or an error.
|
||||
/// </returns>
|
||||
Task<Result<Guid?>> GetMediaItemLibraryIdAsync(FavoriteMediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the paginated favorites of the user identified by <paramref name="userId"/>, together with the display data of the media items they reference,
|
||||
/// or all the matching favorites when the pagination data is <see langword="null"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are retrieved.</param>
|
||||
/// <param name="mediaKind">The kind of media item to restrict the favorites to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching favorites are returned.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{FavoriteItemDto}"/>, or an error.</returns>
|
||||
Task<Result<PaginatedResultDto<FavoriteItemDto>>> GetAllForUserAsync(Guid userId, FavoriteMediaKind? mediaKind, PaginationDataDto? paginationData = null, bool shouldTrackEntities = false, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Ids, among <paramref name="mediaItemIds"/>, of the media items of kind <paramref name="mediaKind"/> that the user identified by <paramref name="userId"/> has favorited.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are checked.</param>
|
||||
/// <param name="mediaKind">The kind of the media items.</param>
|
||||
/// <param name="mediaItemIds">The Ids of the media items to check.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the subset of the Ids that are favorites of the user, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<Guid>>> GetFavoritedMediaItemIdsForUserAsync(Guid userId, FavoriteMediaKind mediaKind, IReadOnlyCollection<Guid> mediaItemIds, CancellationToken cancellationToken);
|
||||
}
|
||||
+5
-3
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
@@ -44,16 +45,17 @@ public interface IPlaylistRepository : IRepository<PlaylistEntity>,
|
||||
Task<Result<IReadOnlyList<PlaylistSummaryDto>>> GetAllForUserAsync(Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist identified by <paramref name="id"/> together with the display details of the media items its entries reference,
|
||||
/// when the playlist belongs to the user identified by <paramref name="userId"/>.
|
||||
/// Gets the playlist identified by <paramref name="id"/> together with a page of the display details of the media items its entries reference,
|
||||
/// when the playlist belongs to the user identified by <paramref name="userId"/>, or all the entries when the pagination data is <see langword="null"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the playlist to get.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching entries are returned.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the playlist details, <see langword="null"/> when no such playlist exists, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, int offset, int limit, CancellationToken cancellationToken);
|
||||
Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, PaginationDataDto? paginationData = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Appends a batch of media items of one kind to the end of the ordered entries of a playlist of the user identified by
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
@@ -161,6 +162,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IPlaylistRepository PlaylistRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite repository.
|
||||
/// </summary>
|
||||
IFavoriteRepository FavoriteRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddFavoriteRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddFavoriteRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddFavoriteCommand ToCommand(this AddFavoriteRequest request)
|
||||
{
|
||||
return new AddFavoriteCommand(request.MediaKind, request.MediaItemId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="FavoriteEntity"/>.
|
||||
/// </summary>
|
||||
public static class FavoriteEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="Favorite"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Favorite"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Favorite> ToDomainEntity(this FavoriteEntity repositoryEntity)
|
||||
{
|
||||
return Favorite.Create(
|
||||
FavoriteId.Create(repositoryEntity.Id),
|
||||
UserId.Create(repositoryEntity.UserId),
|
||||
MediaItemId.Create(repositoryEntity.MediaItemId),
|
||||
repositoryEntity.MediaKind,
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="FavoriteResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static FavoriteResponse ToResponse(this FavoriteEntity repositoryEntity)
|
||||
{
|
||||
return new FavoriteResponse(
|
||||
repositoryEntity.Id,
|
||||
repositoryEntity.MediaKind,
|
||||
repositoryEntity.MediaItemId,
|
||||
repositoryEntity.CreatedOnUtc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="FavoriteItemDto"/>.
|
||||
/// </summary>
|
||||
public static class FavoriteItemDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to <see cref="FavoriteItemResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The favorite data to be converted.</param>
|
||||
/// <returns>The converted response, flagged as not available with empty display fields when the display data is missing.</returns>
|
||||
public static FavoriteItemResponse ToResponse(this FavoriteItemDto data)
|
||||
{
|
||||
if (data.Display is null)
|
||||
return new FavoriteItemResponse(
|
||||
data.Favorite.MediaKind,
|
||||
data.Favorite.MediaItemId,
|
||||
false,
|
||||
Guid.Empty,
|
||||
string.Empty,
|
||||
Guid.Empty,
|
||||
string.Empty,
|
||||
Guid.Empty,
|
||||
string.Empty,
|
||||
null);
|
||||
|
||||
FavoriteItemDisplayDto display = data.Display;
|
||||
return new FavoriteItemResponse(
|
||||
data.Favorite.MediaKind,
|
||||
data.Favorite.MediaItemId,
|
||||
true,
|
||||
display.LibraryId,
|
||||
display.Title,
|
||||
display.CollectionId,
|
||||
display.CollectionTitle,
|
||||
display.CreatorId,
|
||||
display.CreatorName,
|
||||
display.CoverPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to a paginated collection of <see cref="FavoriteItemResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The paginated favorite data to be converted.</param>
|
||||
/// <returns>The converted paginated responses.</returns>
|
||||
public static PaginatedResponse<FavoriteItemResponse> ToResponses(this PaginatedResultDto<FavoriteItemDto> data)
|
||||
{
|
||||
return new PaginatedResponse<FavoriteItemResponse>
|
||||
{
|
||||
Data = [.. data.Data.Select(item => item.ToResponse())],
|
||||
CurrentPage = data.CurrentPage,
|
||||
PerPage = data.PerPage,
|
||||
Count = data.Count,
|
||||
NumberOfPages = data.NumberOfPages
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="Favorite"/>.
|
||||
/// </summary>
|
||||
public static class FavoriteMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="FavoriteEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
public static FavoriteEntity ToRepositoryEntity(this Favorite domainEntity)
|
||||
{
|
||||
return new FavoriteEntity
|
||||
{
|
||||
Id = domainEntity.Id.Value,
|
||||
UserId = domainEntity.UserId.Value,
|
||||
MediaKind = domainEntity.MediaKind,
|
||||
MediaItemId = domainEntity.MediaItemId.Value,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetFavoriteStatusRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetFavoriteStatusRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetFavoriteStatusQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetFavoriteStatusQuery ToQuery(this GetFavoriteStatusRequest request)
|
||||
{
|
||||
return new GetFavoriteStatusQuery(request.MediaKind, request.MediaItemIds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetFavoritesRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetFavoritesRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetFavoritesQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetFavoritesQuery ToQuery(this GetFavoritesRequest 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 ?? 200
|
||||
};
|
||||
|
||||
return new GetFavoritesQuery(
|
||||
request.MediaKind,
|
||||
paginationData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetPlaylistRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetPlaylistRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetPlaylistQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist whose entries are retrieved, taken from the route.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetPlaylistQuery ToQuery(this GetPlaylistRequest request, string? playlistId)
|
||||
{
|
||||
PaginationDataDto? paginationData = null;
|
||||
if (request.CurrentPage is not null || request.PerPage is not null)
|
||||
paginationData = new PaginationDataDto
|
||||
{
|
||||
CurrentPage = request.CurrentPage ?? 1,
|
||||
PerPage = request.PerPage ?? 200
|
||||
};
|
||||
|
||||
return new GetPlaylistQuery(
|
||||
playlistId,
|
||||
paginationData);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
@@ -23,8 +22,7 @@ public static class PlaylistDetailsDtoMapping
|
||||
data.Playlist.Name,
|
||||
data.Playlist.Description,
|
||||
data.Playlist.Type,
|
||||
[.. data.Entries.Select(entry => entry.ToResponse())],
|
||||
data.Playlist.EntryCount,
|
||||
data.Entries.ToResponses(),
|
||||
data.Playlist.CreatedOnUtc,
|
||||
data.Playlist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
@@ -48,4 +51,21 @@ public static class PlaylistEntryDtoMapping
|
||||
display.DurationInSeconds,
|
||||
display.CoverPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to a paginated collection of <see cref="PlaylistEntryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The paginated playlist entry data to be converted.</param>
|
||||
/// <returns>The converted paginated responses.</returns>
|
||||
public static PaginatedResponse<PlaylistEntryResponse> ToResponses(this PaginatedResultDto<PlaylistEntryDto> data)
|
||||
{
|
||||
return new PaginatedResponse<PlaylistEntryResponse>
|
||||
{
|
||||
Data = [.. data.Data.Select(entry => entry.ToResponse())],
|
||||
CurrentPage = data.CurrentPage,
|
||||
PerPage = data.PerPage,
|
||||
Count = data.Count,
|
||||
NumberOfPages = data.NumberOfPages
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for the <see cref="FavoriteMediaKind"/> enumeration.
|
||||
/// </summary>
|
||||
public static class FavoriteMediaKindExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the error that reports that a media item of <paramref name="mediaKind"/> does not exist.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item that was not found.</param>
|
||||
/// <returns>The not found error specific to the media kind, or the not supported error when the media kind cannot be favorited yet.</returns>
|
||||
public static Error ToMediaItemNotFoundError(this FavoriteMediaKind mediaKind)
|
||||
{
|
||||
return mediaKind switch
|
||||
{
|
||||
FavoriteMediaKind.MusicArtist => DomainErrors.Music.ArtistNotFound,
|
||||
FavoriteMediaKind.MusicAlbum => DomainErrors.Music.AlbumNotFound,
|
||||
FavoriteMediaKind.MusicTrack => DomainErrors.Music.TrackNotFound,
|
||||
FavoriteMediaKind.Book => DomainErrors.WrittenContent.BookNotFound,
|
||||
_ => DomainErrors.Favorites.FavoriteMediaKindIsNotSupported
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Command for marking a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media item to favorite.</param>
|
||||
/// <param name="MediaItemId">The unique identifier of the media item to favorite.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record AddFavoriteCommand(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
Guid? MediaItemId
|
||||
) : ICommand;
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
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.Favorites;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
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.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to mark a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
public class AddFavoriteCommandHandler : ICommandHandler<AddFavoriteCommand, Result<FavoriteResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<AddFavoriteCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteCommandHandler"/> 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 AddFavoriteCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<AddFavoriteCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to mark a media item as a favorite of 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 favorite of the current user on the media item, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<FavoriteResponse>> HandleAsync(AddFavoriteCommand 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 media kind is a defined value and the media item identifier is a non-empty Guid before this point.
|
||||
FavoriteMediaKind mediaKind = command.MediaKind!.Value;
|
||||
Guid mediaItemId = command.MediaItemId!.Value;
|
||||
|
||||
// A planned media kind has no catalogued library to look the item up in, so it is rejected before any lookup.
|
||||
if (!Favorite.IsSupported(mediaKind))
|
||||
return DomainErrors.Favorites.FavoriteMediaKindIsNotSupported;
|
||||
|
||||
// The item must exist, and its library must be reachable by the current user, so another user's library cannot be probed through favorites.
|
||||
Result<Guid?> getLibraryIdResult = await _unitOfWork.FavoriteRepository.GetMediaItemLibraryIdAsync(mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryIdResult.IsFailure)
|
||||
return getLibraryIdResult.Errors;
|
||||
if (getLibraryIdResult.Value is null)
|
||||
return mediaKind.ToMediaItemNotFoundError();
|
||||
|
||||
// An item whose library is not reachable is reported exactly like a missing item, so the response cannot be used to probe whether an item exists in another user's library.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(getLibraryIdResult.Value.Value), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return mediaKind.ToMediaItemNotFoundError();
|
||||
|
||||
// Adding an item that is already a favorite is idempotent: the existing favorite is returned and no event is raised.
|
||||
Result<FavoriteEntity?> getExistingFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getExistingFavoriteResult.IsFailure)
|
||||
return getExistingFavoriteResult.Errors;
|
||||
if (getExistingFavoriteResult.Value is not null)
|
||||
return getExistingFavoriteResult.Value.ToResponse();
|
||||
|
||||
Result<Favorite> createFavoriteResult = Favorite.Create(UserId.Create(userId), MediaItemId.Create(mediaItemId), mediaKind);
|
||||
if (createFavoriteResult.IsFailure)
|
||||
return createFavoriteResult.Errors;
|
||||
Favorite favorite = createFavoriteResult.Value;
|
||||
|
||||
Result<Created> insertResult = await _unitOfWork.FavoriteRepository.InsertAsync(favorite.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
return insertResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
{
|
||||
// A concurrent request favorited the same item between the read above and this write, and the unique index rejected this one. The
|
||||
// desired state already holds, so the request succeeds with the stored favorite, without announcing a favorite that this request did not create.
|
||||
if (!saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.UniqueConstraintViolation))
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
_unitOfWork.ClearTrackedEntities();
|
||||
Result<FavoriteEntity?> getConcurrentFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getConcurrentFavoriteResult.IsFailure)
|
||||
return getConcurrentFavoriteResult.Errors;
|
||||
if (getConcurrentFavoriteResult.Value is null)
|
||||
return saveChangesResult.Errors;
|
||||
return getConcurrentFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored.
|
||||
Result<FavoriteEntity?> getFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoriteResult.IsFailure)
|
||||
return getFavoriteResult.Errors;
|
||||
if (getFavoriteResult.Value is null)
|
||||
return DomainErrors.Favorites.FavoriteNotFound;
|
||||
|
||||
return getFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#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.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
public class AddFavoriteCommandValidator : AbstractValidator<AddFavoriteCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public AddFavoriteCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.MediaKind)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
RuleFor(command => command.MediaKind)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(command => command.MediaKind is not null);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty)
|
||||
.When(command => command.MediaItemId is not null);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Command for removing a media item from the favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The name of the kind of the favorited media item, taken from the route.</param>
|
||||
/// <param name="MediaItemId">The unique identifier of the favorited media item, taken from the route.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record RemoveFavoriteCommand(
|
||||
string? MediaKind,
|
||||
string? MediaItemId
|
||||
) : ICommand;
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
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.Favorites;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
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.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to remove a media item from the favorites of the current user.
|
||||
/// </summary>
|
||||
public class RemoveFavoriteCommandHandler : ICommandHandler<RemoveFavoriteCommand, Result<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<RemoveFavoriteCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteCommandHandler"/> 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 RemoveFavoriteCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<RemoveFavoriteCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to remove a media item from the favorites of 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 operation, or an error.</returns>
|
||||
public async Task<Result<Deleted>> HandleAsync(RemoveFavoriteCommand 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 values are a defined media kind name and a non-empty Guid before this point.
|
||||
FavoriteMediaKind mediaKind = Enum.Parse<FavoriteMediaKind>(command.MediaKind!, ignoreCase: true);
|
||||
Guid mediaItemId = Guid.Parse(command.MediaItemId!);
|
||||
|
||||
// The favorite is loaded by the current user, the kind and the item, so another user's favorite is never touched. It is loaded so that its
|
||||
// aggregate can raise the removal event before the row is deleted. The library of the item is deliberately not evaluated, so a user can
|
||||
// always remove their own favorite whose item was deleted or is no longer accessible.
|
||||
Result<FavoriteEntity?> getFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoriteResult.IsFailure)
|
||||
return getFavoriteResult.Errors;
|
||||
// Removing a favorite that is already absent succeeds, so a retry, or another tab that removed it first, does not turn the
|
||||
// caller's removal into an error. Nothing is deleted and no event is raised because this request did not remove anything.
|
||||
if (getFavoriteResult.Value is null)
|
||||
return Result.Deleted;
|
||||
|
||||
Result<Favorite> toDomainEntityResult = getFavoriteResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Favorite favorite = toDomainEntityResult.Value;
|
||||
|
||||
Result<Deleted> removeResult = favorite.Remove();
|
||||
if (removeResult.IsFailure)
|
||||
return removeResult.Errors;
|
||||
|
||||
Result<Deleted> deleteFavoriteResult = await _unitOfWork.FavoriteRepository.DeleteByIdAsync(favorite.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteFavoriteResult.IsFailure)
|
||||
return deleteFavoriteResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
{
|
||||
// A concurrent request removed the same favorite between the read above and this write, so the row this request tried to delete is already gone. The
|
||||
// desired state already holds, so the request succeeds, without announcing a removal that this request did not perform.
|
||||
if (!saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
_unitOfWork.ClearTrackedEntities();
|
||||
Result<FavoriteEntity?> getRemainingFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getRemainingFavoriteResult.IsFailure)
|
||||
return getRemainingFavoriteResult.Errors;
|
||||
if (getRemainingFavoriteResult.Value is not null)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return Result.Deleted;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="RemoveFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
public class RemoveFavoriteCommandValidator : AbstractValidator<RemoveFavoriteCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public RemoveFavoriteCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.MediaKind)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
// Only the member names are accepted, so a numeric route value that happens to parse as an enumeration value is rejected.
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => Enum.GetNames<FavoriteMediaKind>().Contains(mediaKind, StringComparer.OrdinalIgnoreCase))
|
||||
.When(command => command.MediaKind is not null && command.MediaKind.Length > 0)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.Must(mediaItemId => Guid.TryParse(mediaItemId, out Guid parsedMediaItemId) && parsedMediaItemId != Guid.Empty)
|
||||
.When(command => command.MediaItemId is not null && command.MediaItemId.Length > 0)
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Query for finding out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media items to check.</param>
|
||||
/// <param name="MediaItemIds">The unique identifiers of the media items to check.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetFavoriteStatusQuery(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
IReadOnlyList<Guid>? MediaItemIds
|
||||
) : IQuery;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
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.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to find out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
public class GetFavoriteStatusQueryHandler : IQueryHandler<GetFavoriteStatusQuery, Result<FavoriteStatusResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<GetFavoriteStatusQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusQueryHandler"/> 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 GetFavoriteStatusQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IValidator<GetFavoriteStatusQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to find out which media items of one kind are favorites 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 <see cref="FavoriteStatusResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<FavoriteStatusResponse>> HandleAsync(GetFavoriteStatusQuery 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 media kind is a defined value and the identifiers are a non-empty collection of non-empty Guids before this point.
|
||||
FavoriteMediaKind mediaKind = query.MediaKind!.Value;
|
||||
List<Guid> mediaItemIds = [.. query.MediaItemIds!.Distinct()];
|
||||
|
||||
// Only the favorites of the current user are checked, so no library access is evaluated: the answer reveals nothing about other users.
|
||||
Result<IReadOnlyList<Guid>> getFavoritedIdsResult = await _unitOfWork.FavoriteRepository
|
||||
.GetFavoritedMediaItemIdsForUserAsync(userId, mediaKind, mediaItemIds, cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoritedIdsResult.IsFailure)
|
||||
return getFavoritedIdsResult.Errors;
|
||||
|
||||
return new FavoriteStatusResponse(getFavoritedIdsResult.Value);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetFavoriteStatusQuery"/>.
|
||||
/// </summary>
|
||||
public class GetFavoriteStatusQueryValidator : AbstractValidator<GetFavoriteStatusQuery>
|
||||
{
|
||||
private const int MAXIMUM_MEDIA_ITEM_COUNT = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetFavoriteStatusQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.MediaKind)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
RuleFor(query => query.MediaKind)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdsCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.Must(mediaItemIds => mediaItemIds!.Count <= MAXIMUM_MEDIA_ITEM_COUNT)
|
||||
.When(query => query.MediaItemIds is not null)
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdsExceedMaximumCount);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.Must(mediaItemIds => !mediaItemIds!.Contains(Guid.Empty))
|
||||
.When(query => query.MediaItemIds is not null)
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the favorites of the current user, from the most recently favorited.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of media item to restrict the favorites to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="PaginationData">The object containing the requested pagination data.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetFavoritesQuery(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
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.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
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.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a window of the favorites of the current user.
|
||||
/// </summary>
|
||||
public class GetFavoritesQueryHandler : IQueryHandler<GetFavoritesQuery, Result<PaginatedResponse<FavoriteItemResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<GetFavoritesQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
|
||||
public GetFavoritesQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService, IValidator<GetFavoritesQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a window of the favorites 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 favorites, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PaginatedResponse<FavoriteItemResponse>>> HandleAsync(GetFavoritesQuery 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 favorites are scoped to the current user by the repository.
|
||||
Result<PaginatedResultDto<FavoriteItemDto>> getFavoritesResult = await _unitOfWork.FavoriteRepository
|
||||
.GetAllForUserAsync(userId, query.MediaKind, query.PaginationData, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoritesResult.IsFailure)
|
||||
return getFavoritesResult.Errors;
|
||||
|
||||
// Check the access permissions once for each library that the favorited items might belong to.
|
||||
PaginatedResultDto<FavoriteItemDto> page = getFavoritesResult.Value;
|
||||
List<Guid> libraryIds = [.. page.Data
|
||||
.Select(item => item.Display?.LibraryId ?? Guid.Empty)
|
||||
.Where(libraryId => libraryId != Guid.Empty)
|
||||
.Distinct()];
|
||||
Dictionary<Guid, bool> libraryAccess = [];
|
||||
foreach (Guid libraryId in libraryIds)
|
||||
{
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
libraryAccess[libraryId] = canAccessLibrary;
|
||||
}
|
||||
|
||||
if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary))
|
||||
{
|
||||
List<FavoriteItemDto> items = [];
|
||||
foreach (FavoriteItemDto item in page.Data)
|
||||
{
|
||||
Guid libraryId = item.Display?.LibraryId ?? Guid.Empty;
|
||||
if (libraryId == Guid.Empty || libraryAccess[libraryId])
|
||||
items.Add(item);
|
||||
else // Keep the row so its owner can see and remove it, but do not expose display data from a library the user cannot access.
|
||||
items.Add(item with { Display = null });
|
||||
}
|
||||
page = page with { Data = items };
|
||||
}
|
||||
|
||||
return Result.From(page.ToResponses());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetFavoritesQuery"/>.
|
||||
/// </summary>
|
||||
public class GetFavoritesQueryValidator : AbstractValidator<GetFavoritesQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetFavoritesQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.MediaKind)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2,11 +2,11 @@
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -94,7 +94,7 @@ public class CreatePlaylistCommandHandler : ICommandHandler<CreatePlaylistComman
|
||||
|
||||
// The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored.
|
||||
Result<PlaylistDetailsDto?> getDetailsResult = await _unitOfWork.PlaylistRepository
|
||||
.GetDetailsForUserAsync(playlist.Id.Value, userId, 0, PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
.GetDetailsForUserAsync(playlist.Id.Value, userId, new PaginationDataDto(), cancellationToken).ConfigureAwait(false);
|
||||
if (getDetailsResult.IsFailure)
|
||||
return getDetailsResult.Errors;
|
||||
if (getDetailsResult.Value is null)
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a playlist of the current user, together with a window of its ordered entries.
|
||||
/// Query for getting a playlist of the current user, together with a page of its ordered entries.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="Offset">The zero based position of the first entry to return.</param>
|
||||
/// <param name="Limit">The maximum number of entries to return in this window.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; Offset: {Offset}; Limit: {Limit}")]
|
||||
/// <param name="PaginationData">The object containing the requested pagination data.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}")]
|
||||
public record GetPlaylistQuery(
|
||||
string? PlaylistId,
|
||||
int Offset = 0,
|
||||
int Limit = PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+4
-4
@@ -70,7 +70,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
|
||||
// The playlist is scoped to the current user by the repository, so a playlist of another user is indistinguishable from a missing one.
|
||||
Result<PlaylistDetailsDto?> getPlaylistResult = await _unitOfWork.PlaylistRepository
|
||||
.GetDetailsForUserAsync(playlistId, userId, query.Offset, query.Limit, cancellationToken).ConfigureAwait(false);
|
||||
.GetDetailsForUserAsync(playlistId, userId, query.PaginationData, cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
@@ -78,7 +78,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
|
||||
// Check the access permissions for each library that the tracks in the playlist might belong to.
|
||||
PlaylistDetailsDto playlist = getPlaylistResult.Value;
|
||||
List<Guid> libraryIds = [.. playlist.Entries
|
||||
List<Guid> libraryIds = [.. playlist.Entries.Data
|
||||
.Select(entry => entry.Display?.LibraryId ?? Guid.Empty)
|
||||
.Where(libraryId => libraryId != Guid.Empty)
|
||||
.Distinct()];
|
||||
@@ -93,7 +93,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary))
|
||||
{
|
||||
List<PlaylistEntryDto> entries = [];
|
||||
foreach (PlaylistEntryDto entry in playlist.Entries)
|
||||
foreach (PlaylistEntryDto entry in playlist.Entries.Data)
|
||||
{
|
||||
Guid libraryId = entry.Display?.LibraryId ?? Guid.Empty;
|
||||
if (libraryId == Guid.Empty || libraryAccess[libraryId])
|
||||
@@ -102,7 +102,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
// Keep the row so its owner can see and remove it, but do not expose display data from a library the user cannot access.
|
||||
entries.Add(entry with { Display = null });
|
||||
}
|
||||
playlist = playlist with { Entries = entries };
|
||||
playlist = playlist with { Entries = playlist.Entries with { Data = entries } };
|
||||
}
|
||||
|
||||
return playlist.ToResponse();
|
||||
|
||||
@@ -25,13 +25,5 @@ public class GetPlaylistQueryValidator : AbstractValidator<GetPlaylistQuery>
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(query => query.PlaylistId is not null && query.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.Offset)
|
||||
.GreaterThanOrEqualTo(0)
|
||||
.WithError(Errors.Playlists.PlaylistEntryWindowOffsetIsInvalid);
|
||||
|
||||
RuleFor(query => query.Limit)
|
||||
.InclusiveBetween(1, PlaylistWindow.MAXIMUM_ENTRY_WINDOW_SIZE)
|
||||
.WithError(Errors.Playlists.PlaylistEntryWindowLimitIsInvalid);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// The bounds of one playlist entry read window.
|
||||
/// </summary>
|
||||
public static class PlaylistWindow
|
||||
{
|
||||
/// <summary>
|
||||
/// The default number of entries a single read window returns.
|
||||
/// </summary>
|
||||
public const int DEFAULT_ENTRY_WINDOW_SIZE = 200;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum number of entries a single read window may return.
|
||||
/// </summary>
|
||||
public const int MAXIMUM_ENTRY_WINDOW_SIZE = 1000;
|
||||
}
|
||||
Reference in new issue
Block a user