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,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>