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

@@ -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)