Cleans up the artwork and the stored media of deleted music library items and libraries.

This commit is contained in:
BinaryAlley committed 2026-10-13 13:26:26 +03:00
1 parent 9d82f283e4
commit 4f43bf352b
23 files changed
+1390 -74

No files matched your search

@@ -442,6 +442,38 @@ public class BookRepositoryTests
Assert.Equal(keptContributor.Id, Assert.Single(storedBook.Contributors).Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyThatLibrariesBooks()
{
// Arrange
// The delete uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-deletebylibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.Create();
bookOfLibrary.LibraryId = libraryId;
bookOfLibrary.Path = "/books/library.epub";
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.Path = "/books/other.epub";
context.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary);
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
context.ChangeTracker.Clear();
BookEntity survivor = Assert.Single(await context.Books.AsNoTracking().ToListAsync());
Assert.Equal(bookOfAnotherLibrary.Id, survivor.Id);
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
@@ -5,6 +5,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioL
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -37,6 +38,8 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -77,6 +80,28 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId));
}
[Fact]
public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldRemoveTheArtworkOfTheAlbumAndOfItsTracks()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg");
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg");
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// The artwork of the album and of its tracks does not cascade from the album row, so it is removed together with the album.
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
public async Task DeleteAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
@@ -184,6 +209,74 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
AlbumEntity album = _albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: "A Night at the Opera",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
// An artist must keep at least one album, so a sibling album is seeded alongside the deleted one.
AlbumEntity otherAlbum = _albumEntityFixture.Create(
id: Guid.NewGuid(),
artistId: artistId,
libraryId: libraryId,
title: "News of the World",
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -35,6 +37,9 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -73,6 +78,33 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
}
[Fact]
public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldRemoveTheArtworkOfTheArtistAndOfItsChildren()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
await SeedArtworkAsync(MusicArtworkOwnerType.Artist, artistId, "media/music/queen/artist.jpg");
await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg");
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg");
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// The artist takes its albums and their tracks with it, and the artwork of all of them does not cascade, so it is removed together with the artist.
Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
Assert.Null(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
public async Task DeleteArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
@@ -163,6 +195,61 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
AlbumEntity album = _albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: "A Night at the Opera",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -6,12 +6,14 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioL
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
@@ -40,6 +42,7 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -81,6 +84,26 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
}
[Fact]
public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldRemoveItsArtworkRecords()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac");
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/bohemian-rhapsody.jpg");
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// The artwork of the track does not cascade from the track row, so it is removed together with the track.
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
public async Task DeleteTrack_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
@@ -229,10 +252,12 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Fact]
@@ -258,8 +283,9 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean validation error instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
@@ -272,8 +298,9 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
@@ -286,8 +313,9 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("AlbumIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
@@ -300,11 +328,27 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>