Adds favorites and aligns playlist and favorite pagination

This commit is contained in:
BinaryAlley committed 2026-10-22 20:27:07 +03:00
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; }
}
@@ -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);
}
@@ -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;
@@ -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();
}
}
@@ -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);
}
}
@@ -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;
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
@@ -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);
}
}
@@ -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;
@@ -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());
}
}
@@ -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,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;
@@ -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;
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Favorites;
/// <summary>
/// Represents a request for marking a media item as a favorite of the current user.
/// </summary>
/// <param name="MediaKind">The kind of the media item to favorite. Required.</param>
/// <param name="MediaItemId">The Id of the media item to favorite. Required.</param>
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public record AddFavoriteRequest(
FavoriteMediaKind? MediaKind,
Guid? MediaItemId
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Favorites;
/// <summary>
/// Represents a request 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. Required.</param>
/// <param name="MediaItemIds">The Ids of the media items to check, from 1 to 100. Required.</param>
[DebuggerDisplay("MediaKind: {MediaKind}")]
public record GetFavoriteStatusRequest(
FavoriteMediaKind? MediaKind,
List<Guid>? MediaItemIds
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Favorites;
/// <summary>
/// Represents a request for getting a window of the favorites of the current user.
/// </summary>
/// <param name="MediaKind">The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted.</param>
/// <param name="CurrentPage">The one based page of favorites to return. Optional; defaults to 1 when a page size is provided.</param>
/// <param name="PerPage">The number of favorites per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every matching favorite is returned.</param>
[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetFavoritesRequest(
FavoriteMediaKind? MediaKind,
int? CurrentPage,
int? PerPage
);
@@ -5,12 +5,12 @@ using System.Diagnostics;
namespace Lumina.Contracts.Requests.Playlists;
/// <summary>
/// Represents a request for getting a window of the entries of a playlist of the current user.
/// Represents a request for getting a page of the entries of a playlist of the current user.
/// </summary>
/// <param name="Offset">The zero based position of the first entry to return. Optional; defaults to 0.</param>
/// <param name="Limit">The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.</param>
[DebuggerDisplay("Offset: {Offset}; Limit: {Limit}")]
/// <param name="CurrentPage">The one based page of entries to return. Optional; defaults to 1 when a page size is provided.</param>
/// <param name="PerPage">The number of entries per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every entry is returned.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetPlaylistRequest(
int? Offset,
int? Limit
int? CurrentPage,
int? PerPage
);
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Favorites;
/// <summary>
/// Represents a response for a favorite of the current user together with the display details of the media item it references.
/// </summary>
/// <remarks>
/// The display fields are generic across media kinds. For a music artist the title is the artist name and there is no collection or
/// creator. For a music album the creator is the artist and there is no collection. For a music track the collection is the album and the
/// creator is the artist. For a book there is no collection yet, because the series of a book is not catalogued, and the creator is its first author.
/// </remarks>
/// <param name="MediaKind">The kind of the favorited media item.</param>
/// <param name="MediaItemId">The Id of the favorited media item.</param>
/// <param name="IsAvailable">Whether the media item still exists and can be accessed by the user. When <see langword="false"/>, every display field is empty.</param>
/// <param name="LibraryId">The Id of the media library that contains the media item, or an empty Guid when the item is not available.</param>
/// <param name="Title">The title of the media item, or an empty string when the item is not available.</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("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public sealed record FavoriteItemResponse(
FavoriteMediaKind MediaKind,
Guid MediaItemId,
bool IsAvailable,
Guid LibraryId,
string Title,
Guid CollectionId,
string CollectionTitle,
Guid CreatorId,
string CreatorName,
string? CoverPath
);
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Favorites;
/// <summary>
/// Represents a response for a favorite of the current user.
/// </summary>
/// <param name="Id">The Id of the favorite.</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="FavoritedOnUtc">The date and time when the media item was favorited.</param>
[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public sealed record FavoriteResponse(
Guid Id,
FavoriteMediaKind MediaKind,
Guid MediaItemId,
DateTime FavoritedOnUtc
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Favorites;
/// <summary>
/// Represents a response that tells which of the checked media items are favorites of the current user.
/// </summary>
/// <param name="FavoritedMediaItemIds">The Ids, among the checked ones, of the media items that are favorites of the current user.</param>
[DebuggerDisplay("Favorited: {FavoritedMediaItemIds.Count}")]
public sealed record FavoriteStatusResponse(
IReadOnlyList<Guid> FavoritedMediaItemIds
);
@@ -1,31 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Common;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Playlists;
/// <summary>
/// Represents a response for a playlist together with its ordered entries.
/// Represents a response for a playlist together with a page of its ordered entries.
/// </summary>
/// <param name="Id">The Id of the playlist.</param>
/// <param name="Name">The name of the playlist.</param>
/// <param name="Description">The description of the playlist, if applicable.</param>
/// <param name="Type">The kind of media the playlist holds.</param>
/// <param name="Entries">The ordered entries of the requested window of the playlist.</param>
/// <param name="EntryCount">The number of entries the playlist holds, even when only a window of them is returned.</param>
/// <param name="Entries">The ordered entries of the requested page 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}; Window: {Entries.Count}")]
[DebuggerDisplay("Id: {Id}; Name: {Name}; Entries: {Entries.Count}")]
public sealed record PlaylistResponse(
Guid Id,
string Name,
string? Description,
PlaylistType Type,
IReadOnlyList<PlaylistEntryResponse> Entries,
int EntryCount,
PaginatedResponse<PlaylistEntryResponse> Entries,
DateTime CreatedOnUtc,
DateTime? UpdatedOnUtc
);
@@ -0,0 +1,77 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Favorites;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="FavoriteEntity"/> entity.
/// </summary>
public class FavoriteConfiguration : IEntityTypeConfiguration<FavoriteEntity>
{
/// <summary>
/// Configures the <see cref="FavoriteEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<FavoriteEntity> builder)
{
builder.ToTable("Favorites");
builder.HasKey(favorite => favorite.Id);
builder.Property(favorite => favorite.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
// A favorite belongs to the user that created it, and it is removed with that user.
builder.HasOne<UserEntity>()
.WithMany()
.HasForeignKey(favorite => favorite.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
builder.Property(favorite => favorite.UserId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(favorite => favorite.MediaKind)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(2);
builder.Property(favorite => favorite.MediaItemId)
.IsRequired()
.HasColumnOrder(3);
// Audit.
builder.Property(favorite => favorite.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(4);
builder.Property(favorite => favorite.CreatedBy)
.IsRequired()
.HasColumnOrder(5);
builder.Property(favorite => favorite.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(6);
builder.Property(favorite => favorite.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(7);
// The referenced media item is kept by kind and Id only, without a foreign key: one table serves every media kind, so no single table
// can be referenced, and a favorite survives the deletion of the item it references, so its owner can still see and remove it.
// The unique index makes the storage medium the owner of the "one favorite per user and item" invariant: a duplicate is rejected even
// when two concurrent adds both pass the existence check of the handler.
builder.HasIndex(favorite => new { favorite.UserId, favorite.MediaKind, favorite.MediaItemId })
.IsUnique();
// Enable listing the favorites of a user from the most recently favorited: the first index serves the listing of every kind, and the second one serves the listing restricted to one media kind.
builder.HasIndex(favorite => new { favorite.UserId, favorite.CreatedOnUtc });
builder.HasIndex(favorite => new { favorite.UserId, favorite.MediaKind, favorite.CreatedOnUtc });
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,62 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsFavorites : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Favorites",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
MediaKind = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
MediaItemId = table.Column<Guid>(type: "TEXT", nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Favorites", x => x.Id);
table.ForeignKey(
name: "FK_Favorites_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Favorites_UserId_CreatedOnUtc",
table: "Favorites",
columns: new[] { "UserId", "CreatedOnUtc" });
migrationBuilder.CreateIndex(
name: "IX_Favorites_UserId_MediaKind_CreatedOnUtc",
table: "Favorites",
columns: new[] { "UserId", "MediaKind", "CreatedOnUtc" });
migrationBuilder.CreateIndex(
name: "IX_Favorites_UserId_MediaKind_MediaItemId",
table: "Favorites",
columns: new[] { "UserId", "MediaKind", "MediaItemId" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Favorites");
}
}
}
@@ -299,6 +299,54 @@ namespace Lumina.DataAccess.Common.Migrations
b.ToTable("Tags", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid>("MediaItemId")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("MediaKind")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<Guid>("UserId")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.HasKey("Id");
b.HasIndex("UserId", "CreatedOnUtc");
b.HasIndex("UserId", "MediaKind", "CreatedOnUtc");
b.HasIndex("UserId", "MediaKind", "MediaItemId")
.IsUnique();
b.ToTable("Favorites", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b =>
{
b.Property<Guid>("Id")
@@ -2839,6 +2887,15 @@ namespace Lumina.DataAccess.Common.Migrations
b.Navigation("User");
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b =>
{
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b =>
{
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null)
@@ -0,0 +1,403 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Favorites;
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
using Lumina.Application.Common.DTO.Favorites;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Favorites;
/// <summary>
/// Repository for favorites.
/// </summary>
/// <remarks>
/// A favorite references its media item by kind and Id without a foreign key, so reading a page of favorites resolves the display data of
/// the referenced items with one batched query per media kind present in the page, and a favorite whose item no longer exists is kept
/// without display data. Duplicate favorites of the same user on the same item are rejected by the unique (UserId, MediaKind, MediaItemId) index.
/// </remarks>
internal sealed class FavoriteRepository : IFavoriteRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="FavoriteRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public FavoriteRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new favorite.
/// </summary>
/// <param name="data">The favorite to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Task<Result<Created>> InsertAsync(FavoriteEntity data, CancellationToken cancellationToken)
{
// The handler checks whether the user already favorited the item and creates a new favorite with a new Id, so this always adds a
// row. A retried or concurrent add that passed the handler's check is rejected by the unique (UserId, MediaKind, MediaItemId)
// index when the changes are saved, which is the only check that can observe another request's write.
_luminaDbContext.Favorites.Add(data);
return Task.FromResult<Result<Created>>(Result.Created);
}
/// <summary>
/// Deletes the favorite identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the favorite to delete.</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>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
// A handler may already have loaded the same favorite in this unit of work, so the tracked instance is preferred over materializing a second copy.
FavoriteEntity? favorite = _luminaDbContext.Favorites.Local.FirstOrDefault(trackedFavorite => trackedFavorite.Id == id);
favorite ??= await _luminaDbContext.Favorites.FirstOrDefaultAsync(foundFavorite => foundFavorite.Id == id, cancellationToken).ConfigureAwait(false);
if (favorite is null)
return DomainErrors.Favorites.FavoriteNotFound;
_luminaDbContext.Favorites.Remove(favorite);
return Result.Deleted;
}
/// <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>
public async Task<Result<FavoriteEntity?>> GetByMediaItemIdForUserAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a favorite that belongs to another user in the first place.
IQueryable<FavoriteEntity> query = _luminaDbContext.Favorites;
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query
.FirstOrDefaultAsync(favorite => favorite.UserId == userId && favorite.MediaKind == mediaKind && favorite.MediaItemId == mediaItemId, cancellationToken).ConfigureAwait(false);
}
/// <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>
public async Task<Result<Guid?>> GetMediaItemLibraryIdAsync(FavoriteMediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken)
{
// Only the library Id is projected, so the check never materializes the media item. The planned kinds have no catalogue table yet, so they have no library.
Guid? libraryId = mediaKind switch
{
FavoriteMediaKind.MusicArtist => await _luminaDbContext.Artists
.AsNoTracking()
.Where(artist => artist.Id == mediaItemId)
.Select(artist => (Guid?)artist.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
FavoriteMediaKind.MusicAlbum => await _luminaDbContext.Albums
.AsNoTracking()
.Where(album => album.Id == mediaItemId)
.Select(album => (Guid?)album.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
FavoriteMediaKind.MusicTrack => await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.Id == mediaItemId)
.Select(track => (Guid?)track.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
FavoriteMediaKind.Book => await _luminaDbContext.Books
.AsNoTracking()
.Where(book => book.Id == mediaItemId)
.Select(book => (Guid?)book.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
_ => null,
};
return Result<Guid?>.Success(libraryId);
}
/// <summary>
/// Gets the paginated favorites of the user identified by <paramref name="userId"/>, from the most recently favorited, 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>
public async Task<Result<PaginatedResultDto<FavoriteItemDto>>> GetAllForUserAsync(Guid userId, FavoriteMediaKind? mediaKind, PaginationDataDto? paginationData = null, bool shouldTrackEntities = false, CancellationToken cancellationToken = default)
{
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a favorite that belongs to another user in the first place.
IQueryable<FavoriteEntity> favoritesQuery = _luminaDbContext.Favorites;
if (!shouldTrackEntities)
favoritesQuery = favoritesQuery.AsNoTracking();
favoritesQuery = favoritesQuery.Where(favorite => favorite.UserId == userId);
if (mediaKind is not null)
{
FavoriteMediaKind kindFilter = mediaKind.Value;
favoritesQuery = favoritesQuery.Where(favorite => favorite.MediaKind == kindFilter);
}
// The Id is the tiebreaker, so favorites created at the same instant keep a stable order between pages.
IOrderedQueryable<FavoriteEntity> orderedFavoritesQuery = favoritesQuery
.OrderByDescending(favorite => favorite.CreatedOnUtc)
.ThenBy(favorite => favorite.Id);
// If no pagination was requested, return all the favorites of the user.
if (paginationData is null)
{
IReadOnlyList<FavoriteItemDto> allFavorites = await ToFavoriteItemsAsync(orderedFavoritesQuery, cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<FavoriteItemDto>
{
Data = allFavorites,
CurrentPage = 1,
PerPage = allFavorites.Count,
Count = allFavorites.Count,
NumberOfPages = 1
};
}
int count = await orderedFavoritesQuery.Select(favorite => favorite.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
// Only the requested page is materialized, because a user can favorite any number of items.
IQueryable<FavoriteEntity> pageQuery = orderedFavoritesQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage);
IReadOnlyList<FavoriteItemDto> paginatedResult = await ToFavoriteItemsAsync(pageQuery, cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<FavoriteItemDto>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Reads the display data of the media items referenced by the favorites of <paramref name="favoritesQuery"/>, one query per media kind present.
/// </summary>
/// <param name="favoritesQuery">The query of the favorites to read the display data for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The favorites together with the display data of the media items they reference.</returns>
private async Task<IReadOnlyList<FavoriteItemDto>> ToFavoriteItemsAsync(IQueryable<FavoriteEntity> favoritesQuery, CancellationToken cancellationToken)
{
List<FavoriteEntity> favorites = await favoritesQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
Dictionary<FavoriteMediaKind, Dictionary<Guid, FavoriteItemDisplayDto>> displayDataByKind = [];
foreach (IGrouping<FavoriteMediaKind, FavoriteEntity> kindGroup in favorites.GroupBy(favorite => favorite.MediaKind))
{
List<Guid> mediaItemIds = [.. kindGroup.Select(favorite => favorite.MediaItemId).Distinct()];
displayDataByKind[kindGroup.Key] = await GetDisplayDataAsync(kindGroup.Key, mediaItemIds, cancellationToken).ConfigureAwait(false);
}
// A favorite whose item was deleted is kept with no display data, so its owner can still see and remove it instead of it silently disappearing.
List<FavoriteItemDto> items = [];
foreach (FavoriteEntity favorite in favorites)
{
FavoriteItemDisplayDto? display = null;
if (displayDataByKind[favorite.MediaKind].TryGetValue(favorite.MediaItemId, out FavoriteItemDisplayDto? foundDisplay))
display = foundDisplay;
items.Add(new FavoriteItemDto(favorite, display));
}
return items;
}
/// <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>
public async Task<Result<IReadOnlyList<Guid>>> GetFavoritedMediaItemIdsForUserAsync(Guid userId, FavoriteMediaKind mediaKind, IReadOnlyCollection<Guid> mediaItemIds, CancellationToken cancellationToken)
{
Guid[] requestedIds = [.. mediaItemIds];
// The unique (UserId, MediaKind, MediaItemId) index serves this lookup, and the caller bounds the number of requested Ids.
IReadOnlyList<Guid> favoritedIds = await _luminaDbContext.Favorites
.AsNoTracking()
.Where(favorite => favorite.UserId == userId && favorite.MediaKind == mediaKind && requestedIds.Contains(favorite.MediaItemId))
.Select(favorite => favorite.MediaItemId)
.Distinct()
.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From(favoritedIds);
}
/// <summary>
/// Reads the display data of the media items of kind <paramref name="mediaKind"/> identified by <paramref name="mediaItemIds"/> in one query per bounded chunk.
/// </summary>
/// <param name="mediaKind">The kind of the media items.</param>
/// <param name="mediaItemIds">The Ids of the media items whose display data is read.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The display data keyed by media item Id. A media item that no longer exists, or whose kind has no catalogue yet, is absent.</returns>
private async Task<Dictionary<Guid, FavoriteItemDisplayDto>> GetDisplayDataAsync(FavoriteMediaKind mediaKind, IReadOnlyCollection<Guid> mediaItemIds, CancellationToken cancellationToken)
{
if (mediaItemIds.Count == 0)
return [];
// The lookup is split into bounded chunks, so even an unpaginated listing never exceeds the storage parameter limit.
const int LOOKUP_CHUNK_SIZE = 500;
List<DisplayRow> rows = [];
foreach (Guid[] chunk in mediaItemIds.Chunk(LOOKUP_CHUNK_SIZE))
rows.AddRange(await GetDisplayRowsAsync(mediaKind, chunk, cancellationToken).ConfigureAwait(false));
return rows.ToDictionary(
row => row.MediaItemId,
row => new FavoriteItemDisplayDto(
row.LibraryId,
row.Title,
row.CollectionId ?? Guid.Empty,
row.CollectionTitle ?? string.Empty,
row.CreatorId ?? Guid.Empty,
row.CreatorName ?? string.Empty,
row.CoverPath));
}
/// <summary>
/// Reads the display data of one bounded chunk of media items of kind <paramref name="mediaKind"/> in a single query.
/// </summary>
/// <param name="mediaKind">The kind of the media items.</param>
/// <param name="requestedIds">The bounded chunk of media item Ids whose display data is read.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The display rows of the media items that exist.</returns>
private async Task<List<DisplayRow>> GetDisplayRowsAsync(FavoriteMediaKind mediaKind, Guid[] requestedIds, CancellationToken cancellationToken)
{
List<DisplayRow> rows;
switch (mediaKind)
{
case FavoriteMediaKind.MusicArtist:
// The cover of the artist is the cover artwork stored for it, if any, the same one the artist listing exposes.
rows = await _luminaDbContext.Artists
.AsNoTracking()
.Where(artist => requestedIds.Contains(artist.Id))
.Select(artist => new DisplayRow(
artist.Id,
artist.LibraryId,
artist.Name,
null,
null,
null,
null,
_luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()))
.ToListAsync(cancellationToken).ConfigureAwait(false);
break;
case FavoriteMediaKind.MusicAlbum:
rows = await (from album in _luminaDbContext.Albums.AsNoTracking()
join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id
where requestedIds.Contains(album.Id)
select new DisplayRow(
album.Id,
album.LibraryId,
album.Title,
null,
null,
artist.Id,
artist.Name,
_luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()))
.ToListAsync(cancellationToken).ConfigureAwait(false);
break;
case FavoriteMediaKind.MusicTrack:
// The cover of a track is the one stored for its album, like in the playlist entries.
rows = await (from track in _luminaDbContext.Tracks.AsNoTracking()
join album in _luminaDbContext.Albums on track.AlbumId equals album.Id
join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id
where requestedIds.Contains(track.Id)
select new DisplayRow(
track.Id,
track.LibraryId,
track.Title,
album.Id,
album.Title,
artist.Id,
artist.Name,
_luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()))
.ToListAsync(cancellationToken).ConfigureAwait(false);
break;
case FavoriteMediaKind.Book:
// The book catalogue does not persist series yet, so a book has no collection. The creator is the first author by display name,
// the same author the book listing shows, and the Id is the tiebreaker between authors that share a display name.
rows = await _luminaDbContext.Books
.AsNoTracking()
.Where(book => requestedIds.Contains(book.Id))
.Select(book => new DisplayRow(
book.Id,
book.LibraryId,
book.Title,
null,
null,
(from bookContributor in _luminaDbContext.BookContributors
join contributor in _luminaDbContext.MediaContributors on bookContributor.MediaContributorId equals contributor.Id
where bookContributor.BookId == book.Id && bookContributor.Role == MediaContributorRole.Author
orderby contributor.DisplayName, contributor.Id
select (Guid?)contributor.Id).FirstOrDefault(),
(from bookContributor in _luminaDbContext.BookContributors
join contributor in _luminaDbContext.MediaContributors on bookContributor.MediaContributorId equals contributor.Id
where bookContributor.BookId == book.Id && bookContributor.Role == MediaContributorRole.Author
orderby contributor.DisplayName, contributor.Id
select contributor.DisplayName).FirstOrDefault(),
book.Artwork
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()))
.ToListAsync(cancellationToken).ConfigureAwait(false);
break;
default:
return [];
}
return rows;
}
/// <summary>
/// The display data of one favorited media item as read from storage, before the absent values are normalized to the generic "no value" form.
/// </summary>
/// <param name="MediaItemId">The Id of the media item.</param>
/// <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, if any.</param>
/// <param name="CollectionTitle">The title of the collection that contains the media item, if any.</param>
/// <param name="CreatorId">The Id of the creator of the media item, if any.</param>
/// <param name="CreatorName">The name of the creator of the media item, if any.</param>
/// <param name="CoverPath">The path of the cover art of the media item, if available.</param>
private sealed record DisplayRow(
Guid MediaItemId,
Guid LibraryId,
string Title,
Guid? CollectionId,
string? CollectionTitle,
Guid? CreatorId,
string? CreatorName,
string? CoverPath
);
}
@@ -3,6 +3,7 @@ using Dapper;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Repositories.Playlists;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.DTO.Playlists;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
@@ -169,18 +170,17 @@ internal sealed class PlaylistRepository : IPlaylistRepository
}
/// <summary>
/// Gets the playlist identified by <paramref name="id"/> together with a window of 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="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>
/// <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 and its entry count, <see langword="null"/> when no such playlist exists, or an error.
/// An <see cref="Result{TValue}"/> containing either the playlist details and the paginated entries, <see langword="null"/> when no such playlist exists, or an error.
/// </returns>
public async Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, int offset, int limit, CancellationToken cancellationToken)
public async Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, PaginationDataDto? paginationData = null, CancellationToken cancellationToken = default)
{
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a playlist that belongs to another user in the first place.
PlaylistEntity? playlist = await _luminaDbContext.Playlists
@@ -189,16 +189,58 @@ internal sealed class PlaylistRepository : IPlaylistRepository
if (playlist is null)
return Result<PlaylistDetailsDto?>.Success(null);
// Only the requested window is materialized. A playlist can hold any number of entries, so the page never loads the whole list.
List<PlaylistEntryEntity> windowEntries = await _luminaDbContext.PlaylistEntries
IQueryable<PlaylistEntryEntity> entriesQuery = _luminaDbContext.PlaylistEntries
.AsNoTracking()
.Where(entry => entry.PlaylistId == id)
.OrderBy(entry => entry.Position)
.Skip(offset)
.Take(limit)
.ToListAsync(cancellationToken).ConfigureAwait(false);
.OrderBy(entry => entry.Position);
List<Guid> trackIds = [.. windowEntries
// If no pagination was requested, return all the entries of the playlist.
if (paginationData is null)
{
IReadOnlyList<PlaylistEntryDto> allEntries = await ToPlaylistEntriesAsync(entriesQuery, offset: 0, cancellationToken).ConfigureAwait(false);
return new PlaylistDetailsDto(playlist, new PaginatedResultDto<PlaylistEntryDto>
{
Data = allEntries,
CurrentPage = 1,
PerPage = allEntries.Count,
Count = allEntries.Count,
NumberOfPages = 1
});
}
int count = await entriesQuery.Select(entry => entry.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
int offset = (currentPage - 1) * paginationData.PerPage;
// Only the requested page is materialized. A playlist can hold any number of entries, so the page never loads the whole list.
IQueryable<PlaylistEntryEntity> pageQuery = entriesQuery
.Skip(offset)
.Take(paginationData.PerPage);
IReadOnlyList<PlaylistEntryDto> paginatedResult = await ToPlaylistEntriesAsync(pageQuery, offset, cancellationToken).ConfigureAwait(false);
return new PlaylistDetailsDto(playlist, new PaginatedResultDto<PlaylistEntryDto>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
});
}
/// <summary>
/// Reads the display data of the tracks referenced by the entries of <paramref name="entriesQuery"/>.
/// </summary>
/// <param name="entriesQuery">The ordered query of the entries to read the display data for.</param>
/// <param name="offset">The zero based position of the first entry of the page, used to compute the dense display position.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The entries together with the display data of the tracks they reference.</returns>
private async Task<IReadOnlyList<PlaylistEntryDto>> ToPlaylistEntriesAsync(IQueryable<PlaylistEntryEntity> entriesQuery, int offset, CancellationToken cancellationToken)
{
List<PlaylistEntryEntity> entries = await entriesQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> trackIds = [.. entries
.Where(entry => entry.MediaItemType == PlaylistMediaItemType.MusicTrack)
.Select(entry => entry.MediaItemId)
.Distinct()];
@@ -206,15 +248,14 @@ internal sealed class PlaylistRepository : IPlaylistRepository
// An entry whose track was deleted is kept with no display data, so its owner can still see and remove it instead of it silently
// disappearing from the playlist. The sparse order key is converted to a dense display position for the response.
List<PlaylistEntryDto> entries = [];
for (int index = 0; index < windowEntries.Count; index++)
List<PlaylistEntryDto> items = [];
for (int index = 0; index < entries.Count; index++)
{
PlaylistEntryEntity entry = windowEntries[index];
PlaylistEntryEntity entry = entries[index];
displayDataByTrackId.TryGetValue(entry.MediaItemId, out PlaylistEntryDisplayDto? displayData);
entries.Add(new PlaylistEntryDto(entry, displayData, offset + index));
items.Add(new PlaylistEntryDto(entry, displayData, offset + index));
}
return new PlaylistDetailsDto(playlist, entries);
return items;
}
/// <summary>
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Favorites;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
@@ -53,6 +54,7 @@ public class LuminaDbContext : DbContext
public virtual DbSet<MusicPlayRecordEntity> MusicPlayRecords { get; set; } = null!;
public virtual DbSet<PlaylistEntity> Playlists { get; set; } = null!;
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
public virtual DbSet<FavoriteEntity> Favorites { get; set; } = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
@@ -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;
@@ -13,6 +14,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.DataAccess.Core.Repositories.Authorization;
using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Favorites;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
@@ -68,6 +70,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private IUserSettingsRepository? _userSettingsRepository;
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
private IPlaylistRepository? _playlistRepository;
private IFavoriteRepository? _favoriteRepository;
/// <summary>
/// Gets the permission repository.
@@ -402,6 +405,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
/// <summary>
/// Gets the favorite repository.
/// </summary>
public IFavoriteRepository FavoriteRepository
{
get
{
_favoriteRepository ??= new FavoriteRepository(_luminaDbContext);
return _favoriteRepository;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
/// </summary>
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Domain.SharedKernel.Common.Enums.Favorites;
/// <summary>
/// Enumeration for the kinds of media item that can be marked as a favorite.
/// </summary>
[DebuggerDisplay("{ToString()}")]
public enum FavoriteMediaKind
{
/// <summary>
/// A favorite that references an artist of a music library.
/// </summary>
MusicArtist,
/// <summary>
/// A favorite that references an album of a music library.
/// </summary>
MusicAlbum,
/// <summary>
/// A favorite that references a track of a music library.
/// </summary>
MusicTrack,
/// <summary>
/// A favorite that references a book of a book library.
/// </summary>
Book,
/// <summary>
/// A favorite that references a video file. Planned: video libraries are not catalogued yet, so this kind cannot be favorited.
/// </summary>
Video,
/// <summary>
/// A favorite that references a photo. Planned: photo libraries are not catalogued yet, so this kind cannot be favorited.
/// </summary>
Photo,
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
#endregion
namespace Lumina.Domain.Common.Errors;
/// <summary>
/// Favorite error types.
/// </summary>
public static partial class Errors
{
public static class Favorites
{
public static Error FavoriteNotFound => Error.NotFound(description: nameof(FavoriteNotFound));
public static Error FavoriteAlreadyExists => Error.Conflict(description: nameof(FavoriteAlreadyExists));
public static Error FavoriteMediaKindIsInvalid => Error.Validation(description: nameof(FavoriteMediaKindIsInvalid));
public static Error FavoriteMediaKindIsNotSupported => Error.Validation(description: nameof(FavoriteMediaKindIsNotSupported));
public static Error FavoriteMediaItemIdCannotBeEmpty => Error.Validation(description: nameof(FavoriteMediaItemIdCannotBeEmpty));
public static Error FavoriteMediaItemIdsCannotBeEmpty => Error.Validation(description: nameof(FavoriteMediaItemIdsCannotBeEmpty));
public static Error FavoriteMediaItemIdsExceedMaximumCount => Error.Validation(description: nameof(FavoriteMediaItemIdsExceedMaximumCount));
}
}
@@ -23,7 +23,5 @@ public static partial class Errors
public static Error PlaylistEntryNotFound => Error.NotFound(description: nameof(PlaylistEntryNotFound));
public static Error PlaylistEntryPositionsAreInvalid => Error.Validation(description: nameof(PlaylistEntryPositionsAreInvalid));
public static Error PlaylistMoveTargetPositionIsInvalid => Error.Validation(description: nameof(PlaylistMoveTargetPositionIsInvalid));
public static Error PlaylistEntryWindowOffsetIsInvalid => Error.Validation(description: nameof(PlaylistEntryWindowOffsetIsInvalid));
public static Error PlaylistEntryWindowLimitIsInvalid => Error.Validation(description: nameof(PlaylistEntryWindowLimitIsInvalid));
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
/// <summary>
/// Value Object for the Id of a media item, declared by the favorite bounded context to keep the reference to the catalogue decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class MediaItemId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="MediaItemId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private MediaItemId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="MediaItemId"/> class.
/// </summary>
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
public static MediaItemId CreateUnique()
{
return new MediaItemId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="MediaItemId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="MediaItemId"/> instance.</param>
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
public static MediaItemId Create(Guid value)
{
return new MediaItemId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
/// <summary>
/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class UserId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private UserId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId CreateUnique()
{
return new UserId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="UserId"/> instance.</param>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId Create(Guid value)
{
return new UserId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
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.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
/// <summary>
/// Domain event raised when a media item is marked as a favorite.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="FavoriteId">The unique identifier of the favorite.</param>
/// <param name="UserId">The unique identifier of the user that favorited the media item.</param>
/// <param name="MediaItemId">The unique identifier of the favorited media item.</param>
/// <param name="MediaKind">The kind of the favorited media item.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("FavoriteId: {FavoriteId.Value}; UserId: {UserId.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")]
public record FavoriteAddedDomainEvent(
Guid Id,
FavoriteId FavoriteId,
UserId UserId,
MediaItemId MediaItemId,
FavoriteMediaKind MediaKind,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
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.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
/// <summary>
/// Domain event raised when a media item is removed from the favorites.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="FavoriteId">The unique identifier of the favorite.</param>
/// <param name="UserId">The unique identifier of the user that owned the favorite.</param>
/// <param name="MediaItemId">The unique identifier of the media item that was unfavorited.</param>
/// <param name="MediaKind">The kind of the media item that was unfavorited.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("FavoriteId: {FavoriteId.Value}; UserId: {UserId.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")]
public record FavoriteRemovedDomainEvent(
Guid Id,
FavoriteId FavoriteId,
UserId UserId,
MediaItemId MediaItemId,
FavoriteMediaKind MediaKind,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
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.Events;
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
/// <summary>
/// Aggregate root for a favorite, the marker a user places on a media item.
/// </summary>
[DebuggerDisplay("Id: {Id.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")]
public sealed class Favorite : AggregateRoot<FavoriteId>
{
/// <summary>
/// Gets the object representing the unique identifier of the user that owns the favorite.
/// </summary>
public UserId UserId { get; private set; }
/// <summary>
/// Gets the Id of the favorited media item.
/// </summary>
public MediaItemId MediaItemId { get; private set; }
/// <summary>
/// Gets the kind of the favorited media item.
/// </summary>
public FavoriteMediaKind MediaKind { get; private set; }
/// <summary>
/// Gets a value indicating whether the favorite was marked for removal in this unit of work.
/// </summary>
public bool IsRemoved { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Favorite"/> class.
/// </summary>
/// <param name="id">The object representing the unique identifier of the favorite.</param>
/// <param name="userId">The object representing the unique identifier of the user that owns the favorite.</param>
/// <param name="mediaItemId">The Id of the favorited media item.</param>
/// <param name="mediaKind">The kind of the favorited media item.</param>
/// <param name="createdOnUtc">The date and time when the favorite was created.</param>
/// <param name="updatedOnUtc">The date and time when the favorite was last updated.</param>
private Favorite(
FavoriteId id,
UserId userId,
MediaItemId mediaItemId,
FavoriteMediaKind mediaKind,
DateTime createdOnUtc,
Optional<DateTime> updatedOnUtc) : base(id)
{
Id = id;
UserId = userId;
MediaItemId = mediaItemId;
MediaKind = mediaKind;
CreatedOnUtc = createdOnUtc;
UpdatedOnUtc = updatedOnUtc;
}
/// <summary>
/// Creates a new favorite of the media item identified by <paramref name="mediaItemId"/> for the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The object representing the unique identifier of the user that owns the favorite.</param>
/// <param name="mediaItemId">The Id of the media item to favorite.</param>
/// <param name="mediaKind">The kind of the media item to favorite.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Favorite"/>, or an error message.
/// </returns>
public static Result<Favorite> Create(UserId userId, MediaItemId mediaItemId, FavoriteMediaKind mediaKind)
{
// A planned media kind is part of the model so the storage and the contracts are ready for it, but its items cannot be favorited until its library exists.
if (!IsSupported(mediaKind))
return Errors.Favorites.FavoriteMediaKindIsNotSupported;
DateTime occurredOnUtc = DateTime.UtcNow;
Favorite favorite = new(
FavoriteId.CreateUnique(),
userId,
mediaItemId,
mediaKind,
occurredOnUtc,
Optional<DateTime>.None());
favorite._domainEvents.Add(new FavoriteAddedDomainEvent(
Guid.NewGuid(),
favorite.Id,
userId,
mediaItemId,
mediaKind,
occurredOnUtc));
return favorite;
}
/// <summary>
/// Creates a new instance of the <see cref="Favorite"/> class, with pre-existing data.
/// </summary>
/// <param name="id">The object representing the unique identifier of the favorite.</param>
/// <param name="userId">The object representing the unique identifier of the user that owns the favorite.</param>
/// <param name="mediaItemId">The Id of the favorited media item.</param>
/// <param name="mediaKind">The kind of the favorited media item.</param>
/// <param name="createdOnUtc">The date and time when the favorite was created.</param>
/// <param name="updatedOnUtc">The date and time when the favorite was last updated.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Favorite"/>, or an error message.
/// </returns>
public static Result<Favorite> Create(
FavoriteId id,
UserId userId,
MediaItemId mediaItemId,
FavoriteMediaKind mediaKind,
DateTime createdOnUtc,
Optional<DateTime> updatedOnUtc)
{
// A stored favorite is rehydrated as it was stored, whether or not its media kind is supported today.
return new Favorite(id, userId, mediaItemId, mediaKind, createdOnUtc, updatedOnUtc);
}
/// <summary>
/// Marks the favorite as removed, raising the domain event that announces its removal.
/// </summary>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Deleted> Remove()
{
if (IsRemoved)
return Result.Deleted;
// Earlier events become irrelevant once the favorite is removed.
_domainEvents.Clear();
IsRemoved = true;
_domainEvents.Add(new FavoriteRemovedDomainEvent(
Guid.NewGuid(),
Id,
UserId,
MediaItemId,
MediaKind,
DateTime.UtcNow));
return Result.Deleted;
}
/// <summary>
/// Determines whether media items of <paramref name="mediaKind"/> can be favorited today.
/// </summary>
/// <param name="mediaKind">The kind of media item.</param>
/// <returns><see langword="true"/> if items of the media kind can be favorited, <see langword="false"/> otherwise.</returns>
public static bool IsSupported(FavoriteMediaKind mediaKind)
{
return mediaKind switch
{
FavoriteMediaKind.MusicArtist => true,
FavoriteMediaKind.MusicAlbum => true,
FavoriteMediaKind.MusicTrack => true,
FavoriteMediaKind.Book => true,
_ => false
};
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a favorite.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class FavoriteId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="FavoriteId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private FavoriteId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="FavoriteId"/> class.
/// </summary>
/// <returns>The created <see cref="FavoriteId"/> instance.</returns>
public static FavoriteId CreateUnique()
{
return new FavoriteId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="FavoriteId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="FavoriteId"/> instance.</param>
/// <returns>The created <see cref="FavoriteId"/> instance.</returns>
public static FavoriteId Create(Guid value)
{
return new FavoriteId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,18 @@
namespace Lumina.Presentation.Api.Common.Routes.Favorites;
/// <summary>
/// Class for the collection of the favorite routes of the API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the favorites of the current user.
/// </summary>
public static class Favorites
{
public const string GET_FAVORITES = "/users/me/favorites";
public const string ADD_FAVORITE = "/users/me/favorites";
public const string REMOVE_FAVORITE = "/users/me/favorites/{mediaKind}/{mediaItemId}";
public const string GET_FAVORITE_STATUS = "/users/me/favorites/status";
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Favorites;
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
using Lumina.Contracts.Requests.Favorites;
using Lumina.Contracts.Responses.Favorites;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Favorites;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
/// <summary>
/// API endpoint for the <c>/users/me/favorites</c> route, for adding a favorite.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class AddFavoriteEndpoint : BaseEndpoint<AddFavoriteRequest, IResult>
{
private readonly ICommandHandler<AddFavoriteCommand, Result<FavoriteResponse>> _addFavoriteCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="AddFavoriteEndpoint"/> class.
/// </summary>
/// <param name="addFavoriteCommandHandler">Injected service for handling add favorite commands.</param>
public AddFavoriteEndpoint(ICommandHandler<AddFavoriteCommand, Result<FavoriteResponse>> addFavoriteCommandHandler)
{
_addFavoriteCommandHandler = addFavoriteCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.POST);
Routes(ApiRoutes.Favorites.ADD_FAVORITE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Marks a media item as a favorite of the current user.
/// </summary>
/// <param name="request">The request containing the kind and the Id of the media item to favorite.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddFavoriteRequest request, CancellationToken cancellationToken)
{
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
// responses, and every response varies by the bearer token that authorized it.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Authorization";
Result<FavoriteResponse> result = await _addFavoriteCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,170 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Favorites;
using Lumina.Contracts.Responses.Favorites;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddFavoriteEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddFavoriteEndpointSummary : Summary<AddFavoriteEndpoint, AddFavoriteRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddFavoriteEndpointSummary"/> class.
/// </summary>
public AddFavoriteEndpointSummary()
{
Summary = "Marks a media item as a favorite of the current user.";
Description = "Marks the media item identified by its kind and its Id as a favorite of the currently authenticated user. The supported kinds are MusicArtist, MusicAlbum, MusicTrack and Book. The kinds Video and Photo exist but are planned: they are rejected with a validation error until video and photo libraries are catalogued. The media item must exist and belong to a media library the current user can access; an item that does not exist and an item of a library the user cannot access are reported with the same not found error, so the response cannot be used to find out what another user holds. The operation is idempotent: adding an item that is already a favorite returns the existing favorite and changes nothing.";
ExampleRequest = new AddFavoriteRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")
);
RequestParam(request => request.MediaKind, "The kind of the media item to favorite. Required. One of MusicArtist, MusicAlbum, MusicTrack or Book.");
RequestParam(request => request.MediaItemId, "The Id of the media item to favorite. Required.");
ResponseParam<FavoriteResponse>(response => response.Id, "The Id of the favorite.");
ResponseParam<FavoriteResponse>(response => response.MediaKind, "The kind of the favorited media item.");
ResponseParam<FavoriteResponse>(response => response.MediaItemId, "The Id of the favorited media item.");
ResponseParam<FavoriteResponse>(response => response.FavoritedOnUtc, "The date and time when the media item was favorited.");
Response(200, "The media item is a favorite of the current user, and the favorite is returned.",
example: new FavoriteResponse(
Id: Guid.Parse("4d5e6f70-8192-4a3b-9c4d-5e6f708192a3"),
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
FavoritedOnUtc: new DateTime(2026, 10, 21, 12, 0, 0, DateTimeKind.Utc)
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = "/api/v1/users/me/favorites"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = "/api/v1/users/me/favorites"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/users/me/favorites"
}
}
);
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/users/me/favorites",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the media item does not exist, or it belongs to a media library the current user cannot access. The error names the kind of the media item.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "ArtistNotFound",
instance = "/api/v1/users/me/favorites",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "AlbumNotFound",
instance = "/api/v1/users/me/favorites",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "TrackNotFound",
instance = "/api/v1/users/me/favorites",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "BookNotFound",
instance = "/api/v1/users/me/favorites",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
Response(409, "The request failed because the favorite could not be stored, because the database is busy or locked. Repeating the request is safe.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "ConcurrencyConflict",
instance = "/api/v1/users/me/favorites",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/users/me/favorites",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"FavoriteMediaKindIsInvalid",
"FavoriteMediaItemIdCannotBeEmpty",
"FavoriteMediaKindIsNotSupported"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Favorites;
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
using Lumina.Contracts.Requests.Favorites;
using Lumina.Contracts.Responses.Favorites;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Favorites;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
/// <summary>
/// API endpoint for the <c>/users/me/favorites/status</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetFavoriteStatusEndpoint : BaseEndpoint<GetFavoriteStatusRequest, IResult>
{
private readonly IQueryHandler<GetFavoriteStatusQuery, Result<FavoriteStatusResponse>> _getFavoriteStatusQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpoint"/> class.
/// </summary>
/// <param name="getFavoriteStatusQueryHandler">Injected service for handling get favorite status queries.</param>
public GetFavoriteStatusEndpoint(IQueryHandler<GetFavoriteStatusQuery, Result<FavoriteStatusResponse>> getFavoriteStatusQueryHandler)
{
_getFavoriteStatusQueryHandler = getFavoriteStatusQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.GET);
Routes(ApiRoutes.Favorites.GET_FAVORITE_STATUS);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Finds out which media items of one kind are favorites of the current user.
/// </summary>
/// <param name="request">The request containing the media kind and the Ids of the media items to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetFavoriteStatusRequest request, CancellationToken cancellationToken)
{
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
// responses, and every response varies by the bearer token that authorized it.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Authorization";
Result<FavoriteStatusResponse> result = await _getFavoriteStatusQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Favorites;
using Lumina.Contracts.Responses.Favorites;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFavoriteStatusEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFavoriteStatusEndpointSummary : Summary<GetFavoriteStatusEndpoint, GetFavoriteStatusRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointSummary"/> class.
/// </summary>
public GetFavoriteStatusEndpointSummary()
{
Summary = "Finds out which media items are favorites of the current user.";
Description = "Checks up to 100 media items of one kind and returns the Ids, among the checked ones, that are favorites of the currently authenticated user. The media item Ids are sent by repeating the mediaItemIds query parameter once per Id, and the limit of 100 keeps the request line within the size limit of the server. Only the favorites of the current user are consulted, so the answer reveals nothing about the media items of other users. An Id that does not exist, or that is not a favorite, is simply absent from the answer.";
ExampleRequest = new GetFavoriteStatusRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemIds:
[
Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
Guid.Parse("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d")
]
);
RequestParam(request => request.MediaKind, "The kind of the media items to check. Required. One of MusicArtist, MusicAlbum, MusicTrack or Book.");
RequestParam(request => request.MediaItemIds, "The Ids of the media items to check, from 1 to 100, sent as a repeated query parameter. Required.");
ResponseParam<FavoriteStatusResponse>(response => response.FavoritedMediaItemIds, "The Ids, among the checked ones, of the media items that are favorites of the current user.");
Response(200, "The favorite status of the checked media items is returned.",
example: new FavoriteStatusResponse(
FavoritedMediaItemIds: [Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")]
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = "/api/v1/users/me/favorites/status"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = "/api/v1/users/me/favorites/status"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/users/me/favorites/status"
}
}
);
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/users/me/favorites/status",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/users/me/favorites/status",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"FavoriteMediaKindIsInvalid",
"FavoriteMediaItemIdsCannotBeEmpty",
"FavoriteMediaItemIdsExceedMaximumCount",
"FavoriteMediaItemIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Favorites;
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
using Lumina.Contracts.Requests.Favorites;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.Favorites;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Favorites;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
/// <summary>
/// API endpoint for the <c>/users/me/favorites</c> route, for getting the favorites.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetFavoritesEndpoint : BaseEndpoint<GetFavoritesRequest, IResult>
{
private readonly IQueryHandler<GetFavoritesQuery, Result<PaginatedResponse<FavoriteItemResponse>>> _getFavoritesQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoritesEndpoint"/> class.
/// </summary>
/// <param name="getFavoritesQueryHandler">Injected service for handling get favorites queries.</param>
public GetFavoritesEndpoint(IQueryHandler<GetFavoritesQuery, Result<PaginatedResponse<FavoriteItemResponse>>> getFavoritesQueryHandler)
{
_getFavoritesQueryHandler = getFavoritesQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.GET);
Routes(ApiRoutes.Favorites.GET_FAVORITES);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets a page of the favorites of the current user.
/// </summary>
/// <param name="request">The request containing the optional media kind filter and the page bounds.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetFavoritesRequest request, CancellationToken cancellationToken)
{
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
// responses, and every response varies by the bearer token that authorized it.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Authorization";
Result<PaginatedResponse<FavoriteItemResponse>> result = await _getFavoritesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,166 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Favorites;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.Favorites;
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFavoritesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFavoritesEndpointSummary : Summary<GetFavoritesEndpoint, GetFavoritesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoritesEndpointSummary"/> class.
/// </summary>
public GetFavoritesEndpointSummary()
{
Summary = "Gets the favorites of the current user.";
Description = "Gets the favorites of the currently authenticated user, from the most recently favorited, across every kind of media item or restricted to one kind. The currentPage and perPage query parameters select the page, and count reports the number of favorites that match the filter. When neither parameter is provided, every matching favorite is returned in a single page. Each favorite carries the display details of the media item it references: the title, the collection, the creator and the cover art. A favorite whose media item was deleted, or whose media library the user can no longer access, is still returned, with isAvailable set to false and empty display details, so the user can see it and remove it. A favorite of another user is never returned.";
ExampleRequest = new GetFavoritesRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
CurrentPage: 1,
PerPage: 200
);
RequestParam(request => request.MediaKind, "The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted.");
RequestParam(request => request.CurrentPage, "The one based page of favorites to return. Optional; defaults to 1 when a page size is provided.");
RequestParam(request => request.PerPage, "The number of favorites per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every matching favorite is returned.");
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.Data, "The favorites of the requested page, from the most recently favorited.");
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.CurrentPage, "The current page number.");
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.PerPage, "The number of favorites retrieved per page.");
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.Count, "The total number of favorites that match the filter.");
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.NumberOfPages, "The total number of pages.");
ResponseParam<FavoriteItemResponse>(response => response.MediaKind, "The kind of the favorited media item.");
ResponseParam<FavoriteItemResponse>(response => response.MediaItemId, "The Id of the favorited media item.");
ResponseParam<FavoriteItemResponse>(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user.");
ResponseParam<FavoriteItemResponse>(response => response.LibraryId, "The Id of the media library that contains the media item.");
ResponseParam<FavoriteItemResponse>(response => response.Title, "The title of the media item.");
ResponseParam<FavoriteItemResponse>(response => response.CollectionId, "The Id of the collection that contains the media item, or the empty Guid when there is none.");
ResponseParam<FavoriteItemResponse>(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none.");
ResponseParam<FavoriteItemResponse>(response => response.CreatorId, "The Id of the creator of the media item, or the empty Guid when there is none.");
ResponseParam<FavoriteItemResponse>(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none.");
ResponseParam<FavoriteItemResponse>(response => response.CoverPath, "The path of the cover art of the media item, if available.");
Response(200, "The favorites of the current user are returned.",
example: new PaginatedResponse<FavoriteItemResponse>
{
Data =
[
new FavoriteItemResponse(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
IsAvailable: true,
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
Title: "The Show Must Go On",
CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
CollectionTitle: "Innuendo",
CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
CreatorName: "Queen",
CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg"
),
new FavoriteItemResponse(
MediaKind: FavoriteMediaKind.Book,
MediaItemId: Guid.Parse("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"),
IsAvailable: true,
LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"),
Title: "The Fellowship of the Ring",
CollectionId: Guid.Empty,
CollectionTitle: string.Empty,
CreatorId: Guid.Parse("8e9f0a1b-2c3d-4e4f-9a5b-6c7d8e9f0a1b"),
CreatorName: "J. R. R. Tolkien",
CoverPath: "/artwork/books/0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/cover.jpg"
),
new FavoriteItemResponse(
MediaKind: FavoriteMediaKind.MusicAlbum,
MediaItemId: Guid.Parse("9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c"),
IsAvailable: false,
LibraryId: Guid.Empty,
Title: string.Empty,
CollectionId: Guid.Empty,
CollectionTitle: string.Empty,
CreatorId: Guid.Empty,
CreatorName: string.Empty,
CoverPath: null
)
],
CurrentPage = 1,
PerPage = 200,
Count = 3,
NumberOfPages = 1
}
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = "/api/v1/users/me/favorites"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = "/api/v1/users/me/favorites"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/users/me/favorites"
}
}
);
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/users/me/favorites",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/users/me/favorites",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"FavoriteMediaKindIsInvalid"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Favorites;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
/// <summary>
/// API endpoint for the <c>/users/me/favorites/{mediaKind}/{mediaItemId}</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<RemoveFavoriteCommand, Result<Deleted>> _removeFavoriteCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpoint"/> class.
/// </summary>
/// <param name="removeFavoriteCommandHandler">Injected service for handling remove favorite commands.</param>
public RemoveFavoriteEndpoint(ICommandHandler<RemoveFavoriteCommand, Result<Deleted>> removeFavoriteCommandHandler)
{
_removeFavoriteCommandHandler = removeFavoriteCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.DELETE);
Routes(ApiRoutes.Favorites.REMOVE_FAVORITE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Removes a media item from the favorites of the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
// responses, and every response varies by the bearer token that authorized it.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Authorization";
// Take the kind and the unique identifier of the media item from the route, as raw strings so the validator reports a clean error for an unparseable value.
string? mediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString();
string? mediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString();
Result<Deleted> result = await _removeFavoriteCommandHandler.HandleAsync(new RemoveFavoriteCommand(mediaKind, mediaItemId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
/// <summary>
/// Class used for providing a textual description for the <see cref="RemoveFavoriteEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveFavoriteEndpointSummary : Summary<RemoveFavoriteEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointSummary"/> class.
/// </summary>
public RemoveFavoriteEndpointSummary()
{
Summary = "Removes a media item from the favorites of the current user.";
Description = "Removes the media item identified by its kind and its Id from the favorites of the currently authenticated user. The kind is the name of a kind of media item, such as MusicTrack, and is matched without regard to case. The media item itself is never deleted. The favorite is always the one of the authenticated user, so this route can never remove another user's favorite. The media library of the item is deliberately not checked, so a user can always remove their own favorite whose item was deleted or is no longer accessible. Removing is idempotent: an item that is not a favorite of the user already has the desired state, so the request succeeds without changing anything and without raising an event.";
Params["mediaKind"] = "The name of the kind of media item, matched case insensitively: MusicArtist, MusicAlbum, MusicTrack or Book.";
Params["mediaItemId"] = "The Id of the media item to remove from the favorites.";
Response(200, "The media item was successfully removed from the favorites.");
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
}
}
);
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(409, "The request failed because the database is busy or locked, or the favorite was changed by another request in a way that could not be reconciled. Removing a favorite that another request removed first succeeds.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "ConcurrencyConflict",
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/users/me/favorites/Unknown/not-a-guid",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"FavoriteMediaKindIsInvalid",
"FavoriteMediaItemIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.Playlists;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using System;
@@ -37,8 +38,7 @@ public class CreatePlaylistEndpointSummary : Summary<CreatePlaylistEndpoint, Cre
ResponseParam<PlaylistResponse>(response => response.Name, "The name of the playlist.");
ResponseParam<PlaylistResponse>(response => response.Description, "The description of the playlist, if applicable.");
ResponseParam<PlaylistResponse>(response => response.Type, "The kind of media the playlist holds.");
ResponseParam<PlaylistResponse>(response => response.Entries, "The ordered entries of the playlist.");
ResponseParam<PlaylistResponse>(response => response.EntryCount, "The total number of entries the playlist holds, even when only a window of them is returned.");
ResponseParam<PlaylistResponse>(response => response.Entries, "The page of ordered entries of the playlist, with its pagination metadata.");
ResponseParam<PlaylistResponse>(response => response.CreatedOnUtc, "The date and time when the playlist was created.");
ResponseParam<PlaylistResponse>(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable.");
@@ -48,8 +48,14 @@ public class CreatePlaylistEndpointSummary : Summary<CreatePlaylistEndpoint, Cre
Name: "Evening listening",
Description: "Quiet tracks for the end of the day.",
Type: PlaylistType.Music,
Entries: [],
EntryCount: 0,
Entries: new PaginatedResponse<PlaylistEntryResponse>
{
Data = [],
CurrentPage = 1,
PerPage = 200,
Count = 0,
NumberOfPages = 0
},
CreatedOnUtc: new DateTime(2026, 10, 21, 12, 0, 0, DateTimeKind.Utc),
UpdatedOnUtc: null
)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Playlists;
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Playlists;
@@ -7,7 +8,6 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Playlists;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -45,7 +45,7 @@ public class GetPlaylistEndpoint : BaseEndpoint<GetPlaylistRequest, IResult>
}
/// <summary>
/// Gets a window of the entries of a playlist of the current user.
/// Gets a page of the entries of a playlist of the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -57,12 +57,7 @@ public class GetPlaylistEndpoint : BaseEndpoint<GetPlaylistRequest, IResult>
HttpContext.Response.Headers["Vary"] = "Authorization";
// Take the unique identifier from the route.
string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString();
int offset = request.Offset ?? 0;
// The limit bounds one response window, not the size of the playlist. Clamping it keeps a crafted limit from turning the
// windowed read into one unbounded response, while the handler still validates the value independently.
int limit = Math.Clamp(request.Limit ?? PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE, 1, PlaylistWindow.MAXIMUM_ENTRY_WINDOW_SIZE);
Result<PlaylistResponse> result = await _getPlaylistQueryHandler
.HandleAsync(new GetPlaylistQuery(playlistId, offset, limit), cancellationToken).ConfigureAwait(false);
Result<PlaylistResponse> result = await _getPlaylistQueryHandler.HandleAsync(request.ToQuery(playlistId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Playlists;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.Playlists;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using System;
@@ -22,21 +23,20 @@ public class GetPlaylistEndpointSummary : Summary<GetPlaylistEndpoint, GetPlayli
public GetPlaylistEndpointSummary()
{
Summary = "Gets a playlist of the current user.";
Description = "Gets the playlist identified by its Id when it belongs to the currently authenticated user, together with a window of its ordered entries. The offset and limit query parameters select the window, and entryCount reports the total number of entries. The limit is a response-window bound of at most 1000 entries and does not cap the size of the playlist. Each entry carries the media item Id and the media item kind it references, and a music track also carries the display details needed to play it: the library, album and artist Ids, the title, the album title, the artist name, the duration and the cover art. An entry whose media item was deleted is still returned, with empty display details.";
Description = "Gets the playlist identified by its Id when it belongs to the currently authenticated user, together with a page of its ordered entries. The currentPage and perPage query parameters select the page, and entries.count reports the total number of entries. When neither parameter is provided, every entry is returned in a single page. Each entry carries the media item Id and the media item kind it references, and a music track also carries the display details needed to play it: the library, album and artist Ids, the title, the album title, the artist name, the duration and the cover art. An entry whose media item was deleted is still returned, with empty display details.";
ExampleRequest = new GetPlaylistRequest(
Offset: 0,
Limit: 200
CurrentPage: 1,
PerPage: 200
);
RequestParam(request => request.Offset, "The zero based position of the first entry to return. Optional; defaults to 0.");
RequestParam(request => request.Limit, "The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.");
RequestParam(request => request.CurrentPage, "The one based page of entries to return. Optional; defaults to 1 when a page size is provided.");
RequestParam(request => request.PerPage, "The number of entries per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every entry is returned.");
ResponseParam<PlaylistResponse>(response => response.Id, "The Id of the playlist.");
ResponseParam<PlaylistResponse>(response => response.Name, "The name of the playlist.");
ResponseParam<PlaylistResponse>(response => response.Description, "The description of the playlist, if applicable.");
ResponseParam<PlaylistResponse>(response => response.Type, "The kind of media the playlist holds.");
ResponseParam<PlaylistResponse>(response => response.Entries, "The ordered entries of the playlist.");
ResponseParam<PlaylistResponse>(response => response.EntryCount, "The total number of entries the playlist holds, even when only a window of them is returned.");
ResponseParam<PlaylistResponse>(response => response.Entries, "The page of ordered entries of the playlist, with its pagination metadata.");
ResponseParam<PlaylistResponse>(response => response.CreatedOnUtc, "The date and time when the playlist was created.");
ResponseParam<PlaylistResponse>(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable.");
@@ -46,24 +46,30 @@ public class GetPlaylistEndpointSummary : Summary<GetPlaylistEndpoint, GetPlayli
Name: "Evening listening",
Description: "Quiet tracks for the end of the day.",
Type: PlaylistType.Music,
Entries:
[
new PlaylistEntryResponse(
Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"),
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
MediaItemType: PlaylistMediaItemType.MusicTrack,
Position: 0,
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
MediaItemTitle: "The Show Must Go On",
CollectionTitle: "Innuendo",
CreatorName: "Queen",
DurationInSeconds: 262,
CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg"
)
],
EntryCount: 1,
Entries: new PaginatedResponse<PlaylistEntryResponse>
{
Data =
[
new PlaylistEntryResponse(
Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"),
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
MediaItemType: PlaylistMediaItemType.MusicTrack,
Position: 0,
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
MediaItemTitle: "The Show Must Go On",
CollectionTitle: "Innuendo",
CreatorName: "Queen",
DurationInSeconds: 262,
CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg"
)
],
CurrentPage = 1,
PerPage = 200,
Count = 1,
NumberOfPages = 1
},
CreatedOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc)
)
@@ -124,8 +130,7 @@ public class GetPlaylistEndpointSummary : Summary<GetPlaylistEndpoint, GetPlayli
{
"General.Validation", new[]
{
"PlaylistIdCannotBeEmpty",
"PlaylistEntryWindowOffsetIsInvalid"
"PlaylistIdCannotBeEmpty"
}
}
},
@@ -1,38 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for a paginated collection of lightweight album elements, together with pagination metadata.
/// </summary>
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
public class PaginatedMusicAlbumLiteDto
{
/// <summary>
/// Gets or sets the collection of lightweight album elements associated with this instance.
/// </summary>
public IReadOnlyList<MusicAlbumLiteDto> Data { get; set; } = [];
/// <summary>
/// Gets or sets the current page number in a paginated collection.
/// </summary>
public int CurrentPage { get; set; }
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public int PerPage { get; set; }
/// <summary>
/// Gets or sets the total number of elements available in the paginated result set.
/// </summary>
public int Count { get; set; }
/// <summary>
/// Gets or sets the total number of pages based on elements available in the result set and per page.
/// </summary>
public int NumberOfPages { get; set; }
}
@@ -1,38 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for a paginated collection of lightweight music artist elements, together with pagination metadata.
/// </summary>
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
public class PaginatedMusicArtistLiteDto
{
/// <summary>
/// Gets or sets the collection of lightweight music artist elements associated with this instance.
/// </summary>
public IReadOnlyList<MusicArtistLiteDto> Data { get; set; } = [];
/// <summary>
/// Gets or sets the current page number in a paginated collection.
/// </summary>
public int CurrentPage { get; set; }
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public int PerPage { get; set; }
/// <summary>
/// Gets or sets the total number of elements available in the paginated result set.
/// </summary>
public int Count { get; set; }
/// <summary>
/// Gets or sets the total number of pages based on elements available in the result set and per page.
/// </summary>
public int NumberOfPages { get; set; }
}
@@ -1,38 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for a paginated collection of lightweight track elements, together with pagination metadata.
/// </summary>
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
public class PaginatedMusicTrackLiteDto
{
/// <summary>
/// Gets or sets the collection of lightweight track elements associated with this instance.
/// </summary>
public IReadOnlyList<MusicTrackLiteDto> Data { get; set; } = [];
/// <summary>
/// Gets or sets the current page number in a paginated collection.
/// </summary>
public int CurrentPage { get; set; }
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public int PerPage { get; set; }
/// <summary>
/// Gets or sets the total number of elements available in the paginated result set.
/// </summary>
public int Count { get; set; }
/// <summary>
/// Gets or sets the total number of pages based on elements available in the result set and per page.
/// </summary>
public int NumberOfPages { get; set; }
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Common;
/// <summary>
/// Data transfer object for a page of elements together with its pagination metadata.
/// </summary>
/// <typeparam name="T">The type of the elements of the page.</typeparam>
/// <param name="Data">The elements of the requested page.</param>
/// <param name="CurrentPage">The one based number of the returned page.</param>
/// <param name="PerPage">The number of elements requested per page.</param>
/// <param name="Count">The total number of elements that match the filter, even when only a page of them is returned.</param>
/// <param name="NumberOfPages">The total number of pages that match the filter.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}; Count: {Count}")]
public sealed record PaginatedDto<T>(
List<T> Data,
int CurrentPage,
int PerPage,
int Count,
int NumberOfPages
);
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
/// <summary>
/// Data transfer object for a favorite of the current user.
/// </summary>
/// <param name="Id">The Id of the favorite.</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="FavoritedOnUtc">The date and time when the media item was favorited.</param>
[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public sealed record FavoriteDto(
Guid Id,
FavoriteMediaKind MediaKind,
Guid MediaItemId,
DateTime FavoritedOnUtc
);
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
/// <summary>
/// Data transfer object for a favorite of the current user together with the display details of the media item it references.
/// </summary>
/// <param name="MediaKind">The kind of the favorited media item.</param>
/// <param name="MediaItemId">The Id of the favorited media item.</param>
/// <param name="IsAvailable">Whether the media item still exists and can be accessed by the user. When <see langword="false"/>, every display field is empty.</param>
/// <param name="LibraryId">The Id of the media library that contains the media item, or an empty Guid when the item is not available.</param>
/// <param name="Title">The title of the media item, or an empty string when the item is not available.</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("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public sealed record FavoriteItemDto(
FavoriteMediaKind MediaKind,
Guid MediaItemId,
bool IsAvailable,
Guid LibraryId,
string Title,
Guid CollectionId,
string CollectionTitle,
Guid CreatorId,
string CreatorName,
string? CoverPath
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
/// <summary>
/// Data transfer object that tells which of the checked media items are favorites of the current user.
/// </summary>
/// <param name="FavoritedMediaItemIds">The Ids, among the checked ones, of the media items that are favorites of the current user.</param>
[DebuggerDisplay("Favorited: {FavoritedMediaItemIds.Count}")]
public sealed record FavoriteStatusDto(
List<Guid> FavoritedMediaItemIds
);
@@ -1,38 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Libraries;
/// <summary>
/// Data transfer object for a paginated collection of lightweight book elements, together with pagination metadata.
/// </summary>
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
public class PaginatedBookLiteDto
{
/// <summary>
/// Gets or sets the collection of lightweight book elements associated with this instance.
/// </summary>
public IReadOnlyList<BookLiteDto> Data { get; set; } = [];
/// <summary>
/// Gets or sets the current page number in a paginated collection.
/// </summary>
public int CurrentPage { get; set; }
/// <summary>
/// Gets or sets the number of items to include per page in paginated results.
/// </summary>
public int PerPage { get; set; }
/// <summary>
/// Gets or sets the total number of elements available in the paginated result set.
/// </summary>
public int Count { get; set; }
/// <summary>
/// Gets or sets the total number of pages based on elements available in the result set and per page.
/// </summary>
public int NumberOfPages { get; set; }
}
@@ -1,21 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Enums.Playlists;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Playlists;
/// <summary>
/// Data transfer object for a playlist together with its ordered entries.
/// Data transfer object for a playlist together with a page of its ordered entries.
/// </summary>
/// <param name="Id">The Id of the playlist.</param>
/// <param name="Name">The name of the playlist.</param>
/// <param name="Description">The description of the playlist, if applicable.</param>
/// <param name="Type">The kind of media the playlist holds.</param>
/// <param name="EntryCount">The number of entries the playlist holds, even when only a window of them is returned.</param>
/// <param name="Entries">The ordered entries of the requested window of the playlist.</param>
/// <param name="Entries">The page of ordered entries of the playlist, together with its pagination metadata.</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}; Entries: {Entries.Count}")]
@@ -24,8 +23,7 @@ public sealed record PlaylistDto(
string Name,
string? Description,
PlaylistType Type,
int EntryCount,
List<PlaylistEntryDto> Entries,
PaginatedDto<PlaylistEntryDto> Entries,
DateTime CreatedOnUtc,
DateTime? UpdatedOnUtc
);
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Enums.Favorites;
/// <summary>
/// Enumeration for the kinds of media item that can be marked as a favorite.
/// </summary>
[DebuggerDisplay("{ToString()}")]
public enum FavoriteMediaKind
{
/// <summary>
/// A favorite that references an artist of a music library.
/// </summary>
MusicArtist,
/// <summary>
/// A favorite that references an album of a music library.
/// </summary>
MusicAlbum,
/// <summary>
/// A favorite that references a track of a music library.
/// </summary>
MusicTrack,
/// <summary>
/// A favorite that references a book of a book library.
/// </summary>
Book,
/// <summary>
/// A favorite that references a video file. Planned: video libraries are not catalogued yet, so this kind cannot be favorited.
/// </summary>
Video,
/// <summary>
/// A favorite that references a photo. Planned: photo libraries are not catalogued yet, so this kind cannot be favorited.
/// </summary>
Photo,
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Favorites;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
/// <summary>
/// Represents a request for marking a media item as a favorite of the current user.
/// </summary>
/// <param name="MediaKind">The kind of the media item to favorite. Required.</param>
/// <param name="MediaItemId">The Id of the media item to favorite. Required.</param>
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public record AddFavoriteRequest(
FavoriteMediaKind? MediaKind,
Guid? MediaItemId
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Favorites;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
/// <summary>
/// Represents a request 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. Required.</param>
/// <param name="MediaItemIds">The Ids of the media items to check, from 1 to 100. Required.</param>
[DebuggerDisplay("MediaKind: {MediaKind}")]
public record GetFavoriteStatusRequest(
FavoriteMediaKind? MediaKind,
List<Guid>? MediaItemIds
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Favorites;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
/// <summary>
/// Represents a request for getting a page of the favorites of the current user.
/// </summary>
/// <param name="MediaKind">The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted.</param>
/// <param name="CurrentPage">The one based page of favorites to return. Optional; defaults to 1.</param>
/// <param name="PerPage">The number of favorites per page. Optional; defaults to 200.</param>
[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetFavoritesRequest(
FavoriteMediaKind? MediaKind,
int? CurrentPage,
int? PerPage
);
@@ -5,12 +5,12 @@ using System.Diagnostics;
namespace Lumina.Presentation.Web.Common.Requests.Playlists;
/// <summary>
/// Represents a request for getting a window of the entries of a playlist of the current user.
/// Represents a request for getting a page of the entries of a playlist of the current user.
/// </summary>
/// <param name="Offset">The zero based position of the first entry to return. Optional; defaults to 0.</param>
/// <param name="Limit">The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.</param>
[DebuggerDisplay("Offset: {Offset}; Limit: {Limit}")]
/// <param name="CurrentPage">The one based page of entries to return. Optional; defaults to 1.</param>
/// <param name="PerPage">The number of entries per page. Optional; defaults to 200.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetPlaylistRequest(
int? Offset,
int? Limit
int? CurrentPage,
int? PerPage
);
@@ -0,0 +1,18 @@
namespace Lumina.Presentation.Web.Common.Routes;
/// <summary>
/// Class for the collection of remote API routes called by this Web application.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the favorites endpoints of the remote API.
/// </summary>
public static class Favorites
{
public const string GET_FAVORITES = "users/me/favorites";
public const string ADD_FAVORITE = "users/me/favorites";
public const string REMOVE_FAVORITE = "users/me/favorites/{mediaKind}/{mediaItemId}";
public const string GET_FAVORITE_STATUS = "users/me/favorites/status";
}
}
@@ -0,0 +1,19 @@
namespace Lumina.Presentation.Web.Common.Routes;
/// <summary>
/// Class for the collection of routes defined in the Web application.
/// </summary>
public static partial class WebRoutes
{
/// <summary>
/// Routes for the favorites pages.
/// </summary>
public static class Favorites
{
public const string INDEX = "{culture}/favorites";
public const string GET_FAVORITES = "{culture}/favorites/api-get-favorites";
public const string GET_FAVORITE_STATUS = "{culture}/favorites/api-get-favorite-status";
public const string ADD_FAVORITE = "{culture}/favorites/api-add-favorite";
public const string REMOVE_FAVORITE = "{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite";
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/api-add-favorite</c> route.
/// </summary>
public class AddFavoriteEndpoint : BaseEndpoint<AddFavoriteRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="AddFavoriteEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public AddFavoriteEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.POST);
Routes(WebRoutes.Favorites.ADD_FAVORITE);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
EnableAntiforgery();
}
/// <summary>
/// Marks a media item as a favorite of the current user.
/// </summary>
/// <param name="request">The request containing the kind and the Id of the media item to favorite.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddFavoriteRequest request, CancellationToken cancellationToken)
{
FavoriteDto favorite = await _apiHttpClient.PostAsync<FavoriteDto, AddFavoriteRequest>(ApiRoutes.Favorites.ADD_FAVORITE, request, cancellationToken).ConfigureAwait(false);
return JsonSuccess(favorite);
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddFavoriteEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddFavoriteEndpointSummary : Summary<AddFavoriteEndpoint, AddFavoriteRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddFavoriteEndpointSummary"/> class.
/// </summary>
public AddFavoriteEndpointSummary()
{
Summary = "Marks a media item as a favorite of the current user.";
Description = "Proxies the request that marks a media item as a favorite to the API server. Adding an item that is already a favorite is not an error: the existing favorite is returned.";
ExampleRequest = new AddFavoriteRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")
);
RequestParam(request => request.MediaKind, "The kind of the media item to favorite: MusicArtist, MusicAlbum, MusicTrack or Book. Required.");
RequestParam(request => request.MediaItemId, "The Id of the media item to favorite. Required.");
Response(200, "The media item is a favorite and the favorite is returned.",
example: new SuccessResponse<FavoriteDto>(true, new FavoriteDto(
Id: Guid.Parse("4b7a2c10-5d3e-4f68-9a1b-0c2d3e4f5a6b"),
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
FavoritedOnUtc: new DateTime(2026, 10, 21, 9, 30, 0, DateTimeKind.Utc)))
);
}
}
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/api-get-favorite-status</c> route.
/// </summary>
public class GetFavoriteStatusEndpoint : BaseEndpoint<GetFavoriteStatusRequest, IResult>
{
// The API accepts at most 100 Ids per check, so one more is forwarded to let its validator report an oversized list.
private const int MAXIMUM_FORWARDED_MEDIA_ITEM_COUNT = 101;
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetFavoriteStatusEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Favorites.GET_FAVORITE_STATUS);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
}
/// <summary>
/// Retrieves which of the given media items are favorites of the current user.
/// </summary>
/// <param name="request">The request containing the kind and the Ids of the media items to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetFavoriteStatusRequest request, CancellationToken cancellationToken)
{
// The favorites belong to the authenticated user, so no intermediary may store them, and the response varies by the sign in cookie.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Cookie";
// The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL.
// A missing kind or Id list is left out, so that the API reports the validation error itself.
List<string> queryParameters = [];
if (request.MediaKind is not null)
queryParameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
// The forwarded list is bounded, so the upstream URL stays bounded too.
foreach (Guid mediaItemId in (request.MediaItemIds ?? []).Take(MAXIMUM_FORWARDED_MEDIA_ITEM_COUNT))
queryParameters.Add($"mediaItemIds={mediaItemId}");
string url = queryParameters.Count == 0 ? ApiRoutes.Favorites.GET_FAVORITE_STATUS : $"{ApiRoutes.Favorites.GET_FAVORITE_STATUS}?{string.Join('&', queryParameters)}";
FavoriteStatusDto status = await _apiHttpClient.GetAsync<FavoriteStatusDto>(url, cancellationToken).ConfigureAwait(false);
return JsonSuccess(status);
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFavoriteStatusEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFavoriteStatusEndpointSummary : Summary<GetFavoriteStatusEndpoint, GetFavoriteStatusRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointSummary"/> class.
/// </summary>
public GetFavoriteStatusEndpointSummary()
{
Summary = "Gets which media items are favorites of the current user.";
Description = "Proxies the request that finds out which of the given media items of one kind are favorites of the current user to the API server. The mediaItemIds query parameter is repeated, once per Id.";
ExampleRequest = new GetFavoriteStatusRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemIds:
[
Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
Guid.Parse("5a4b3c2d-1e0f-4a9b-8c7d-6e5f4a3b2c1d")
]
);
RequestParam(request => request.MediaKind, "The kind of the media items to check: MusicArtist, MusicAlbum, MusicTrack or Book. Required.");
RequestParam(request => request.MediaItemIds, "The Ids of the media items to check, from 1 to 100, sent as a repeated mediaItemIds query parameter. Required.");
Response(200, "The Ids, among the checked ones, of the media items that are favorites of the current user are returned.",
example: new SuccessResponse<FavoriteStatusDto>(true, new FavoriteStatusDto(
FavoritedMediaItemIds: [Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")]))
);
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/api-get-favorites</c> route.
/// </summary>
public class GetFavoritesEndpoint : BaseEndpoint<GetFavoritesRequest, IResult>
{
private const int DEFAULT_FAVORITE_PAGE_SIZE = 200;
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoritesEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetFavoritesEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Favorites.GET_FAVORITES);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
}
/// <summary>
/// Retrieves a page of the favorites of the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetFavoritesRequest request, CancellationToken cancellationToken)
{
// The favorites belong to the authenticated user, so no intermediary may store them, and the response varies by the sign in cookie.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Cookie";
// The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL.
// The page bounds are normalized by the API pagination data, exactly like every other paginated collection of the application.
int currentPage = request.CurrentPage ?? 1;
int perPage = request.PerPage ?? DEFAULT_FAVORITE_PAGE_SIZE;
string url = ApiRoutes.Favorites.GET_FAVORITES + $"?currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}&perPage={perPage.ToString(CultureInfo.InvariantCulture)}";
if (request.MediaKind is not null)
url += $"&mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}";
PaginatedDto<FavoriteItemDto> favorites = await _apiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(url, cancellationToken).ConfigureAwait(false);
return JsonSuccess(favorites);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFavoritesEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFavoritesEndpointSummary : Summary<GetFavoritesEndpoint, GetFavoritesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoritesEndpointSummary"/> class.
/// </summary>
public GetFavoritesEndpointSummary()
{
Summary = "Gets the favorites of the current user.";
Description = "Proxies the request that gets a page of the favorites of the current user, from the most recently favorited, to the API server. The currentPage and perPage query parameters select the page, and count reports the total number of favorites that match the filter. Each favorite carries the display details of its media item.";
ExampleRequest = new GetFavoritesRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
CurrentPage: 1,
PerPage: 200
);
RequestParam(request => request.MediaKind, "The kind of media item to restrict the favorites to: MusicArtist, MusicAlbum, MusicTrack or Book. Optional; every kind is returned when omitted.");
RequestParam(request => request.CurrentPage, "The one based page of favorites to return. Optional; defaults to 1.");
RequestParam(request => request.PerPage, "The number of favorites per page. Optional; defaults to 200.");
Response(200, "The requested page of the favorites of the current user is returned.",
example: new SuccessResponse<PaginatedDto<FavoriteItemDto>>(true, new PaginatedDto<FavoriteItemDto>(
Data:
[
new FavoriteItemDto(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
IsAvailable: true,
LibraryId: Guid.Parse("1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"),
Title: "Time",
CollectionId: Guid.Parse("7c6b5a49-3827-4165-9d0e-1f2a3b4c5d6e"),
CollectionTitle: "The Dark Side of the Moon",
CreatorId: Guid.Parse("2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a"),
CreatorName: "Pink Floyd",
CoverPath: "covers/dark-side-of-the-moon.jpg")
],
CurrentPage: 1,
PerPage: 200,
Count: 1,
NumberOfPages: 1))
);
}
}
@@ -0,0 +1,108 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.Index;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites</c> route.
/// </summary>
public class FavoritesIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
// The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath.
private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Favorites.Index";
private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web";
// The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope.
private const string VIEW_PAGE_KEY = "favorites/index";
private readonly IUrlService _urlService;
private readonly ThemePageRenderer _themePageRenderer;
private readonly IAntiforgery _antiforgery;
private readonly IStringLocalizer _localizer;
/// <summary>
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpoint"/> class.
/// </summary>
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
/// <param name="themePageRenderer">Injected service for rendering themed pages.</param>
/// <param name="antiforgery">Injected service for anti-forgery token handling.</param>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the view resources.</param>
public FavoritesIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory)
{
_urlService = urlService;
_themePageRenderer = themePageRenderer;
_antiforgery = antiforgery;
_localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION);
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Favorites.INDEX);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
}
/// <summary>
/// Displays the favorites of the current user across media kinds, rendered by the active theme with a fallback to the Razor view.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// The page shows the favorites of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Cookie";
// The page removes favorites, which submit through the form anti-forgery token, so a fresh token is issued for it.
AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext);
string title = _localizer["Title"].Value;
// The media item link templates carry the all-zero Guid placeholders of their route values, in route order, which the page replaces
// one at a time. The remove template keeps its named mediaKind and mediaItemId route placeholders instead, so those two values do not
// depend on the segment order. The detail pages of the media items expect the Id of their media library in the libraryId query
// parameter, which the page appends to the link from the favorite item.
ThemePageDto pageModel = new()
{
PageKey = VIEW_PAGE_KEY,
Title = title,
Description = string.Empty,
PageData = new Dictionary<string, object?>
{
["getFavoritesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITES) ?? string.Empty,
["getFavoriteStatusUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITE_STATUS) ?? string.Empty,
["addFavoriteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.ADD_FAVORITE) ?? string.Empty,
["removeFavoriteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.REMOVE_FAVORITE) ?? string.Empty,
["artistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, new { artistId = default(Guid) }) ?? string.Empty,
["albumUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.ALBUM, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty,
["trackUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) }) ?? string.Empty,
["bookUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) }) ?? string.Empty,
["antiforgeryToken"] = antiforgeryTokens.RequestToken,
["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer)
}
};
Result<ThemePageRenderResultDto> sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false);
if (sectionResult.IsFailure)
return View("/Core/Views/Favorites/Index.cshtml", viewData: new Dictionary<string, object?> { ["Title"] = title });
return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary<string, object?> { ["Title"] = title });
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.Index;
/// <summary>
/// Class used for providing a textual description for the <see cref="FavoritesIndexViewEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class FavoritesIndexViewEndpointSummary : Summary<FavoritesIndexViewEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointSummary"/> class.
/// </summary>
public FavoritesIndexViewEndpointSummary()
{
Summary = "Renders the favorites page.";
Description = "Renders the page that lists the favorites of the current user across media kinds and removes them.";
Response(200, "The favorites page is rendered.");
}
}
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more