Extends the music library listings with covers, sorting and alpha filtering.

This commit is contained in:
BinaryAlley committed 2026-10-13 13:26:14 +03:00
1 parent 0019821e87
commit 9d82f283e4
69 files changed
+3613 -268

No files matched your search

@@ -1,5 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
@@ -23,4 +25,19 @@ public sealed record AlbumLiteRow
/// Gets the number of tracks of the release.
/// </summary>
public int TotalTracks { get; init; }
/// <summary>
/// Gets the path of the image representing the album, if available.
/// </summary>
public string? CoverPath { get; init; }
/// <summary>
/// Gets the release year of the album (the re-release year, if available, or the original release year), if known.
/// </summary>
public int? ReleaseYear { get; init; }
/// <summary>
/// Gets the set of types of the release.
/// </summary>
public List<MusicReleaseType>? ReleaseTypes { get; init; }
}
@@ -18,4 +18,9 @@ public sealed record ArtistLiteRow
/// Gets the name of the artist.
/// </summary>
public required string Name { get; init; }
/// <summary>
/// Gets the path of the image representing the artist, if available.
/// </summary>
public string? CoverPath { get; init; }
}
@@ -28,4 +28,9 @@ public sealed record TrackLiteRow
/// Gets the number of the disc the track belongs to, if applicable.
/// </summary>
public int? DiscNumber { get; init; }
/// <summary>
/// Gets the duration of the track in seconds.
/// </summary>
public int DurationInSeconds { get; init; }
}
@@ -157,8 +157,10 @@ public static class AlbumEntityMapping
/// Converts <paramref name="repositoryEntity"/> to <see cref="AlbumResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="coverPath">The optional path of the image representing the album.</param>
/// <param name="artwork">The optional stored artwork of the album, in display order.</param>
/// <returns>The converted response entity.</returns>
public static AlbumResponse ToResponse(this AlbumEntity repositoryEntity)
public static AlbumResponse ToResponse(this AlbumEntity repositoryEntity, string? coverPath = null, IReadOnlyList<MediaArtworkDto>? artwork = null)
{
ReleaseInfoDto releaseInfo = new(
repositoryEntity.OriginalReleaseDate,
@@ -220,7 +222,9 @@ public static class AlbumEntityMapping
repositoryEntity.UpdatedOnUtc,
[.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))],
[.. repositoryEntity.Ratings.ToResponses()],
[.. repositoryEntity.Tracks.Select(track => track.ToResponse())]);
[.. repositoryEntity.Tracks.Select(track => track.ToResponse())],
coverPath,
artwork ?? []);
}
/// <summary>
@@ -24,7 +24,10 @@ public static class AlbumLiteRowMapping
return new AlbumLiteResponse(
readModel.Id,
readModel.Title,
readModel.TotalTracks);
readModel.TotalTracks,
readModel.CoverPath,
readModel.ReleaseYear,
readModel.ReleaseTypes);
}
/// <summary>
@@ -147,8 +147,9 @@ public static class ArtistEntityMapping
/// Converts <paramref name="repositoryEntity"/> to <see cref="ArtistResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="coverPath">The optional path of the image representing the artist.</param>
/// <returns>The converted response entity.</returns>
public static ArtistResponse ToResponse(this ArtistEntity repositoryEntity)
public static ArtistResponse ToResponse(this ArtistEntity repositoryEntity, string? coverPath = null)
{
MusicArtistMetadataDto metadata = new(
repositoryEntity.Name,
@@ -178,7 +179,8 @@ public static class ArtistEntityMapping
repositoryEntity.UpdatedOnUtc,
[.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))],
[.. repositoryEntity.Ratings.ToResponses()],
[.. repositoryEntity.Albums.Select(album => album.ToResponse())]);
[.. repositoryEntity.Albums.Select(album => album.ToResponse())],
coverPath);
}
/// <summary>
@@ -23,7 +23,8 @@ public static class ArtistLiteRowMapping
{
return new ArtistLiteResponse(
readModel.Id,
readModel.Name);
readModel.Name,
readModel.CoverPath);
}
/// <summary>
@@ -30,6 +30,10 @@ public static class GetArtistsLiteRequestMapping
return new GetArtistsLiteQuery(
libraryId,
paginationData,
request.SearchTerm);
request.SearchTerm,
request.FilterAlphaKey,
request.ShouldIgnoreThePrefixForAlphaPicker,
request.SortBy,
request.SortOrder);
}
}
@@ -25,7 +25,8 @@ public static class TrackLiteRowMapping
readModel.Id,
readModel.Title,
readModel.TrackNumber,
readModel.DiscNumber);
readModel.DiscNumber,
readModel.DurationInSeconds);
}
/// <summary>
@@ -8,11 +8,15 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -88,6 +92,21 @@ public class GetAlbumQueryHandler : IQueryHandler<GetAlbumQuery, Result<AlbumRes
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
return existingAlbum.ToResponse();
// The artwork of an album is stored in the MusicArtwork table, not on the album row, so it is loaded to expose the cover
// and every other stored piece of artwork.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? coverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
// Only the artwork whose file has already been stored can be presented, so the ones that are still pending resolution are left out.
List<MediaArtworkDto> artwork = [.. getArtworkResult.Value
.Where(storedArtwork => !string.IsNullOrWhiteSpace(storedArtwork.FileName))
.Select(storedArtwork => new MediaArtworkDto(storedArtwork.ArtworkType, storedArtwork.Ordinal, storedArtwork.FileName!))];
return existingAlbum.ToResponse(coverPath, artwork);
}
}
@@ -11,8 +11,11 @@ using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.A
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -87,6 +90,15 @@ public class GetArtistQueryHandler : IQueryHandler<GetArtistQuery, Result<Artist
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
return existingArtist.ToResponse();
// The artwork of the artist is stored separately from the artist, so it is loaded to expose the cover of the artist in the response.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? coverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
return existingArtist.ToResponse(coverPath);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Diagnostics;
#endregion
@@ -12,9 +13,17 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists
/// <param name="LibraryId">The unique identifier of the media library whose artists are retrieved, taken from the route.</param>
/// <param name="PaginationData">The object containing the requested pagination data.</param>
/// <param name="SearchTerm">The search term used to filter the artists by name.</param>
/// <param name="FilterAlphaKey">The alpha key used to filter the artists by the first character of their name.</param>
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not.</param>
/// <param name="SortBy">The name of the field by which to sort the results.</param>
/// <param name="SortOrder">The direction in which to sort the results.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetArtistsLiteQuery(
string? LibraryId,
PaginationDataDto? PaginationData,
string? SearchTerm
string? SearchTerm,
string? FilterAlphaKey,
bool ShouldIgnoreThePrefixForAlphaPicker,
string? SortBy,
SortOrder? SortOrder
) : IQuery;
@@ -78,12 +78,16 @@ public class GetArtistsLiteQueryHandler : IQueryHandler<GetArtistsLiteQuery, Res
LibraryFilterDto filter = new()
{
LibraryId = libraryId,
SearchTerm = query.SearchTerm
SearchTerm = query.SearchTerm,
FilterAlphaKey = query.FilterAlphaKey,
ShouldIgnoreThePrefixForAlphaPicker = query.ShouldIgnoreThePrefixForAlphaPicker
};
Result<PaginatedResultDto<ArtistLiteRow>> getArtistsResult = await _unitOfWork.ArtistRepository.GetAllLiteAsync(
query.PaginationData,
filterModel: filter,
query.SortBy,
query.SortOrder,
filter,
cancellationToken: cancellationToken).ConfigureAwait(false);
return getArtistsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
@@ -26,5 +27,14 @@ public class GetArtistsLiteQueryValidator : AbstractValidator<GetArtistsLiteQuer
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// The alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can
// derive the key of a name unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter.
RuleFor(query => query.FilterAlphaKey)
.Must(alphaKey => alphaKey is null
|| alphaKey == LibraryItemAlphaKeys.NUMBER
|| alphaKey == LibraryItemAlphaKeys.SYMBOL
|| (alphaKey.Length == 1 && char.IsAsciiLetter(alphaKey[0])))
.WithError(Errors.Library.InvalidFilterAlphaKey);
}
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for a stored piece of artwork of a media item.
/// </summary>
/// <param name="Type">The type of the artwork, like the cover or the back of the media item.</param>
/// <param name="Ordinal">The ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered.</param>
/// <param name="Path">The relative path of the stored artwork file.</param>
[DebuggerDisplay("Type: {Type}, Ordinal: {Ordinal}, Path: {Path}")]
public sealed record MediaArtworkDto(
ArtworkType Type,
int Ordinal,
string Path
);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Diagnostics;
#endregion
@@ -10,9 +11,21 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis
/// <param name="CurrentPage">The page of results to retrieve. Optional.</param>
/// <param name="PerPage">The maximum number of artists to retrieve per page. Optional.</param>
/// <param name="SearchTerm">The search term used to filter the artists by name. Optional.</param>
/// <param name="FilterAlphaKey">
/// The alpha key used to filter the results by the first character of their name, for the alpha picker. Optional.
/// Can be <see langword="null"/> to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter,
/// "#" to filter by names whose first character is a digit, or "*" to filter by names whose first character is neither a letter nor a digit.
/// </param>
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not. Optional.</param>
/// <param name="SortBy">The name of the field by which to sort the results. Optional.</param>
/// <param name="SortOrder">The direction in which to sort the results. Optional.</param>
[DebuggerDisplay("SearchTerm: {SearchTerm}")]
public record GetArtistsLiteRequest(
int? CurrentPage,
int? PerPage,
string? SearchTerm
string? SearchTerm,
string? FilterAlphaKey,
bool ShouldIgnoreThePrefixForAlphaPicker,
string? SortBy,
SortOrder? SortOrder
);
@@ -1,5 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
@@ -11,9 +13,15 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albu
/// <param name="Id">The Id of the album.</param>
/// <param name="Title">The title of the album.</param>
/// <param name="TotalTracks">The number of tracks of the release.</param>
/// <param name="CoverPath">The path of the image representing the album, if available.</param>
/// <param name="ReleaseYear">The release year of the album (the re-release year, if available, or the original release year), if known.</param>
/// <param name="ReleaseTypes">The set of types of the release.</param>
[DebuggerDisplay("Title: {Title}")]
public record AlbumLiteResponse(
Guid Id,
string Title,
int TotalTracks
int TotalTracks,
string? CoverPath,
int? ReleaseYear,
List<MusicReleaseType>? ReleaseTypes
);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
@@ -32,6 +33,8 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albu
/// <param name="Contributors">The list of references to the media contributors that performed on the album, each with the role they played.</param>
/// <param name="Ratings">The list of ratings for this album.</param>
/// <param name="Tracks">The list of tracks of the album.</param>
/// <param name="CoverPath">The path of the image representing the album, if available.</param>
/// <param name="Artwork">The stored artwork of the album, in display order, so that all of its pieces can be presented, not just the cover.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AlbumResponse(
Guid Id,
@@ -51,5 +54,7 @@ public record AlbumResponse(
DateTime? UpdatedOnUtc,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings,
List<TrackResponse>? Tracks
List<TrackResponse>? Tracks,
string? CoverPath,
IReadOnlyList<MediaArtworkDto> Artwork
);
@@ -10,8 +10,10 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Arti
/// </summary>
/// <param name="Id">The Id of the artist.</param>
/// <param name="Name">The name of the artist.</param>
/// <param name="CoverPath">The path of the image representing the artist, if available.</param>
[DebuggerDisplay("Name: {Name}")]
public record ArtistLiteResponse(
Guid Id,
string Name
string Name,
string? CoverPath
);
@@ -25,6 +25,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Arti
/// <param name="Contributors">The list of references to the media contributors that make up the artist, each with the role they played.</param>
/// <param name="Ratings">The list of ratings for this artist.</param>
/// <param name="Albums">The list of albums of the artist, each with its own list of tracks.</param>
/// <param name="CoverPath">The path of the image representing the artist, if available.</param>
[DebuggerDisplay("Name: {Metadata.Name}")]
public record ArtistResponse(
Guid Id,
@@ -38,5 +39,6 @@ public record ArtistResponse(
DateTime? UpdatedOnUtc,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings,
List<AlbumResponse>? Albums
List<AlbumResponse>? Albums,
string? CoverPath
);
@@ -12,10 +12,12 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Trac
/// <param name="Title">The title of the track.</param>
/// <param name="TrackNumber">The number of the track on its disc.</param>
/// <param name="DiscNumber">The number of the disc the track belongs to, if applicable.</param>
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
[DebuggerDisplay("Title: {Title}")]
public record TrackLiteResponse(
Guid Id,
string Title,
int TrackNumber,
int? DiscNumber
int? DiscNumber,
int DurationInSeconds
);
@@ -284,7 +284,15 @@ internal sealed class AlbumRepository : IAlbumRepository
{
Id = album.Id,
Title = album.Title,
TotalTracks = album.TotalTracks
TotalTracks = album.TotalTracks,
// The release year and the release types are exposed so that the clients can group and order the releases of an artist.
ReleaseYear = album.ReReleaseYear ?? album.OriginalReleaseYear,
ReleaseTypes = album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList(),
// The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album.
CoverPath = _luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
});
if (paginationData is null)
@@ -18,6 +18,8 @@ using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -29,6 +31,10 @@ namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
/// </summary>
internal sealed class ArtistRepository : IArtistRepository
{
private static readonly MethodInfo s_toLowerMethod = typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes)!;
private static readonly MethodInfo s_startsWithMethod = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
private static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!;
private readonly LuminaDbContext _luminaDbContext;
private readonly IAlbumRepository _albumRepository;
private readonly ITrackRepository _trackRepository;
@@ -488,7 +494,7 @@ internal sealed class ArtistRepository : IArtistRepository
if (filterSpecification is not null)
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
IQueryable<ArtistEntity> orderedArtistsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending);
IQueryable<ArtistEntity> orderedArtistsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
// If no pagination was requested, return all the artists of the library.
if (paginationData is null)
@@ -559,11 +565,16 @@ internal sealed class ArtistRepository : IArtistRepository
if (filterSpecification is not null)
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
IQueryable<ArtistLiteRow> liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending)
IQueryable<ArtistLiteRow> liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker)
.Select(artist => new ArtistLiteRow
{
Id = artist.Id,
Name = artist.Name
Name = artist.Name,
// The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist.
CoverPath = _luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
});
// If no pagination was requested, return all the artists of the library.
@@ -607,11 +618,22 @@ internal sealed class ArtistRepository : IArtistRepository
/// <returns>A filter specification that can be used to query artists matching the provided criteria.</returns>
private static FilterSpecification<ArtistEntity>? BuildFilterSpecification(LibraryFilterDto libraryFilter)
{
FilterSpecification<ArtistEntity>? filterSpecification = null;
// Include the search term filter, if provided.
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
return new ArtistSearchSpecification(libraryFilter.SearchTerm);
filterSpecification = new ArtistSearchSpecification(libraryFilter.SearchTerm);
return null;
// Include the alpha key filter, if provided.
if (libraryFilter.FilterAlphaKey is not null)
{
ArtistAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
filterSpecification = filterSpecification is null
? alphaFilterSpecification
: filterSpecification.And(alphaFilterSpecification);
}
return filterSpecification;
}
/// <summary>
@@ -620,8 +642,8 @@ internal sealed class ArtistRepository : IArtistRepository
/// <param name="artistsQuery">The query to sort.</param>
/// <param name="sortBy">The field to sort by (case-insensitive).</param>
/// <param name="sortOrder">The direction of the sorting.</param>
/// <returns>An ordered artists query.</returns>
private static IOrderedQueryable<ArtistEntity> ApplySorting(IQueryable<ArtistEntity> artistsQuery, string? sortBy, SortOrder sortOrder)
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a name is ignored when deriving the name sort key, or not.</param>
private static IOrderedQueryable<ArtistEntity> ApplySorting(IQueryable<ArtistEntity> artistsQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker)
{
return sortBy?.ToLowerInvariant() switch
{
@@ -638,11 +660,41 @@ internal sealed class ArtistRepository : IArtistRepository
? artistsQuery.OrderByDescending(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id),
_ => sortOrder == SortOrder.Descending
? artistsQuery.OrderByDescending(artist => artist.Name).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id),
? artistsQuery.OrderByDescending(BuildNameSortKey(shouldIgnoreThePrefixForAlphaPicker)).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(BuildNameSortKey(shouldIgnoreThePrefixForAlphaPicker)).ThenBy(artist => artist.Id),
};
}
/// <summary>
/// Builds the expression that derives the name sort key of an artist, matching the effective name used by the alpha filter:
/// the name lowercased, falling back to an empty string when the name is <see langword="null"/>, and optionally
/// stripped of a leading "the " prefix.
/// </summary>
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a name is ignored when deriving the name sort key, or not.</param>
/// <returns>An expression that evaluates to the name sort key of an artist.</returns>
private static Expression<Func<ArtistEntity, string>> BuildNameSortKey(bool shouldIgnoreThePrefixForAlphaPicker)
{
ParameterExpression artist = Expression.Parameter(typeof(ArtistEntity), "artist");
Expression nameProperty = Expression.Property(artist, nameof(ArtistEntity.Name));
// The raw name: the name, unless it is null, in which case an empty string is used.
Expression rawName = Expression.Coalesce(nameProperty, Expression.Constant(string.Empty));
MethodCallExpression lowerName = Expression.Call(rawName, s_toLowerMethod);
// When ignoring the "The " prefix, strip a leading "the " from the lowercased name.
Expression effectiveName = lowerName;
if (shouldIgnoreThePrefixForAlphaPicker)
{
MethodCallExpression startsWithThe = Expression.Call(lowerName, s_startsWithMethod, Expression.Constant("the "));
MethodCallExpression strippedName = Expression.Call(lowerName, s_substringMethod, Expression.Constant(4));
effectiveName = Expression.Condition(startsWithThe, strippedName, lowerName);
}
return Expression.Lambda<Func<ArtistEntity, string>>(effectiveName, artist);
}
/// <summary>
/// Gets the artist of the library identified by <paramref name="libraryId"/> that has the provided <paramref name="name"/>.
/// </summary>
@@ -793,4 +845,19 @@ internal sealed class ArtistRepository : IArtistRepository
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
/// <summary>
/// Deletes all the artists of the media library identified by <paramref name="libraryId"/>, together with their albums and tracks and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are deleted.</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>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
// The albums, tracks and the related data of the artists are removed by the database, through the cascading foreign keys.
await _luminaDbContext.Artists
.Where(artist => artist.LibraryId == libraryId)
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
}
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Specifications;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq.Expressions;
using System.Reflection;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
/// <summary>
/// Represents a filter specification for filtering artists by the alpha key of their name, for the alpha picker.
/// The alpha key is the first character of the name, lowercased, and optionally computed after ignoring a leading "The " prefix.
/// </summary>
internal sealed class ArtistAlphaFilterSpecification : FilterSpecification<ArtistEntity>
{
private static readonly MethodInfo s_toLowerMethod = typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes)!;
private static readonly MethodInfo s_startsWithMethod = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
private static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!;
private static readonly MethodInfo s_globMethod = typeof(SqliteDbFunctionsExtensions)
.GetMethod(nameof(SqliteDbFunctionsExtensions.Glob), [typeof(DbFunctions), typeof(string), typeof(string)])!;
private readonly string? _filterAlphaKey;
private readonly bool _shouldIgnoreThePrefixForAlphaPicker;
/// <summary>
/// Initializes a new instance of the <see cref="ArtistAlphaFilterSpecification"/> class.
/// </summary>
/// <param name="filterAlphaKey">The alpha key to filter by. A single ASCII letter, <see cref="LibraryItemAlphaKeys.NUMBER"/>, or <see cref="LibraryItemAlphaKeys.SYMBOL"/>.</param>
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not.</param>
public ArtistAlphaFilterSpecification(string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker)
{
_filterAlphaKey = filterAlphaKey;
_shouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
}
/// <summary>
/// Creates a LINQ expression that represents the predicate defined by the current specification.
/// </summary>
/// <returns>An expression tree that can be used to evaluate whether an <see cref="ArtistEntity"/> satisfies the specification criteria.</returns>
public override Expression<Func<ArtistEntity, bool>> ToExpression()
{
// When no alpha key was requested, every artist matches.
if (_filterAlphaKey is null)
return artist => true;
ParameterExpression artist = Expression.Parameter(typeof(ArtistEntity), "artist");
Expression effectiveName = BuildEffectiveName(artist);
if (_filterAlphaKey == LibraryItemAlphaKeys.NUMBER)
return BuildGlobPredicate(artist, effectiveName, "[0-9]*");
if (_filterAlphaKey == LibraryItemAlphaKeys.SYMBOL)
return BuildSymbolPredicate(artist, effectiveName);
// The alpha key is a single ASCII letter.
string globPattern = char.ToLowerInvariant(_filterAlphaKey[0]) + "*";
return BuildGlobPredicate(artist, effectiveName, globPattern);
}
/// <summary>
/// Builds the expression representing the lowercased name used to derive the alpha key, falling back to an empty string
/// when the name is <see langword="null"/> or empty, and optionally stripped of a leading "the " prefix.
/// </summary>
/// <param name="artist">The parameter representing the artist entity.</param>
/// <returns>The expression of the effective name.</returns>
private Expression BuildEffectiveName(ParameterExpression artist)
{
Expression nameProperty = Expression.Property(artist, nameof(ArtistEntity.Name));
// The raw name is the name, unless it is null, in which case an empty string is used.
Expression rawName = Expression.Coalesce(nameProperty, Expression.Constant(string.Empty));
MethodCallExpression lowerName = Expression.Call(rawName, s_toLowerMethod);
// When ignoring the "The " prefix, a leading "the " is stripped from the lowercased name.
Expression effectiveName = lowerName;
if (_shouldIgnoreThePrefixForAlphaPicker)
{
MethodCallExpression startsWithThe = Expression.Call(lowerName, s_startsWithMethod, Expression.Constant("the "));
MethodCallExpression strippedName = Expression.Call(lowerName, s_substringMethod, Expression.Constant(4));
effectiveName = Expression.Condition(startsWithThe, strippedName, lowerName);
}
return effectiveName;
}
/// <summary>
/// Builds a predicate that is satisfied when the effective name starts with a glob pattern.
/// </summary>
/// <param name="artist">The parameter representing the artist entity.</param>
/// <param name="effectiveName">The expression of the effective name.</param>
/// <param name="globPattern">The glob pattern the effective name must match.</param>
/// <returns>The built predicate.</returns>
private static Expression<Func<ArtistEntity, bool>> BuildGlobPredicate(ParameterExpression artist, Expression effectiveName, string globPattern)
{
MethodCallExpression glob = BuildGlobCall(effectiveName, globPattern);
return Expression.Lambda<Func<ArtistEntity, bool>>(glob, artist);
}
/// <summary>
/// Builds a predicate that is satisfied when the first character of the effective name is neither a letter nor a digit.
/// </summary>
/// <param name="artist">The parameter representing the artist entity.</param>
/// <param name="effectiveName">The expression of the effective name.</param>
/// <returns>The built predicate.</returns>
private static Expression<Func<ArtistEntity, bool>> BuildSymbolPredicate(ParameterExpression artist, Expression effectiveName)
{
Expression notLetter = Expression.Not(BuildGlobCall(effectiveName, "[a-z]*"));
Expression notDigit = Expression.Not(BuildGlobCall(effectiveName, "[0-9]*"));
return Expression.Lambda<Func<ArtistEntity, bool>>(Expression.AndAlso(notLetter, notDigit), artist);
}
/// <summary>
/// Builds the call to <see cref="SqliteDbFunctionsExtensions.Glob"/> for the effective name and the provided glob pattern.
/// </summary>
/// <param name="effectiveName">The expression of the effective name.</param>
/// <param name="globPattern">The glob pattern the effective name must match.</param>
/// <returns>The built method call.</returns>
private static MethodCallExpression BuildGlobCall(Expression effectiveName, string globPattern)
{
Expression functions = Expression.Property(null, typeof(EF), nameof(EF.Functions));
return Expression.Call(s_globMethod, functions, effectiveName, Expression.Constant(globPattern));
}
}
@@ -242,7 +242,7 @@ internal sealed class TrackRepository : ITrackRepository
.Include(track => track.Contributors)
.AsSplitQuery()
.Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber)
.OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1
.ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -262,7 +262,7 @@ internal sealed class TrackRepository : ITrackRepository
IQueryable<TrackLiteRow> liteRowsQuery = _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber)
.OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1
.ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id)
.Select(track => new TrackLiteRow
@@ -270,7 +270,8 @@ internal sealed class TrackRepository : ITrackRepository
Id = track.Id,
Title = track.Title,
TrackNumber = track.TrackNumber,
DiscNumber = track.DiscNumber
DiscNumber = track.DiscNumber,
DurationInSeconds = track.DurationInSeconds
});
if (paginationData is null)
@@ -373,6 +373,8 @@ public class AddAlbumEndpointSummary : Summary<AddAlbumEndpoint, AddAlbumRequest
ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album.");
ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album.");
ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album.");
ResponseParam<AlbumResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumResponse>(r => r.Artwork, "The stored artwork of the album, in display order, if applicable.");
Response(201, "The newly created album is returned.",
example: new AlbumResponse(
@@ -177,6 +177,8 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album.");
ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album.");
ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album.");
ResponseParam<AlbumResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumResponse>(r => r.Artwork, "The stored artwork of the album, in display order, if applicable.");
Response(200, "The updated album is returned.",
example: new AlbumResponse(
@@ -455,6 +455,8 @@ public class AddArtistEndpointSummary : Summary<AddArtistEndpoint, AddArtistRequ
ResponseParam<ArtistResponse>(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Ratings, "The list of ratings for the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks, "The list of tracks of the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].CoverPath, "The path of the image representing the album, if available.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Artwork, "The stored artwork of the album, in display order, if applicable.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Id, "The Id of the track.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to.");
@@ -503,6 +505,7 @@ public class AddArtistEndpointSummary : Summary<AddArtistEndpoint, AddArtistRequ
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(201, "The new artist is returned.",
example: new ArtistResponse(
@@ -39,6 +39,7 @@ public class GetArtistEndpointSummary : Summary<GetArtistEndpoint, EmptyRequest>
ResponseParam<ArtistResponse>(r => r.Albums, "The list of albums of the artist, each with its own list of tracks.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(200, "The requested artist is returned.",
example: new ArtistResponse(
@@ -65,6 +65,8 @@ public class GetArtistAlbumsEndpointSummary : Summary<GetArtistAlbumsEndpoint, E
ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album.");
ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album.");
ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album.");
ResponseParam<AlbumResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumResponse>(r => r.Artwork, "The stored artwork of the album, in display order, if applicable.");
Response(200, "The list of albums of the artist is returned.",
example: new AlbumResponse[]
@@ -36,6 +36,9 @@ public class GetArtistAlbumsLiteEndpointSummary : Summary<GetArtistAlbumsLiteEnd
ResponseParam<AlbumLiteResponse>(r => r.Id, "The Id of the album.");
ResponseParam<AlbumLiteResponse>(r => r.Title, "The title of the album.");
ResponseParam<AlbumLiteResponse>(r => r.TotalTracks, "The number of tracks of the release.");
ResponseParam<AlbumLiteResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumLiteResponse>(r => r.ReleaseYear, "The release year of the album (the re-release year, if available, or the original release year), if known.");
ResponseParam<AlbumLiteResponse>(r => r.ReleaseTypes, "The set of types of the release.");
Response(200, "The paginated list of the lightweight read models of the albums of the artist is returned.",
example: new PaginatedResponse<AlbumLiteResponse>
@@ -51,6 +51,7 @@ public class GetArtistsEndpointSummary : Summary<GetArtistsEndpoint, GetArtistsR
ResponseParam<ArtistResponse>(r => r.Albums, "The list of albums of the artist, each with its own list of tracks.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(200, "The paginated list of the artists of the media library is returned.",
example: new PaginatedResponse<ArtistResponse>
@@ -39,12 +39,13 @@ public class GetArtistsLiteEndpointSummary : Summary<GetArtistsLiteEndpoint, Get
RequestParam(r => r.PerPage, "The maximum number of artists to retrieve per page. Optional.");
RequestParam(r => r.SearchTerm, "The search term used to filter the artists by name. Optional.");
RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the artists by the first character of their name, for the alpha picker. Optional.");
RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a name is ignored when computing the alpha key, or not.");
RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a name is ignored when computing the alpha key, or not. Optional.");
RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional.");
RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional.");
ResponseParam<ArtistLiteResponse>(r => r.Id, "The Id of the artist.");
ResponseParam<ArtistLiteResponse>(r => r.Name, "The name of the artist.");
ResponseParam<ArtistLiteResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(200, "The paginated list of the lightweight read models of the artists is returned.",
example: new PaginatedResponse<ArtistLiteResponse>
@@ -454,6 +454,8 @@ public class UpdateArtistEndpointSummary : Summary<UpdateArtistEndpoint, UpdateA
ResponseParam<ArtistResponse>(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Ratings, "The list of ratings for the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks, "The list of tracks of the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].CoverPath, "The path of the image representing the album, if available.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Artwork, "The stored artwork of the album, in display order, if applicable.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Id, "The Id of the track.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to.");
@@ -502,6 +504,7 @@ public class UpdateArtistEndpointSummary : Summary<UpdateArtistEndpoint, UpdateA
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();