Adds deletion and restore for music library items.

This commit is contained in:
BinaryAlley committed 2026-11-15 18:53:10 +02:00
1 parent 98515dc5e8
commit f9ad8b2fc5
224 files changed
+22384 -1360

No files matched your search

@@ -130,6 +130,12 @@ public class AlbumConfiguration : IEntityTypeConfiguration<AlbumEntity>
builder.Property(album => album.MetadataProvider)
.HasMaxLength(100)
.HasColumnOrder(38);
builder.Property(album => album.IsDeleted)
.IsRequired()
.HasDefaultValue(false)
.HasColumnOrder(39);
builder.Property(album => album.DeletedOnUtc)
.HasColumnOrder(40);
builder.HasOne(album => album.Artist)
.WithMany(artist => artist.Albums)
@@ -232,5 +238,9 @@ public class AlbumConfiguration : IEntityTypeConfiguration<AlbumEntity>
builder.HasIndex(album => new { album.ArtistId, album.Title });
builder.HasIndex(album => new { album.LibraryId, album.Title });
// The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the
// filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it.
builder.HasIndex(album => new { album.LibraryId, album.IsDeleted, album.DeletedOnUtc, album.Title, album.Id })
.HasFilter("\"IsDeleted\" = 1");
}
}
@@ -83,6 +83,12 @@ public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
builder.Property(artist => artist.MetadataProvider)
.HasMaxLength(100)
.HasColumnOrder(19);
builder.Property(artist => artist.IsDeleted)
.IsRequired()
.HasDefaultValue(false)
.HasColumnOrder(20);
builder.Property(artist => artist.DeletedOnUtc)
.HasColumnOrder(21);
// The areas are owned value objects that are never referenced on their own, so they are stored as JSON documents next to the artist.
builder.OwnsOne(artist => artist.Area, areaBuilder => areaBuilder.ToJson());
@@ -202,7 +208,14 @@ public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
.HasForeignKey(contributor => contributor.ArtistId)
.OnDelete(DeleteBehavior.Cascade);
// The same visible artist cannot appear twice in the same library, while a deleted artist does not block a new visible artist with the
// same name, so that a new file of an artist the user deleted can still materialize as a new, visible artist.
builder.HasIndex(artist => new { artist.LibraryId, artist.Name })
.IsUnique(); // the same artist cannot appear twice in the same library
.IsUnique()
.HasFilter("\"IsDeleted\" = 0");
// The deleted items page filters by library and deletion state, and orders by the stored deletion time, the name and the Id, so the
// filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it.
builder.HasIndex(artist => new { artist.LibraryId, artist.IsDeleted, artist.DeletedOnUtc, artist.Name, artist.Id })
.HasFilter("\"IsDeleted\" = 1");
}
}
@@ -155,6 +155,12 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
builder.Property(track => track.Container)
.HasMaxLength(50)
.HasColumnOrder(49);
builder.Property(track => track.IsDeleted)
.IsRequired()
.HasDefaultValue(false)
.HasColumnOrder(50);
builder.Property(track => track.DeletedOnUtc)
.HasColumnOrder(51);
builder.HasOne(track => track.Album)
.WithMany(album => album.Tracks)
@@ -291,5 +297,9 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
builder.HasIndex(track => new { track.AlbumId, track.TrackNumber });
builder.HasIndex(track => new { track.LibraryId, track.Path })
.IsUnique(); // the same physical track file cannot appear twice in the same library
// The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the
// filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it.
builder.HasIndex(track => new { track.LibraryId, track.IsDeleted, track.DeletedOnUtc, track.Title, track.Id })
.HasFilter("\"IsDeleted\" = 1");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,139 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsMusicDeletionState : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Artists_LibraryId_Name",
table: "Artists");
migrationBuilder.AddColumn<DateTime>(
name: "DeletedOnUtc",
table: "Tracks",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 51);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "Tracks",
type: "INTEGER",
nullable: false,
defaultValue: false)
.Annotation("Relational:ColumnOrder", 50);
migrationBuilder.AddColumn<DateTime>(
name: "DeletedOnUtc",
table: "Artists",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 21);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "Artists",
type: "INTEGER",
nullable: false,
defaultValue: false)
.Annotation("Relational:ColumnOrder", 20);
migrationBuilder.AddColumn<DateTime>(
name: "DeletedOnUtc",
table: "Albums",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 40);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "Albums",
type: "INTEGER",
nullable: false,
defaultValue: false)
.Annotation("Relational:ColumnOrder", 39);
migrationBuilder.CreateIndex(
name: "IX_Tracks_LibraryId_IsDeleted_DeletedOnUtc_Title_Id",
table: "Tracks",
columns: new[] { "LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id" },
filter: "\"IsDeleted\" = 1");
migrationBuilder.CreateIndex(
name: "IX_Artists_LibraryId_IsDeleted_DeletedOnUtc_Name_Id",
table: "Artists",
columns: new[] { "LibraryId", "IsDeleted", "DeletedOnUtc", "Name", "Id" },
filter: "\"IsDeleted\" = 1");
migrationBuilder.CreateIndex(
name: "IX_Artists_LibraryId_Name",
table: "Artists",
columns: new[] { "LibraryId", "Name" },
unique: true,
filter: "\"IsDeleted\" = 0");
migrationBuilder.CreateIndex(
name: "IX_Albums_LibraryId_IsDeleted_DeletedOnUtc_Title_Id",
table: "Albums",
columns: new[] { "LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id" },
filter: "\"IsDeleted\" = 1");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Tracks_LibraryId_IsDeleted_DeletedOnUtc_Title_Id",
table: "Tracks");
migrationBuilder.DropIndex(
name: "IX_Artists_LibraryId_IsDeleted_DeletedOnUtc_Name_Id",
table: "Artists");
migrationBuilder.DropIndex(
name: "IX_Artists_LibraryId_Name",
table: "Artists");
migrationBuilder.DropIndex(
name: "IX_Albums_LibraryId_IsDeleted_DeletedOnUtc_Title_Id",
table: "Albums");
migrationBuilder.DropColumn(
name: "DeletedOnUtc",
table: "Tracks");
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "Tracks");
migrationBuilder.DropColumn(
name: "DeletedOnUtc",
table: "Artists");
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "Artists");
migrationBuilder.DropColumn(
name: "DeletedOnUtc",
table: "Albums");
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "Albums");
migrationBuilder.CreateIndex(
name: "IX_Artists_LibraryId_Name",
table: "Artists",
columns: new[] { "LibraryId", "Name" },
unique: true);
}
}
}
@@ -652,6 +652,10 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(32);
b.Property<DateTime?>("DeletedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(40);
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("TEXT")
@@ -662,6 +666,12 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(false)
.HasColumnOrder(39);
b.Property<string>("Label")
.HasMaxLength(255)
.HasColumnType("TEXT")
@@ -807,6 +817,9 @@ namespace Lumina.DataAccess.Common.Migrations
b.HasIndex("LibraryId", "Title");
b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id")
.HasFilter("\"IsDeleted\" = 1");
b.ToTable("Albums", (string)null);
});
@@ -875,6 +888,10 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(13);
b.Property<DateTime?>("DeletedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(21);
b.Property<string>("Disambiguation")
.HasMaxLength(255)
.HasColumnType("TEXT")
@@ -885,6 +902,12 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(false)
.HasColumnOrder(20);
b.Property<bool>("IsEnded")
.HasColumnType("INTEGER")
.HasColumnOrder(10);
@@ -954,7 +977,11 @@ namespace Lumina.DataAccess.Common.Migrations
b.HasKey("Id");
b.HasIndex("LibraryId", "Name")
.IsUnique();
.IsUnique()
.HasFilter("\"IsDeleted\" = 0");
b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Name", "Id")
.HasFilter("\"IsDeleted\" = 1");
b.ToTable("Artists", (string)null);
});
@@ -1279,6 +1306,10 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(37);
b.Property<DateTime?>("DeletedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(51);
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("TEXT")
@@ -1297,6 +1328,12 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("INTEGER")
.HasColumnOrder(20);
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(false)
.HasColumnOrder(50);
b.Property<bool>("IsVideo")
.HasColumnType("INTEGER")
.HasColumnOrder(31);
@@ -1459,6 +1496,9 @@ namespace Lumina.DataAccess.Common.Migrations
b.HasIndex("LibraryId", "Path")
.IsUnique();
b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id")
.HasFilter("\"IsDeleted\" = 1");
b.ToTable("Tracks", (string)null);
});
@@ -113,17 +113,17 @@ internal sealed class FavoriteRepository : IFavoriteRepository
{
FavoriteMediaKind.MusicArtist => await _luminaDbContext.Artists
.AsNoTracking()
.Where(artist => artist.Id == mediaItemId)
.Where(artist => artist.Id == mediaItemId && !artist.IsDeleted)
.Select(artist => (Guid?)artist.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
FavoriteMediaKind.MusicAlbum => await _luminaDbContext.Albums
.AsNoTracking()
.Where(album => album.Id == mediaItemId)
.Where(album => album.Id == mediaItemId && !album.IsDeleted && !album.Artist!.IsDeleted)
.Select(album => (Guid?)album.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
FavoriteMediaKind.MusicTrack => await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.Id == mediaItemId)
.Where(track => track.Id == mediaItemId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted)
.Select(track => (Guid?)track.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
FavoriteMediaKind.Book => await _luminaDbContext.Books
@@ -293,7 +293,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository
// 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))
.Where(artist => requestedIds.Contains(artist.Id) && !artist.IsDeleted)
.Select(artist => new DisplayRow(
artist.Id,
artist.LibraryId,
@@ -311,7 +311,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository
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)
where requestedIds.Contains(album.Id) && !album.IsDeleted && !artist.IsDeleted
select new DisplayRow(
album.Id,
album.LibraryId,
@@ -331,7 +331,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository
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)
where requestedIds.Contains(track.Id) && !track.IsDeleted && !album.IsDeleted && !artist.IsDeleted
select new DisplayRow(
track.Id,
track.LibraryId,
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
@@ -28,16 +29,19 @@ internal sealed class AlbumRepository : IAlbumRepository
{
private readonly LuminaDbContext _luminaDbContext;
private readonly ITrackRepository _trackRepository;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="AlbumRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
/// <param name="trackRepository">Injected repository for tracks.</param>
public AlbumRepository(LuminaDbContext luminaDbContext, ITrackRepository trackRepository)
/// <param name="dateTimeProvider">Injected provider for the current UTC time, used to stamp deletions deterministically.</param>
public AlbumRepository(LuminaDbContext luminaDbContext, ITrackRepository trackRepository, IDateTimeProvider dateTimeProvider)
{
_luminaDbContext = luminaDbContext;
_trackRepository = trackRepository;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
@@ -121,7 +125,7 @@ internal sealed class AlbumRepository : IAlbumRepository
.Include(repositoryAlbum => repositoryAlbum.Ratings)
.Include(repositoryAlbum => repositoryAlbum.Contributors)
.AsSplitQuery()
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id, cancellationToken).ConfigureAwait(false);
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id && !repositoryAlbum.IsDeleted && !repositoryAlbum.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false);
if (foundAlbum is null)
return Errors.Music.AlbumNotFound;
@@ -141,9 +145,17 @@ internal sealed class AlbumRepository : IAlbumRepository
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
Guid artistId = foundAlbum.ArtistId;
Guid libraryId = foundAlbum.LibraryId;
bool isDeleted = foundAlbum.IsDeleted;
DateTime? deletedOnUtc = foundAlbum.DeletedOnUtc;
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundAlbum, data);
foundAlbum.ArtistId = artistId;
foundAlbum.LibraryId = libraryId;
// The deletion state is owned by the explicit delete and restore operations. Clearing the modified flags keeps it out of the UPDATE statement,
// so an edit that raced with a delete can never write the deletion state back and resurrect the album.
foundAlbum.IsDeleted = isDeleted;
foundAlbum.DeletedOnUtc = deletedOnUtc;
_luminaDbContext.Entry(foundAlbum).Property(album => album.IsDeleted).IsModified = false;
_luminaDbContext.Entry(foundAlbum).Property(album => album.DeletedOnUtc).IsModified = false;
// Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted.
Result<Updated> reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundAlbum.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
@@ -204,7 +216,8 @@ internal sealed class AlbumRepository : IAlbumRepository
/// <returns>An <see cref="Result{TValue}"/> containing either an <see cref="AlbumEntity"/>, or an error.</returns>
public async Task<Result<AlbumEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
IQueryable<AlbumEntity> query = _luminaDbContext.Albums;
// A deleted album, or an album of a deleted artist, is kept in the storage medium only so that its paths stay reserved and it can be restored, so it is never returned to a caller.
IQueryable<AlbumEntity> query = _luminaDbContext.Albums.Where(album => !album.IsDeleted && !album.Artist!.IsDeleted);
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
@@ -215,17 +228,17 @@ internal sealed class AlbumRepository : IAlbumRepository
.Include(album => album.Tags)
.Include(album => album.Genres)
.Include(album => album.Contributors)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Ratings)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Genres)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Tags)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Moods)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Isrcs)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Contributors)
.AsSplitQuery();
}
@@ -233,7 +246,7 @@ internal sealed class AlbumRepository : IAlbumRepository
}
/// <summary>
/// Gets all the albums of the artist identified by <paramref name="artistId"/>.
/// Gets the albums of the artist identified by <paramref name="artistId"/> that are not soft deleted.
/// </summary>
/// <param name="artistId">The Id of the artist whose albums are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -245,25 +258,54 @@ internal sealed class AlbumRepository : IAlbumRepository
.Include(album => album.Tags)
.Include(album => album.Genres)
.Include(album => album.Contributors)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Ratings)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Genres)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Tags)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Moods)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Isrcs)
.Include(album => album.Tracks)
.Include(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Contributors)
.AsSplitQuery()
.Where(album => album.ArtistId == artistId && !album.IsDeleted && !album.Artist!.IsDeleted)
.OrderBy(album => album.Title)
.ThenBy(album => album.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the albums of the artist identified by <paramref name="artistId"/>, whether they are soft deleted or not.
/// </summary>
/// <param name="artistId">The Id of the artist whose albums are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="AlbumEntity"/>, or an error.</returns>
public async Task<Result<IReadOnlyList<AlbumEntity>>> GetByArtistIdIncludingDeletedAsync(Guid artistId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Albums
.AsNoTracking()
.Where(album => album.ArtistId == artistId)
.OrderBy(album => album.Title)
.ThenBy(album => album.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the album identified by <paramref name="id"/>, whether it is soft deleted or not, without loading its navigation properties.
/// </summary>
/// <param name="id">The Id of the album to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="AlbumEntity"/>, or an error.</returns>
public async Task<Result<AlbumEntity?>> GetIncludingDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Albums
.AsNoTracking()
.FirstOrDefaultAsync(album => album.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the lightweight read models of the albums of the artist identified by <paramref name="artistId"/>,
/// or all of them when the pagination data is <see langword="null"/>, projecting only the fields needed to display the albums in a card-based grid.
@@ -279,7 +321,7 @@ internal sealed class AlbumRepository : IAlbumRepository
// 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)
.Where(album => album.ArtistId == artistId && !album.IsDeleted && !album.Artist!.IsDeleted)
.OrderBy(album => album.Title)
.ThenBy(album => album.Id)
.Select(album => new AlbumLiteRow(
@@ -335,7 +377,7 @@ internal sealed class AlbumRepository : IAlbumRepository
public async Task<Result<AlbumEntity?>> GetByTitleAsync(Guid artistId, string title, CancellationToken cancellationToken)
{
AlbumEntity? album = await _luminaDbContext.Albums
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId && repositoryAlbum.Title == title, cancellationToken).ConfigureAwait(false);
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId && repositoryAlbum.Title == title && !repositoryAlbum.IsDeleted && !repositoryAlbum.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false);
return album;
}
@@ -352,10 +394,98 @@ internal sealed class AlbumRepository : IAlbumRepository
string directoryPrefix = directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
AlbumEntity? album = await _luminaDbContext.Albums
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId
&& !repositoryAlbum.IsDeleted
&& !repositoryAlbum.Artist!.IsDeleted
&& repositoryAlbum.Tracks.Any(track => track.Path.StartsWith(directoryPrefix)), cancellationToken).ConfigureAwait(false);
return album;
}
/// <summary>
/// Gets the soft deleted album identified by <paramref name="id"/>, when its artist is not soft deleted.
/// </summary>
/// <param name="id">The Id of the soft deleted album to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="AlbumEntity"/>, <see langword="null"/> when the album does not exist, is not soft deleted, or its artist is soft deleted, or an error.</returns>
public async Task<Result<AlbumEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Albums
.AsNoTracking()
.FirstOrDefaultAsync(album => album.Id == id && album.IsDeleted && !album.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the soft deleted albums of the media library identified by <paramref name="libraryId"/>, whose artist is not soft deleted.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted albums are 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 soft deleted albums, or an error.</returns>
public async Task<Result<IReadOnlyList<AlbumEntity>>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Albums
.AsNoTracking()
.Include(album => album.Artist)
.Where(album => album.LibraryId == libraryId && album.IsDeleted && !album.Artist!.IsDeleted)
// The deletion time is stored when the album is deleted, so later writes to the hidden row cannot change the order of the deleted items,
// and every deleted row carries a deletion time because the delete operation always sets it. All terms sort descending, so the filtered
// (LibraryId, IsDeleted, DeletedOnUtc, Title, Id) index can be scanned backwards and the database does not build a temporary B-tree.
.OrderByDescending(album => album.DeletedOnUtc)
.ThenByDescending(album => album.Title)
.ThenByDescending(album => album.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Soft deletes the album identified by <paramref name="id"/>, without removing its stored metadata or artwork, when another visible album of its artist remains.
/// </summary>
/// <remarks>
/// The update is executed directly against the storage medium, so an entity already tracked by the caller is not refreshed, and the audit fields
/// stamped by the change tracker are not updated; the deletion time is stored in <see cref="AlbumEntity.DeletedOnUtc"/> instead.
/// </remarks>
/// <param name="id">The Id of the album to soft 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<Updated>> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
DateTime deletedOnUtc = _dateTimeProvider.UtcNow;
// The condition that an artist must have at least one remaining album is re-checked here so a delete that raced with another cannot leave the artist without albums.
int updatedRows = await _luminaDbContext.Albums
.Where(album => album.Id == id
&& !album.IsDeleted
&& _luminaDbContext.Albums.Any(sibling => sibling.ArtistId == album.ArtistId && sibling.Id != album.Id && !sibling.IsDeleted))
.ExecuteUpdateAsync(setters => setters
.SetProperty(album => album.IsDeleted, true)
.SetProperty(album => album.DeletedOnUtc, deletedOnUtc), cancellationToken).ConfigureAwait(false);
if (updatedRows > 0)
return Result.Updated;
// The update matched nothing, so the album is missing, is already deleted, or is the last visible album of its artist. The row is read
// only to report the reason, never to decide the transition.
AlbumEntity? album = await _luminaDbContext.Albums
.AsNoTracking()
.FirstOrDefaultAsync(candidate => candidate.Id == id, cancellationToken).ConfigureAwait(false);
if (album is null || album.IsDeleted)
return Errors.Music.AlbumNotFound;
return Errors.Music.ArtistMustHaveAtLeastOneAlbum;
}
/// <summary>
/// Restores the soft deleted album identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the album to restore.</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<Updated>> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
AlbumEntity? album = await _luminaDbContext.Albums.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == id, cancellationToken).ConfigureAwait(false);
if (album is null || !album.IsDeleted)
return Errors.Music.AlbumNotFound;
album.IsDeleted = false;
album.DeletedOnUtc = null;
return Result.Updated;
}
/// <summary>
/// Deletes the album identified by <paramref name="id"/>, together with its tracks and its contributions, by the database cascade.
/// </summary>
@@ -382,7 +512,7 @@ internal sealed class AlbumRepository : IAlbumRepository
public async Task<Result<int>> GetAlbumsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Albums
.CountAsync(album => album.LibraryId == libraryId && album.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false);
.CountAsync(album => album.LibraryId == libraryId && !album.IsDeleted && !album.Artist!.IsDeleted && album.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -395,6 +525,8 @@ internal sealed class AlbumRepository : IAlbumRepository
{
return await _luminaDbContext.Albums
.CountAsync(album => album.LibraryId == libraryId
&& !album.IsDeleted
&& !album.Artist!.IsDeleted
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album
&& musicArtwork.OwnerId == album.Id
&& (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false);
@@ -416,6 +548,8 @@ internal sealed class AlbumRepository : IAlbumRepository
.AsNoTracking()
.Include(album => album.Artist)
.Where(album => album.LibraryId == libraryId
&& !album.IsDeleted
&& !album.Artist!.IsDeleted
&& !excludedIds.Contains(album.Id)
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album
&& musicArtwork.OwnerId == album.Id
@@ -439,7 +573,7 @@ internal sealed class AlbumRepository : IAlbumRepository
List<AlbumTrackPathRow> rows = await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => albumIdsList.Contains(track.AlbumId))
.Where(track => albumIdsList.Contains(track.AlbumId) && !track.IsDeleted)
.OrderBy(track => track.AlbumId)
.ThenBy(track => track.Path)
.Select(track => new AlbumTrackPathRow(track.AlbumId, track.Path))
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Specifications;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
@@ -38,6 +39,7 @@ internal sealed class ArtistRepository : IArtistRepository
private readonly LuminaDbContext _luminaDbContext;
private readonly IAlbumRepository _albumRepository;
private readonly ITrackRepository _trackRepository;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="ArtistRepository"/> class.
@@ -45,11 +47,13 @@ internal sealed class ArtistRepository : IArtistRepository
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
/// <param name="albumRepository">Injected repository for albums.</param>
/// <param name="trackRepository">Injected repository for tracks.</param>
public ArtistRepository(LuminaDbContext luminaDbContext, IAlbumRepository albumRepository, ITrackRepository trackRepository)
/// <param name="dateTimeProvider">Injected provider for the current UTC time, used to stamp deletions deterministically.</param>
public ArtistRepository(LuminaDbContext luminaDbContext, IAlbumRepository albumRepository, ITrackRepository trackRepository, IDateTimeProvider dateTimeProvider)
{
_luminaDbContext = luminaDbContext;
_albumRepository = albumRepository;
_trackRepository = trackRepository;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
@@ -65,7 +69,7 @@ internal sealed class ArtistRepository : IArtistRepository
return Errors.Music.ArtistAlreadyExists;
// An artist is unique within its library by its name, so the same artist can never be registered twice in the same library.
bool doesArtistNameExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.LibraryId == artist.LibraryId && repositoryArtist.Name == artist.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
bool doesArtistNameExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.LibraryId == artist.LibraryId && repositoryArtist.Name == artist.Name && !repositoryArtist.IsDeleted, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesArtistNameExist)
return Errors.Music.ArtistAlreadyExists;
@@ -154,14 +158,27 @@ internal sealed class ArtistRepository : IArtistRepository
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Contributors)
.AsSplitQuery()
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id, cancellationToken).ConfigureAwait(false);
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id && !repositoryArtist.IsDeleted, cancellationToken).ConfigureAwait(false);
if (foundArtist is null)
return Errors.Music.ArtistNotFound;
// A soft deleted album or track is kept out of every edit, so a payload that names one, even under another parent, must not rewrite it.
Result<Success> validateNoSoftDeletedItemsResult = ValidateNoSoftDeletedItemsAreEdited(foundArtist, data);
if (validateNoSoftDeletedItemsResult.IsFailure)
return validateNoSoftDeletedItemsResult.Errors;
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
Guid libraryId = foundArtist.LibraryId;
bool isDeleted = foundArtist.IsDeleted;
DateTime? deletedOnUtc = foundArtist.DeletedOnUtc;
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundArtist, data);
foundArtist.LibraryId = libraryId;
// The deletion state is owned by the explicit delete and restore operations. Clearing the modified flags keeps it out of the UPDATE statement,
// so an edit that raced with a delete can never write the deletion state back and resurrect the artist.
foundArtist.IsDeleted = isDeleted;
foundArtist.DeletedOnUtc = deletedOnUtc;
_luminaDbContext.Entry(foundArtist).Property(artist => artist.IsDeleted).IsModified = false;
_luminaDbContext.Entry(foundArtist).Property(artist => artist.DeletedOnUtc).IsModified = false;
// A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a
// contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another field of the artist was edited.
@@ -257,7 +274,8 @@ internal sealed class ArtistRepository : IArtistRepository
// albums and their tracks are updated in place, so that persisted entities keep their identity across an edit. An album whose data did
// not change produces no write statement, because its own repository only applies the values that actually changed.
List<Guid> incomingAlbumIds = [.. data.Albums.Select(album => album.Id)];
foreach (AlbumEntity removedAlbum in foundArtist.Albums.Where(album => !incomingAlbumIds.Contains(album.Id)).ToList())
// A soft deleted album is kept out of every edit, so it is never removed from the tracked aggregate, which would permanently delete it.
foreach (AlbumEntity removedAlbum in foundArtist.Albums.Where(album => !album.IsDeleted && !incomingAlbumIds.Contains(album.Id)).ToList())
foundArtist.Albums.Remove(removedAlbum);
foreach (AlbumEntity incomingAlbum in data.Albums)
@@ -283,6 +301,30 @@ internal sealed class ArtistRepository : IArtistRepository
return Result.Updated;
}
/// <summary>
/// Ensures no incoming album or track of <paramref name="data"/> matches a soft deleted album or track of <paramref name="foundArtist"/>.
/// </summary>
/// <param name="foundArtist">The tracked artist that is being updated.</param>
/// <param name="data">The artist carrying the desired albums and tracks.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful check, or an error.</returns>
private static Result<Success> ValidateNoSoftDeletedItemsAreEdited(ArtistEntity foundArtist, ArtistEntity data)
{
Dictionary<Guid, AlbumEntity> storedAlbums = foundArtist.Albums.ToDictionary(album => album.Id);
Dictionary<Guid, TrackEntity> storedTracks = foundArtist.Albums.SelectMany(album => album.Tracks).ToDictionary(track => track.Id);
foreach (AlbumEntity incomingAlbum in data.Albums)
{
if (storedAlbums.TryGetValue(incomingAlbum.Id, out AlbumEntity? storedAlbum) && storedAlbum.IsDeleted)
return Errors.Music.AlbumNotFound;
foreach (TrackEntity incomingTrack in incomingAlbum.Tracks)
if (storedTracks.TryGetValue(incomingTrack.Id, out TrackEntity? storedTrack) && storedTrack.IsDeleted)
return Errors.Music.TrackNotFound;
}
return Result.Success;
}
/// <summary>
/// Gets the file system paths of the tracks that are not yet stored and will therefore be inserted when <paramref name="data"/> is applied over <paramref name="foundArtist"/>.
/// </summary>
@@ -341,7 +383,8 @@ internal sealed class ArtistRepository : IArtistRepository
private async Task<Result<Updated>> ReconcileTracksAsync(AlbumEntity existingAlbum, AlbumEntity incomingAlbum, CancellationToken cancellationToken)
{
List<Guid> incomingTrackIds = [.. incomingAlbum.Tracks.Select(track => track.Id)];
foreach (TrackEntity removedTrack in existingAlbum.Tracks.Where(track => !incomingTrackIds.Contains(track.Id)).ToList())
// A soft deleted track is kept out of every edit, so it is never removed from the tracked album, which would permanently delete it.
foreach (TrackEntity removedTrack in existingAlbum.Tracks.Where(track => !track.IsDeleted && !incomingTrackIds.Contains(track.Id)).ToList())
existingAlbum.Tracks.Remove(removedTrack);
foreach (TrackEntity incomingTrack in incomingAlbum.Tracks)
@@ -375,40 +418,43 @@ internal sealed class ArtistRepository : IArtistRepository
/// <returns>An <see cref="Result{TValue}"/> containing either an <see cref="ArtistEntity"/>, or an error.</returns>
public async Task<Result<ArtistEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
IQueryable<ArtistEntity> query = _luminaDbContext.Artists;
// A deleted artist is kept in the storage medium only so that its paths stay reserved and it can be restored, so it is never returned to a caller.
IQueryable<ArtistEntity> query = _luminaDbContext.Artists.Where(artist => !artist.IsDeleted);
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
// The albums and the tracks of an artist are child entities of its aggregate, so the deleted ones are filtered out of the graph
// that a caller edits or displays, while the repository keeps them stored for a restore.
query = query
.Include(artist => artist.Tags)
.Include(artist => artist.Genres)
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Ratings)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Genres)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tags)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Moods)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Isrcs)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Contributors)
.AsSplitQuery();
}
@@ -446,7 +492,7 @@ internal sealed class ArtistRepository : IArtistRepository
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{ArtistEntity}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<ArtistEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
IQueryable<ArtistEntity> artistsQuery = _luminaDbContext.Artists;
IQueryable<ArtistEntity> artistsQuery = _luminaDbContext.Artists.Where(artist => !artist.IsDeleted);
if (!shouldTrackEntities)
artistsQuery = artistsQuery.AsNoTracking();
if (shouldIncludeNavigationProperties)
@@ -455,31 +501,31 @@ internal sealed class ArtistRepository : IArtistRepository
.Include(artist => artist.Tags)
.Include(artist => artist.Genres)
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Ratings)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Genres)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tags)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Moods)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Isrcs)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Contributors)
.AsSplitQuery();
}
@@ -550,13 +596,13 @@ internal sealed class ArtistRepository : IArtistRepository
return Errors.Library.FilterMustIncludeLibraryId;
// The lightweight read models are retrieved without tracking by default, because they are never modified by the caller.
IQueryable<ArtistEntity> artistsQuery = _luminaDbContext.Artists;
IQueryable<ArtistEntity> artistsQuery = _luminaDbContext.Artists.Where(artist => !artist.IsDeleted);
if (!shouldTrackEntities)
artistsQuery = artistsQuery.AsNoTracking();
if (shouldIncludeNavigationProperties)
artistsQuery = artistsQuery
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.AsSplitQuery();
artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId);
@@ -702,8 +748,10 @@ internal sealed class ArtistRepository : IArtistRepository
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="ArtistEntity"/> with the provided name, or an error.</returns>
public async Task<Result<ArtistEntity?>> GetByNameAsync(Guid libraryId, string name, CancellationToken cancellationToken)
{
// A deleted artist is not returned to the scan, so a scan that finds a new file of the same artist materializes a new, visible artist
// instead of attaching the file to the deleted one.
ArtistEntity? artist = await _luminaDbContext.Artists
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.LibraryId == libraryId && repositoryArtist.Name == name, cancellationToken).ConfigureAwait(false);
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.LibraryId == libraryId && repositoryArtist.Name == name && !repositoryArtist.IsDeleted, cancellationToken).ConfigureAwait(false);
return artist;
}
@@ -729,45 +777,46 @@ internal sealed class ArtistRepository : IArtistRepository
.Include(artist => artist.Tags)
.Include(artist => artist.Ratings)
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.ReleaseTypes)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Genres)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tags)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Ratings)
.Include(artist => artist.Albums)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Moods)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Isrcs)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.WorkLanguages)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.ThenInclude(track => track.WorkIswcs)
.AsSplitQuery()
.Where(artist => artist.LibraryId == libraryId
&& !artist.IsDeleted
&& (artist.MetadataStatus != MetadataStatus.Enriched
|| artist.Albums.Any(album => album.MetadataStatus != MetadataStatus.Enriched)
|| artist.Albums.Any(album => album.Tracks.Any(track => track.MetadataStatus != MetadataStatus.Enriched)))
|| artist.Albums.Any(album => !album.IsDeleted && album.MetadataStatus != MetadataStatus.Enriched)
|| artist.Albums.Any(album => !album.IsDeleted && album.Tracks.Any(track => !track.IsDeleted && track.MetadataStatus != MetadataStatus.Enriched)))
&& (lastName == null || artist.Name.CompareTo(lastName) > 0))
.OrderBy(artist => artist.Name)
.Take(pageSize)
@@ -784,9 +833,10 @@ internal sealed class ArtistRepository : IArtistRepository
{
return await _luminaDbContext.Artists
.CountAsync(artist => artist.LibraryId == libraryId
&& !artist.IsDeleted
&& (artist.MetadataStatus != MetadataStatus.Enriched
|| artist.Albums.Any(album => album.MetadataStatus != MetadataStatus.Enriched)
|| artist.Albums.Any(album => album.Tracks.Any(track => track.MetadataStatus != MetadataStatus.Enriched))), cancellationToken).ConfigureAwait(false);
|| artist.Albums.Any(album => !album.IsDeleted && album.MetadataStatus != MetadataStatus.Enriched)
|| artist.Albums.Any(album => !album.IsDeleted && album.Tracks.Any(track => !track.IsDeleted && track.MetadataStatus != MetadataStatus.Enriched))), cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -799,6 +849,7 @@ internal sealed class ArtistRepository : IArtistRepository
{
return await _luminaDbContext.Artists
.CountAsync(artist => artist.LibraryId == libraryId
&& !artist.IsDeleted
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist
&& musicArtwork.OwnerId == artist.Id
&& (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false);
@@ -817,10 +868,11 @@ internal sealed class ArtistRepository : IArtistRepository
{
return await _luminaDbContext.Artists
.AsNoTracking()
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.Include(artist => artist.Albums.Where(album => !album.IsDeleted))
.ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted))
.AsSplitQuery()
.Where(artist => artist.LibraryId == libraryId
&& !artist.IsDeleted
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist
&& musicArtwork.OwnerId == artist.Id
&& (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable))
@@ -844,6 +896,73 @@ internal sealed class ArtistRepository : IArtistRepository
return Result.Updated;
}
/// <summary>
/// Gets the soft deleted artist identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the soft deleted artist to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="ArtistEntity"/>, <see langword="null"/> when the artist does not exist or is not soft deleted, or an error.</returns>
public async Task<Result<ArtistEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Artists
.AsNoTracking()
.FirstOrDefaultAsync(artist => artist.Id == id && artist.IsDeleted, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the soft deleted artists of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted artists are 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 soft deleted artists, or an error.</returns>
public async Task<Result<IReadOnlyList<ArtistEntity>>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Artists
.AsNoTracking()
.Where(artist => artist.LibraryId == libraryId && artist.IsDeleted)
// The deletion time is stored when the artist is deleted, so later writes to the hidden row cannot change the order of the deleted items,
// and every deleted row carries a deletion time because the delete operation always sets it. All terms sort descending, so the filtered
// (LibraryId, IsDeleted, DeletedOnUtc, Name, Id) index can be scanned backwards and the database does not build a temporary B-tree.
.OrderByDescending(artist => artist.DeletedOnUtc)
.ThenByDescending(artist => artist.Name)
.ThenByDescending(artist => artist.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Soft deletes the artist identified by <paramref name="id"/>, without removing its stored metadata or artwork.
/// </summary>
/// <param name="id">The Id of the artist to soft 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<Updated>> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
ArtistEntity? artist = await _luminaDbContext.Artists.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == id, cancellationToken).ConfigureAwait(false);
if (artist is null || artist.IsDeleted)
return Errors.Music.ArtistNotFound;
artist.IsDeleted = true;
artist.DeletedOnUtc = _dateTimeProvider.UtcNow;
return Result.Updated;
}
/// <summary>
/// Restores the soft deleted artist identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the artist to restore.</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<Updated>> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
ArtistEntity? artist = await _luminaDbContext.Artists.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == id, cancellationToken).ConfigureAwait(false);
if (artist is null || !artist.IsDeleted)
return Errors.Music.ArtistNotFound;
artist.IsDeleted = false;
artist.DeletedOnUtc = null;
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>
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
@@ -26,14 +27,17 @@ namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
internal sealed class TrackRepository : ITrackRepository
{
private readonly LuminaDbContext _luminaDbContext;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="TrackRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public TrackRepository(LuminaDbContext luminaDbContext)
/// <param name="dateTimeProvider">Injected provider for the current UTC time, used to stamp deletions deterministically.</param>
public TrackRepository(LuminaDbContext luminaDbContext, IDateTimeProvider dateTimeProvider)
{
_luminaDbContext = luminaDbContext;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
@@ -73,6 +77,10 @@ internal sealed class TrackRepository : ITrackRepository
/// <summary>
/// Gets the subset of <paramref name="paths"/> that is already used by a track of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <remarks>
/// Soft deleted tracks are included on purpose: their paths must still count as taken, so that a scan never materializes a track that the user
/// deleted back into the catalogue.
/// </remarks>
/// <param name="libraryId">The Id of the library whose tracks are searched.</param>
/// <param name="paths">The track paths to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -113,7 +121,10 @@ internal sealed class TrackRepository : ITrackRepository
.Include(repositoryTrack => repositoryTrack.Moods)
.Include(repositoryTrack => repositoryTrack.Isrcs)
.AsSplitQuery()
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id, cancellationToken).ConfigureAwait(false);
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id
&& !repositoryTrack.IsDeleted
&& !repositoryTrack.Album!.IsDeleted
&& !repositoryTrack.Album!.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false);
if (foundTrack is null)
return Errors.Music.TrackNotFound;
@@ -133,9 +144,17 @@ internal sealed class TrackRepository : ITrackRepository
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
Guid albumId = foundTrack.AlbumId;
Guid libraryId = foundTrack.LibraryId;
bool isDeleted = foundTrack.IsDeleted;
DateTime? deletedOnUtc = foundTrack.DeletedOnUtc;
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundTrack, data);
foundTrack.AlbumId = albumId;
foundTrack.LibraryId = libraryId;
// The deletion state is owned by the explicit delete and restore operations. Clearing the modified flags keeps it out of the UPDATE statement,
// so an edit that raced with a delete can never write the deletion state back and resurrect the track.
foundTrack.IsDeleted = isDeleted;
foundTrack.DeletedOnUtc = deletedOnUtc;
_luminaDbContext.Entry(foundTrack).Property(track => track.IsDeleted).IsModified = false;
_luminaDbContext.Entry(foundTrack).Property(track => track.DeletedOnUtc).IsModified = false;
// Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted.
Result<Updated> reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundTrack.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
@@ -212,7 +231,9 @@ internal sealed class TrackRepository : ITrackRepository
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="TrackEntity"/>, or an error.</returns>
public async Task<Result<TrackEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
IQueryable<TrackEntity> query = _luminaDbContext.Tracks;
// A deleted track, or a track of a deleted album or artist, is kept in the storage medium only so that its path stays reserved and it
// can be restored, so it is never returned to a caller.
IQueryable<TrackEntity> query = _luminaDbContext.Tracks.Where(track => !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted);
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
@@ -232,7 +253,7 @@ internal sealed class TrackRepository : ITrackRepository
}
/// <summary>
/// Gets all the tracks of the album identified by <paramref name="albumId"/>.
/// Gets the tracks of the album identified by <paramref name="albumId"/> that are not soft deleted.
/// </summary>
/// <param name="albumId">The Id of the album whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -247,8 +268,25 @@ internal sealed class TrackRepository : ITrackRepository
.Include(track => track.Isrcs)
.Include(track => track.Contributors)
.AsSplitQuery()
.Where(track => track.AlbumId == albumId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted)
.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);
}
/// <summary>
/// Gets all the tracks of the album identified by <paramref name="albumId"/>, whether they are soft deleted or not.
/// </summary>
/// <param name="albumId">The Id of the album whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="TrackEntity"/>, or an error.</returns>
public async Task<Result<IReadOnlyList<TrackEntity>>> GetByAlbumIdIncludingDeletedAsync(Guid albumId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1
.OrderBy(track => track.DiscNumber ?? 1)
.ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -267,8 +305,8 @@ internal sealed class TrackRepository : ITrackRepository
// The lightweight read models are always retrieved without tracking, because they are never modified by the caller.
IQueryable<TrackLiteRow> liteRowsQuery = _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1
.Where(track => track.AlbumId == albumId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted)
.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(
@@ -325,7 +363,7 @@ internal sealed class TrackRepository : ITrackRepository
{
IQueryable<TrackEntity> query = _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.LibraryId == libraryId);
.Where(track => track.LibraryId == libraryId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted);
if (artistId is not null)
query = query.Where(track => track.Album!.ArtistId == artistId.Value);
@@ -357,6 +395,10 @@ internal sealed class TrackRepository : ITrackRepository
/// <summary>
/// Gets the track of the library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary>
/// <remarks>
/// Soft deleted tracks are included on purpose: when the file disappears from disk, the scan deletion strategy must be able to permanently
/// remove a track that the user had already deleted, instead of leaving its soft deleted row behind.
/// </remarks>
/// <param name="libraryId">The Id of the library whose track is retrieved.</param>
/// <param name="path">The file system path of the track to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -388,7 +430,13 @@ internal sealed class TrackRepository : ITrackRepository
// that is not in the named library, album and artist simply yields no row.
return await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId)
.Where(track => track.Id == trackId
&& track.LibraryId == libraryId
&& track.AlbumId == albumId
&& track.Album!.ArtistId == artistId
&& !track.IsDeleted
&& !track.Album!.IsDeleted
&& !track.Album!.Artist!.IsDeleted)
.Select(track => new TrackStreamDto(
track.Path,
track.LibraryId,
@@ -424,7 +472,13 @@ internal sealed class TrackRepository : ITrackRepository
// that is not in the named library, album and artist simply yields no row.
return await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId)
.Where(track => track.Id == trackId
&& track.LibraryId == libraryId
&& track.AlbumId == albumId
&& track.Album!.ArtistId == artistId
&& !track.IsDeleted
&& !track.Album!.IsDeleted
&& !track.Album!.Artist!.IsDeleted)
.Select(track => new TrackPlaybackManifestDto(
track.Path,
track.Container,
@@ -441,6 +495,89 @@ internal sealed class TrackRepository : ITrackRepository
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the soft deleted track identified by <paramref name="id"/>, when its album and artist are not soft deleted.
/// </summary>
/// <param name="id">The Id of the soft deleted track to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="TrackEntity"/>, <see langword="null"/> when the track does not exist, is not soft deleted, or its album or artist is soft deleted, or an error.</returns>
public async Task<Result<TrackEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Tracks
.AsNoTracking()
.FirstOrDefaultAsync(track => track.Id == id
&& track.IsDeleted
&& !track.Album!.IsDeleted
&& !track.Album!.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the soft deleted tracks of the media library identified by <paramref name="libraryId"/>, whose album and artist are not soft deleted.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted tracks are 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 soft deleted tracks, or an error.</returns>
public async Task<Result<IReadOnlyList<TrackEntity>>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Tracks
.AsNoTracking()
.Include(track => track.Album)
.ThenInclude(album => album!.Artist)
.Where(track => track.LibraryId == libraryId
&& track.IsDeleted
&& !track.Album!.IsDeleted
&& !track.Album!.Artist!.IsDeleted)
// The deletion time is stored when the track is deleted, so later writes to the hidden row cannot change the order of the deleted items,
// and every deleted row carries a deletion time because the delete operation always sets it. All terms sort descending, so the filtered
// (LibraryId, IsDeleted, DeletedOnUtc, Title, Id) index can be scanned backwards and the database does not build a temporary B-tree.
.OrderByDescending(track => track.DeletedOnUtc)
.ThenByDescending(track => track.Title)
.ThenByDescending(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Soft deletes the track identified by <paramref name="id"/>, without removing its stored metadata or artwork.
/// </summary>
/// <remarks>
/// The update is executed directly against the storage medium, so an entity already tracked by the caller is not refreshed, and the audit fields
/// stamped by the change tracker are not updated; the deletion time is stored in <see cref="TrackEntity.DeletedOnUtc"/> instead.
/// </remarks>
/// <param name="id">The Id of the track to soft 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<Updated>> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
DateTime deletedOnUtc = _dateTimeProvider.UtcNow;
// The update covers the existence check and the transition in one statement, so two concurrent deletes of the same track cannot both succeed.
int updatedRows = await _luminaDbContext.Tracks
.Where(track => track.Id == id && !track.IsDeleted)
.ExecuteUpdateAsync(setters => setters
.SetProperty(track => track.IsDeleted, true)
.SetProperty(track => track.DeletedOnUtc, deletedOnUtc), cancellationToken).ConfigureAwait(false);
if (updatedRows == 0)
return Errors.Music.TrackNotFound;
return Result.Updated;
}
/// <summary>
/// Restores the soft deleted track identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the track to restore.</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<Updated>> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
TrackEntity? track = await _luminaDbContext.Tracks.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == id, cancellationToken).ConfigureAwait(false);
if (track is null || !track.IsDeleted)
return Errors.Music.TrackNotFound;
track.IsDeleted = false;
track.DeletedOnUtc = null;
return Result.Updated;
}
/// <summary>
/// Deletes the track identified by <paramref name="id"/>, together with its owned collections and contributions, by the database cascade.
/// </summary>
@@ -529,7 +666,11 @@ internal sealed class TrackRepository : ITrackRepository
public async Task<Result<int>> GetTracksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Tracks
.CountAsync(track => track.LibraryId == libraryId && track.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false);
.CountAsync(track => track.LibraryId == libraryId
&& !track.IsDeleted
&& !track.Album!.IsDeleted
&& !track.Album!.Artist!.IsDeleted
&& track.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -566,7 +707,7 @@ internal sealed class TrackRepository : ITrackRepository
{
List<TrackLibraryCount> chunkCounts = await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => chunk.Contains(track.Id))
.Where(track => chunk.Contains(track.Id) && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted)
.GroupBy(track => track.LibraryId)
.Select(group => new TrackLibraryCount
{
@@ -616,7 +757,7 @@ internal sealed class TrackRepository : ITrackRepository
.Include(track => track.Contributors)
.AsSplitQuery();
}
tracks.AddRange(await query.Where(track => chunk.Contains(track.Id)).ToListAsync(cancellationToken).ConfigureAwait(false));
tracks.AddRange(await query.Where(track => chunk.Contains(track.Id) && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted).ToListAsync(cancellationToken).ConfigureAwait(false));
}
return Result.From<IReadOnlyList<TrackEntity>>(tracks);
}
@@ -578,6 +578,9 @@ internal sealed class PlaylistRepository : IPlaylistRepository
INNER JOIN Albums AS album ON album.Id = track.AlbumId
INNER JOIN Artists AS artist ON artist.Id = album.ArtistId
WHERE track.LibraryId = @libraryId
AND track.IsDeleted = 0
AND album.IsDeleted = 0
AND artist.IsDeleted = 0
""");
if (artistId is not null)
insertSql.Append(" AND album.ArtistId = @artistId");
@@ -965,7 +968,7 @@ internal sealed class PlaylistRepository : IPlaylistRepository
List<PlaylistEntryDisplayDto> chunkDetails = 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 chunk.Contains(track.Id)
where chunk.Contains(track.Id) && !track.IsDeleted && !album.IsDeleted && !artist.IsDeleted
select new PlaylistEntryDisplayDto(
track.Id,
track.Title,
+3 -3
View File
@@ -145,7 +145,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
{
get
{
_artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository);
_artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository, _dateTimeProvider);
return _artistRepository;
}
}
@@ -157,7 +157,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
{
get
{
_albumRepository ??= new AlbumRepository(_luminaDbContext, TrackRepository);
_albumRepository ??= new AlbumRepository(_luminaDbContext, TrackRepository, _dateTimeProvider);
return _albumRepository;
}
}
@@ -169,7 +169,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
{
get
{
_trackRepository ??= new TrackRepository(_luminaDbContext);
_trackRepository ??= new TrackRepository(_luminaDbContext, _dateTimeProvider);
return _trackRepository;
}
}