Adds playlist management and playback

This commit is contained in:
BinaryAlley committed 2026-10-21 16:30:58 +03:00
1 parent 009a0c8156
commit 9889c86c76
296 files changed
+18830 -367

No files matched your search

@@ -0,0 +1,92 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
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="PlaylistEntity"/> entity.
/// </summary>
public class PlaylistConfiguration : IEntityTypeConfiguration<PlaylistEntity>
{
/// <summary>
/// Configures the <see cref="PlaylistEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<PlaylistEntity> builder)
{
builder.ToTable("Playlists");
builder.HasKey(playlist => playlist.Id);
builder.Property(playlist => playlist.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 playlist belongs to the user that created it, and it is removed with that user.
builder.HasOne<UserEntity>()
.WithMany()
.HasForeignKey(playlist => playlist.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
builder.Property(playlist => playlist.UserId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(playlist => playlist.Name)
.IsRequired()
.HasMaxLength(255)
.HasColumnOrder(2);
builder.Property(playlist => playlist.Description)
.HasMaxLength(2000)
.HasColumnOrder(3);
builder.Property(playlist => playlist.Type)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(4);
// Audit.
builder.Property(playlist => playlist.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(5);
builder.Property(playlist => playlist.CreatedBy)
.IsRequired()
.HasColumnOrder(6);
builder.Property(playlist => playlist.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(7);
builder.Property(playlist => playlist.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(8);
// The entry count is maintained by the set-based entry operations, so a window read never counts the entries of the whole playlist.
builder.Property(playlist => playlist.EntryCount)
.IsRequired()
.HasDefaultValue(0)
.HasColumnOrder(10);
// The concurrency token is incremented by every details edit and by every set-based entry operation, so a concurrent writer is
// detected instead of silently overwriting the ordering work of another request.
builder.Property(playlist => playlist.Version)
.IsConcurrencyToken()
.HasDefaultValue(0L)
.HasColumnOrder(9);
// The entries of the playlist are owned by the playlist: they are removed with it, and they are never referenced from elsewhere.
builder.HasMany(playlist => playlist.Entries)
.WithOne()
.HasForeignKey(entry => entry.PlaylistId)
.OnDelete(DeleteBehavior.Cascade);
// Enables the list of the playlists of a user in the order of their most recent activity.
builder.HasIndex(playlist => new { playlist.UserId, playlist.UpdatedOnUtc });
}
}
@@ -0,0 +1,70 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="PlaylistEntryEntity"/> entity.
/// </summary>
public class PlaylistEntryConfiguration : IEntityTypeConfiguration<PlaylistEntryEntity>
{
/// <summary>
/// Configures the <see cref="PlaylistEntryEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<PlaylistEntryEntity> builder)
{
builder.ToTable("PlaylistEntries");
builder.HasKey(entry => entry.Id);
builder.Property(entry => entry.Id)
.ValueGeneratedNever()
.HasColumnOrder(0);
builder.Property(entry => entry.PlaylistId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(entry => entry.MediaItemId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(entry => entry.MediaItemType)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(3);
builder.Property(entry => entry.Position)
.IsRequired()
.HasColumnOrder(4);
// Audit.
builder.Property(entry => entry.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(5);
builder.Property(entry => entry.CreatedBy)
.IsRequired()
.HasColumnOrder(6);
builder.Property(entry => entry.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(7);
builder.Property(entry => entry.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(8);
// The referenced media item is kept by Id only, without a foreign key, so a playlist entry survives the deletion of the item it
// references and its owner can still see and remove the dangling entry.
// The unique index makes the storage medium the owner of the ordering invariant: a duplicate position is rejected even if an operation bypasses the repository.
builder.HasIndex(entry => new { entry.PlaylistId, entry.Position })
.IsUnique();
// Enables finding the playlists that reference a media item, for example when a track is deleted.
builder.HasIndex(entry => entry.MediaItemId);
}
}
@@ -10,20 +10,21 @@ namespace Lumina.DataAccess.Common.Dapper;
/// Maps <see cref="Guid"/> values to and from the TEXT representation used by the SQLite provider.
/// </summary>
/// <remarks>
/// The SQLite provider stores <see cref="Guid"/> columns as TEXT, and Dapper falls back to Convert.ChangeType when materializing such
/// columns into <see cref="Guid"/> properties. <see cref="Guid"/> has no string <see cref="TypeConverter"/>, so that conversion throws
/// an <see cref="InvalidCastException"/>; this handler performs the conversion explicitly instead.
/// The SQLite provider stores <see cref="Guid"/> columns as upper case TEXT. Dapper falls back to Convert.ChangeType when materializing
/// such columns into <see cref="Guid"/> properties. <see cref="Guid"/> has no string <see cref="TypeConverter"/>, so that conversion
/// throws an <see cref="InvalidCastException"/>; this handler performs the conversion explicitly instead, and writes the same upper case
/// representation so raw key comparisons and foreign keys match the rows created by Entity Framework.
/// </remarks>
internal sealed class SqliteGuidTypeHandler : SqlMapper.TypeHandler<Guid>
{
/// <summary>
/// Sets the parameter value to the TEXT representation of the <see cref="Guid"/> value, keeping writes consistent with reads.
/// Sets the parameter value to the upper case TEXT representation the SQLite provider uses for <see cref="Guid"/> columns.
/// </summary>
/// <param name="parameter">The database parameter to set.</param>
/// <param name="value">The <see cref="Guid"/> value to store.</param>
public override void SetValue(IDbDataParameter parameter, Guid value)
{
parameter.Value = value.ToString();
parameter.Value = value.ToString().ToUpperInvariant();
}
/// <summary>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,93 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsPlaylists : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Playlists",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
Type = table.Column<string>(type: "TEXT", maxLength: 20, 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),
Version = table.Column<long>(type: "INTEGER", nullable: false, defaultValue: 0L),
EntryCount = table.Column<int>(type: "INTEGER", nullable: false, defaultValue: 0)
},
constraints: table =>
{
table.PrimaryKey("PK_Playlists", x => x.Id);
table.ForeignKey(
name: "FK_Playlists_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "PlaylistEntries",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
PlaylistId = table.Column<Guid>(type: "TEXT", nullable: false),
MediaItemId = table.Column<Guid>(type: "TEXT", nullable: false),
MediaItemType = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
Position = table.Column<long>(type: "INTEGER", 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_PlaylistEntries", x => x.Id);
table.ForeignKey(
name: "FK_PlaylistEntries_Playlists_PlaylistId",
column: x => x.PlaylistId,
principalTable: "Playlists",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_PlaylistEntries_MediaItemId",
table: "PlaylistEntries",
column: "MediaItemId");
migrationBuilder.CreateIndex(
name: "IX_PlaylistEntries_PlaylistId_Position",
table: "PlaylistEntries",
columns: new[] { "PlaylistId", "Position" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Playlists_UserId_UpdatedOnUtc",
table: "Playlists",
columns: new[] { "UserId", "UpdatedOnUtc" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PlaylistEntries");
migrationBuilder.DropTable(
name: "Playlists");
}
}
}
@@ -1904,6 +1904,119 @@ namespace Lumina.DataAccess.Common.Migrations
b.ToTable("Books", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<int>("EntryCount")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(0)
.HasColumnOrder(10);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<Guid>("UserId")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<long>("Version")
.IsConcurrencyToken()
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(0L)
.HasColumnOrder(9);
b.HasKey("Id");
b.HasIndex("UserId", "UpdatedOnUtc");
b.ToTable("Playlists", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<Guid>("MediaItemId")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("MediaItemType")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<Guid>("PlaylistId")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<long>("Position")
.HasColumnType("INTEGER")
.HasColumnOrder(4);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.HasKey("Id");
b.HasIndex("MediaItemId");
b.HasIndex("PlaylistId", "Position")
.IsUnique();
b.ToTable("PlaylistEntries", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b =>
{
b.Property<Guid>("Id")
@@ -3429,6 +3542,24 @@ namespace Lumina.DataAccess.Common.Migrations
b.Navigation("Ratings");
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", 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.Playlists.PlaylistEntryEntity", b =>
{
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null)
.WithMany("Entries")
.HasForeignKey("PlaylistId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b =>
{
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null)
@@ -3518,6 +3649,11 @@ namespace Lumina.DataAccess.Common.Migrations
b.Navigation("Contributors");
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b =>
{
b.Navigation("Entries");
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
{
b.Navigation("Libraries");
@@ -16,8 +16,9 @@ internal static class CollectionReconciler
/// </summary>
/// <remarks>
/// Existing items that are absent from the desired set are removed, desired items that are absent are added, and matched items are left untouched, unless
/// <paramref name="shouldReplace"/> reports that their non-key values changed, in which case only that item is replaced. Because the tracked instances are
/// never rebuilt as a whole, the rows that did not change keep their identity and their audit columns.
/// <paramref name="shouldReplace"/> reports that their non-key values changed, in which case only that item is replaced, or <paramref name="applyMatched"/> is
/// provided, in which case the matched tracked item is updated in place. Because the tracked instances are never rebuilt as a whole, the rows that did not change
/// keep their identity and their audit columns.
/// </remarks>
/// <typeparam name="TExisting">The type of the tracked items.</typeparam>
/// <typeparam name="TIncoming">The type of the desired items.</typeparam>
@@ -28,13 +29,15 @@ internal static class CollectionReconciler
/// <param name="incomingKeySelector">Selects the matching key of a desired item.</param>
/// <param name="shouldReplace">Determines whether a matched tracked item must be replaced, because a non-key value changed.</param>
/// <param name="createNew">Creates the entity used for a desired item that is not matched by any tracked item.</param>
/// <param name="applyMatched">Applies the incoming non-key values onto a matched tracked item, when the caller updates matched items in place instead of replacing them.</param>
public static void Reconcile<TExisting, TIncoming, TKey>(
ICollection<TExisting> existingItems,
IEnumerable<TIncoming> incomingItems,
Func<TExisting, TKey> existingKeySelector,
Func<TIncoming, TKey> incomingKeySelector,
Func<TExisting, TIncoming, bool> shouldReplace,
Func<TIncoming, TExisting> createNew)
Func<TIncoming, TExisting> createNew,
Action<TExisting, TIncoming>? applyMatched = null)
where TExisting : class
where TKey : notnull
{
@@ -65,6 +68,10 @@ internal static class CollectionReconciler
existingItems.Add(replacementItem);
existingByKey[incomingKey] = replacementItem;
}
else if (applyMatched is not null)
// The caller updates the matched instance in place. This keeps the tracked instance and its key, which is the only
// safe option when the key is user-assigned and the tracked instance is still in the change tracker.
applyMatched(matchedItem, incomingItem);
}
else
{
@@ -47,7 +47,13 @@ internal static class EditableValuesCopier
{
if (excludedProperties.Contains(property.Name))
continue;
trackedEntry.Property(property.Name).CurrentValue = incomingEntry.Property(property.Name).CurrentValue;
PropertyEntry trackedProperty = trackedEntry.Property(property.Name);
object? incomingValue = incomingEntry.Property(property.Name).CurrentValue;
// Only an actual change is assigned and marked modified. Assigning every value unconditionally, or relying on change detection that has not run yet, would make the caller unable to tell a no-op save from a real edit.
if (Equals(trackedProperty.CurrentValue, incomingValue))
continue;
trackedProperty.CurrentValue = incomingValue;
trackedProperty.IsModified = true;
}
}
}
@@ -226,16 +226,14 @@ internal sealed class BookRepository : IBookRepository
// Apply sorting based on the specified sortBy and sortOrder parameters.
booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
IQueryable<BookLiteRow> liteRowsQuery = booksQuery.Select(book => new BookLiteRow
{
Id = book.Id,
Title = book.Title,
ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear,
CoverPath = book.Artwork
IQueryable<BookLiteRow> liteRowsQuery = booksQuery.Select(book => new BookLiteRow(
book.Id,
book.Title,
book.ReReleaseYear ?? book.OriginalReleaseYear,
book.Artwork
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
});
.FirstOrDefault()));
// If no pagination was requested, return all the books of the library.
if (paginationData is null)
@@ -102,7 +102,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
DateTime nowUtc = DateTime.UtcNow;
object parameters = new { libraryId, scanId, userId, nowUtc };
// the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as lowercase hex (hex(randomblob(16))), which the storage layer parses as a Guid;
// the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as upper case hex (hex(randomblob(16))), which the storage layer parses as a Guid;
// generating the Ids in code would defeat the purpose of these single statement bulk inserts
// add an audit entry for every media library scan snapshot item that is no longer present in the current scan, meaning it was deleted from the storage medium
@@ -275,25 +275,23 @@ internal sealed class AlbumRepository : IAlbumRepository
public async Task<Result<PaginatedResultDto<AlbumLiteRow>>> GetAlbumsLiteByArtistIdAsync(Guid artistId, PaginationDataDto? paginationData, CancellationToken cancellationToken)
{
// The lightweight read models are always retrieved without tracking, because they are never modified by the caller.
// The release year and the release types are exposed so that the clients can group and order the releases of an artist.
// 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.
IQueryable<AlbumLiteRow> liteRowsQuery = _luminaDbContext.Albums
.AsNoTracking()
.Where(album => album.ArtistId == artistId)
.OrderBy(album => album.Title)
.ThenBy(album => album.Id)
.Select(album => new AlbumLiteRow
{
Id = album.Id,
Title = album.Title,
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
.Select(album => new AlbumLiteRow(
album.Id,
album.Title,
album.TotalTracks,
_luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
});
.FirstOrDefault(),
album.ReReleaseYear ?? album.OriginalReleaseYear,
album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList()));
if (paginationData is null)
{
@@ -565,17 +565,15 @@ internal sealed class ArtistRepository : IArtistRepository
if (filterSpecification is not null)
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
// 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.
IQueryable<ArtistLiteRow> liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker)
.Select(artist => new ArtistLiteRow
{
Id = artist.Id,
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
.Select(artist => new ArtistLiteRow(
artist.Id,
artist.Name,
_luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
});
.FirstOrDefault()));
// If no pagination was requested, return all the artists of the library.
if (paginationData is null)
@@ -266,14 +266,12 @@ internal sealed class TrackRepository : ITrackRepository
.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
{
Id = track.Id,
Title = track.Title,
TrackNumber = track.TrackNumber,
DiscNumber = track.DiscNumber,
DurationInSeconds = track.DurationInSeconds
});
.Select(track => new TrackLiteRow(
track.Id,
track.Title,
track.TrackNumber,
track.DiscNumber,
track.DurationInSeconds));
if (paginationData is null)
{
@@ -333,24 +331,21 @@ internal sealed class TrackRepository : ITrackRepository
if (excludedIds.Length > 0)
query = query.Where(track => !excludedIds.Contains(track.Id));
// SQLite randomizes the rows before the limit, so the result is a uniform sample of every matching track.
// SQLite randomizes the rows before the limit, so the result is a uniform sample of every matching track. The cover is the cover artwork stored for the album, exactly like the album cards expose it.
return await query
.OrderBy(_ => EF.Functions.Random())
.Take(count)
.Select(track => new ShuffleTrackRowDto
{
TrackId = track.Id,
Title = track.Title,
DurationInSeconds = track.DurationInSeconds,
AlbumId = track.AlbumId,
AlbumTitle = track.Album!.Title,
ArtistId = track.Album!.ArtistId,
// The cover is the cover artwork stored for the album, exactly like the album cards expose it.
CoverPath = _luminaDbContext.MusicArtwork
.Select(track => new ShuffleTrackRowDto(
track.Id,
track.Title,
track.DurationInSeconds,
track.AlbumId,
track.Album!.Title,
track.Album!.ArtistId,
_luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == track.AlbumId && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
})
.FirstOrDefault()))
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -529,4 +524,54 @@ internal sealed class TrackRepository : ITrackRepository
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
/// <summary>
/// Gets the number of tracks in <paramref name="trackIds"/> that exist, together with the distinct Ids of the libraries that contain them.
/// </summary>
/// <param name="trackIds">The Ids of the tracks whose access information is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the access summary of the existing tracks, or an error.</returns>
public async Task<Result<TrackAccessSummaryDto>> GetAccessInfoByIdsAsync(IReadOnlyCollection<Guid> trackIds, CancellationToken cancellationToken)
{
if (trackIds.Count == 0)
return Result.From(new TrackAccessSummaryDto(0, []));
// The chunk is deliberately large: it stays below the SQLite parameter limit while keeping a 100k queue to a handful of sequential round trips.
// The projection groups by library, so the storage medium returns one row per library instead of one row per requested track.
const int LOOKUP_CHUNK_SIZE = 20_000;
int trackCount = 0;
HashSet<Guid> libraryIds = [];
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
{
List<TrackLibraryCount> chunkCounts = await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => chunk.Contains(track.Id))
.GroupBy(track => track.LibraryId)
.Select(group => new TrackLibraryCount
{
LibraryId = group.Key,
TrackCount = group.Count()
})
.ToListAsync(cancellationToken).ConfigureAwait(false);
trackCount += chunkCounts.Sum(count => count.TrackCount);
libraryIds.UnionWith(chunkCounts.Select(count => count.LibraryId));
}
return Result.From(new TrackAccessSummaryDto(trackCount, [.. libraryIds]));
}
/// <summary>
/// The number of requested tracks that exist in one library.
/// </summary>
private sealed class TrackLibraryCount
{
/// <summary>
/// Gets or sets the Id of the library.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the number of requested tracks in the library.
/// </summary>
public int TrackCount { get; set; }
}
}
File diff suppressed because it is too large. Load diff
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.Themes;
@@ -50,6 +51,8 @@ public class LuminaDbContext : DbContext
public virtual DbSet<ScheduledJobExecutionEntity> ScheduledJobExecutions { get; set; } = null!;
public virtual DbSet<SchedulerDisplayPreferencesEntity> SchedulerDisplayPreferences { get; set; } = null!;
public virtual DbSet<MusicPlayRecordEntity> MusicPlayRecords { get; set; } = null!;
public virtual DbSet<PlaylistEntity> Playlists { get; set; } = null!;
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Playlists;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
@@ -15,6 +16,7 @@ using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
using Lumina.DataAccess.Core.Repositories.Playlists;
using Lumina.DataAccess.Core.Repositories.Plugins;
using Lumina.DataAccess.Core.Repositories.Scheduling;
using Lumina.DataAccess.Core.Repositories.Themes;
@@ -65,6 +67,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private IUserRepository? _userRepository;
private IUserSettingsRepository? _userSettingsRepository;
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
private IPlaylistRepository? _playlistRepository;
/// <summary>
/// Gets the permission repository.
@@ -387,6 +390,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
/// <summary>
/// Gets the playlist repository.
/// </summary>
public IPlaylistRepository PlaylistRepository
{
get
{
_playlistRepository ??= new PlaylistRepository(_luminaDbContext);
return _playlistRepository;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
/// </summary>