mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 07:11:10 +00:00
Refactors the add and update album and track slices across the stack
This commit is contained in:
1 parent
ea6eb9f796
commit
54cae054c1
30 files changed
+846
-325
No files matched your search
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -75,56 +76,89 @@ internal sealed class AlbumRepository : IAlbumRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing album, replacing its editable data while preserving its identity and audit columns.
|
||||
/// Updates an existing album, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns.
|
||||
/// </summary>
|
||||
/// <param name="album">The album whose editable data is applied to the stored album.</param>
|
||||
/// <param name="data">The album whose editable data is applied to the stored album.</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>> UpdateAsync(AlbumEntity album, CancellationToken cancellationToken)
|
||||
public async Task<Result<Updated>> UpdateAsync(AlbumEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
AlbumEntity? foundAlbum = await _luminaDbContext.Albums
|
||||
.Include(repositoryAlbum => repositoryAlbum.Tags)
|
||||
.Include(repositoryAlbum => repositoryAlbum.Genres)
|
||||
.Include(repositoryAlbum => repositoryAlbum.Ratings)
|
||||
.Include(repositoryAlbum => repositoryAlbum.Contributors)
|
||||
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == album.Id, cancellationToken).ConfigureAwait(false);
|
||||
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (foundAlbum is null)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
|
||||
// The stored identity and audit columns are never overwritten by an edit.
|
||||
// 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;
|
||||
DateTime createdOnUtc = foundAlbum.CreatedOnUtc;
|
||||
Guid createdBy = foundAlbum.CreatedBy;
|
||||
|
||||
// Copy the editable scalar properties of the album, ignoring the unchanged collection columns.
|
||||
_luminaDbContext.Entry(foundAlbum).CurrentValues.SetValues(album);
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundAlbum, data);
|
||||
foundAlbum.ArtistId = artistId;
|
||||
foundAlbum.LibraryId = libraryId;
|
||||
foundAlbum.CreatedOnUtc = createdOnUtc;
|
||||
foundAlbum.CreatedBy = createdBy;
|
||||
|
||||
// Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated.
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => album.Tags.Select(albumTag => albumTag.Name).Contains(tag.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => album.Genres.Select(albumGenre => albumGenre.Name).Contains(genre.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
await ReconcileTagsAndGenresAsync(foundAlbum, data, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
foundAlbum.Tags.Clear();
|
||||
foundAlbum.Tags.UnionWith(album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
|
||||
foundAlbum.Genres.Clear();
|
||||
foundAlbum.Genres.UnionWith(album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
|
||||
// Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change
|
||||
// are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the album.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Ratings,
|
||||
data.Ratings,
|
||||
existingRating => existingRating.Source?.ToString() ?? string.Empty,
|
||||
incomingRating => incomingRating.Source?.ToString() ?? string.Empty,
|
||||
shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating),
|
||||
createNew: incomingRating => incomingRating);
|
||||
|
||||
// Replace the owned ratings and contributors collections of the album, so that removed entries are deleted and new entries are inserted.
|
||||
foundAlbum.Ratings.Clear();
|
||||
foundAlbum.Ratings.AddRange(album.Ratings);
|
||||
foundAlbum.Contributors.Clear();
|
||||
foundAlbum.Contributors.AddRange(album.Contributors);
|
||||
// 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 album of the same artist was edited.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Contributors,
|
||||
data.Contributors,
|
||||
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
|
||||
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
|
||||
shouldReplace: (existingContributor, incomingContributor) => false,
|
||||
createNew: incomingContributor => incomingContributor);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciles the tags and genres of <paramref name="foundAlbum"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
|
||||
/// </summary>
|
||||
/// <param name="foundAlbum">The tracked album whose tags and genres are reconciled.</param>
|
||||
/// <param name="data">The album carrying the desired tags and genres.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task ReconcileTagsAndGenresAsync(AlbumEntity foundAlbum, AlbumEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
|
||||
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
|
||||
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => tagNames.Contains(tag.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => genreNames.Contains(genre.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Tags,
|
||||
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
|
||||
existingTag => existingTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (existingTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Genres,
|
||||
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
|
||||
existingGenre => existingGenre.Name!,
|
||||
incomingGenre => incomingGenre.Name!,
|
||||
shouldReplace: (existingGenre, incomingGenre) => false,
|
||||
createNew: incomingGenre => incomingGenre);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an album by its Id.
|
||||
/// </summary>
|
||||
|
||||
@@ -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.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -25,14 +26,20 @@ namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
internal sealed class ArtistRepository : IArtistRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
private readonly IAlbumRepository _albumRepository;
|
||||
private readonly ITrackRepository _trackRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ArtistRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public ArtistRepository(LuminaDbContext luminaDbContext)
|
||||
/// <param name="albumRepository">Injected repository for albums.</param>
|
||||
/// <param name="trackRepository">Injected repository for tracks.</param>
|
||||
public ArtistRepository(LuminaDbContext luminaDbContext, IAlbumRepository albumRepository, ITrackRepository trackRepository)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
_albumRepository = albumRepository;
|
||||
_trackRepository = trackRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -87,37 +94,96 @@ internal sealed class ArtistRepository : IArtistRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing artist.
|
||||
/// Updates an existing artist, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns.
|
||||
/// </summary>
|
||||
/// <param name="artist">The artist to update.</param>
|
||||
/// <param name="data">The artist whose editable data is applied to the stored artist.</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>> UpdateAsync(ArtistEntity artist, CancellationToken cancellationToken)
|
||||
public async Task<Result<Updated>> UpdateAsync(ArtistEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
ArtistEntity? foundArtist = await _luminaDbContext.Artists
|
||||
.Include(repositoryArtist => repositoryArtist.Contributors)
|
||||
.Include(repositoryArtist => repositoryArtist.Albums)
|
||||
.ThenInclude(album => album.Tracks)
|
||||
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == artist.Id, cancellationToken).ConfigureAwait(false);
|
||||
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (foundArtist is null)
|
||||
return Errors.Music.ArtistNotFound;
|
||||
|
||||
// The stored identity and audit columns are never overwritten by an edit.
|
||||
// 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;
|
||||
DateTime createdOnUtc = foundArtist.CreatedOnUtc;
|
||||
Guid createdBy = foundArtist.CreatedBy;
|
||||
|
||||
// Copy the editable scalar properties of the artist, ignoring the unchanged collection columns.
|
||||
_luminaDbContext.Entry(foundArtist).CurrentValues.SetValues(artist);
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundArtist, data);
|
||||
foundArtist.LibraryId = libraryId;
|
||||
foundArtist.CreatedOnUtc = createdOnUtc;
|
||||
foundArtist.CreatedBy = createdBy;
|
||||
|
||||
// Replace the owned collections of the artist, so that removed entries are deleted and new entries are inserted.
|
||||
foundArtist.Contributors.Clear();
|
||||
foundArtist.Contributors.AddRange(artist.Contributors);
|
||||
foundArtist.Albums.Clear();
|
||||
foundArtist.Albums.AddRange(artist.Albums);
|
||||
// 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.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundArtist.Contributors,
|
||||
data.Contributors,
|
||||
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
|
||||
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
|
||||
shouldReplace: (existingContributor, incomingContributor) => false,
|
||||
createNew: incomingContributor => incomingContributor);
|
||||
|
||||
// Reconcile the albums by their Id: albums that are no longer present are removed, new albums are inserted, and existing
|
||||
// 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())
|
||||
foundArtist.Albums.Remove(removedAlbum);
|
||||
|
||||
foreach (AlbumEntity incomingAlbum in data.Albums)
|
||||
{
|
||||
AlbumEntity? existingAlbum = foundArtist.Albums.FirstOrDefault(album => album.Id == incomingAlbum.Id);
|
||||
if (existingAlbum is null)
|
||||
{
|
||||
Result<Created> insertAlbumResult = await _albumRepository.InsertAsync(incomingAlbum, cancellationToken).ConfigureAwait(false);
|
||||
if (insertAlbumResult.IsFailure)
|
||||
return insertAlbumResult.Errors;
|
||||
continue;
|
||||
}
|
||||
|
||||
Result<Updated> updateAlbumResult = await _albumRepository.UpdateAsync(incomingAlbum, cancellationToken).ConfigureAwait(false);
|
||||
if (updateAlbumResult.IsFailure)
|
||||
return updateAlbumResult.Errors;
|
||||
|
||||
Result<Updated> updateTracksResult = await ReconcileTracksAsync(existingAlbum, incomingAlbum, cancellationToken).ConfigureAwait(false);
|
||||
if (updateTracksResult.IsFailure)
|
||||
return updateTracksResult.Errors;
|
||||
}
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciles the tracks of an existing album against the provided tracks, by their Id.
|
||||
/// </summary>
|
||||
/// <param name="existingAlbum">The tracked album whose tracks are reconciled.</param>
|
||||
/// <param name="incomingAlbum">The album carrying the tracks to reconcile with.</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>
|
||||
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())
|
||||
existingAlbum.Tracks.Remove(removedTrack);
|
||||
|
||||
foreach (TrackEntity incomingTrack in incomingAlbum.Tracks)
|
||||
{
|
||||
incomingTrack.AlbumId = existingAlbum.Id;
|
||||
incomingTrack.LibraryId = existingAlbum.LibraryId;
|
||||
TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == incomingTrack.Id);
|
||||
if (existingTrack is null)
|
||||
{
|
||||
Result<Created> insertTrackResult = await _trackRepository.InsertAsync(incomingTrack, cancellationToken).ConfigureAwait(false);
|
||||
if (insertTrackResult.IsFailure)
|
||||
return insertTrackResult.Errors;
|
||||
continue;
|
||||
}
|
||||
|
||||
Result<Updated> updateTrackResult = await _trackRepository.UpdateAsync(incomingTrack, cancellationToken).ConfigureAwait(false);
|
||||
if (updateTrackResult.IsFailure)
|
||||
return updateTrackResult.Errors;
|
||||
}
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -67,60 +68,109 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing track, replacing its editable data while preserving its identity and audit columns.
|
||||
/// Updates an existing track, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns.
|
||||
/// </summary>
|
||||
/// <param name="track">The track whose editable data is applied to the stored track.</param>
|
||||
/// <param name="data">The track whose editable data is applied to the stored track.</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>> UpdateAsync(TrackEntity track, CancellationToken cancellationToken)
|
||||
public async Task<Result<Updated>> UpdateAsync(TrackEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
// Every collection that is reconciled must be loaded, so that the reconciliation can see the rows that are already stored and leave the unchanged ones alone.
|
||||
TrackEntity? foundTrack = await _luminaDbContext.Tracks
|
||||
.Include(repositoryTrack => repositoryTrack.Tags)
|
||||
.Include(repositoryTrack => repositoryTrack.Genres)
|
||||
.Include(repositoryTrack => repositoryTrack.Ratings)
|
||||
.Include(repositoryTrack => repositoryTrack.Contributors)
|
||||
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == track.Id, cancellationToken).ConfigureAwait(false);
|
||||
.Include(repositoryTrack => repositoryTrack.Moods)
|
||||
.Include(repositoryTrack => repositoryTrack.Isrcs)
|
||||
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (foundTrack is null)
|
||||
return Errors.Music.TrackNotFound;
|
||||
|
||||
// The stored identity and audit columns are never overwritten by an edit.
|
||||
// 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;
|
||||
DateTime createdOnUtc = foundTrack.CreatedOnUtc;
|
||||
Guid createdBy = foundTrack.CreatedBy;
|
||||
|
||||
// Copy the editable scalar properties of the track, ignoring the unchanged collection columns.
|
||||
_luminaDbContext.Entry(foundTrack).CurrentValues.SetValues(track);
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundTrack, data);
|
||||
foundTrack.AlbumId = albumId;
|
||||
foundTrack.LibraryId = libraryId;
|
||||
foundTrack.CreatedOnUtc = createdOnUtc;
|
||||
foundTrack.CreatedBy = createdBy;
|
||||
|
||||
// Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated.
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => track.Genres.Select(trackGenre => trackGenre.Name).Contains(genre.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
await ReconcileTagsAndGenresAsync(foundTrack, data, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
foundTrack.Tags.Clear();
|
||||
foundTrack.Tags.UnionWith(track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
|
||||
foundTrack.Genres.Clear();
|
||||
foundTrack.Genres.UnionWith(track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
|
||||
// Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change
|
||||
// are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the track.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Ratings,
|
||||
data.Ratings,
|
||||
existingRating => existingRating.Source?.ToString() ?? string.Empty,
|
||||
incomingRating => incomingRating.Source?.ToString() ?? string.Empty,
|
||||
shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating),
|
||||
createNew: incomingRating => incomingRating);
|
||||
|
||||
// Replace the owned collections of the track, so that removed entries are deleted and new entries are inserted.
|
||||
foundTrack.Ratings.Clear();
|
||||
foundTrack.Ratings.AddRange(track.Ratings);
|
||||
foundTrack.Contributors.Clear();
|
||||
foundTrack.Contributors.AddRange(track.Contributors);
|
||||
foundTrack.Moods.Clear();
|
||||
foundTrack.Moods.AddRange(track.Moods);
|
||||
foundTrack.Isrcs.Clear();
|
||||
foundTrack.Isrcs.AddRange(track.Isrcs);
|
||||
// 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 track of the same album was edited.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Contributors,
|
||||
data.Contributors,
|
||||
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
|
||||
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
|
||||
shouldReplace: (existingContributor, incomingContributor) => false,
|
||||
createNew: incomingContributor => incomingContributor);
|
||||
|
||||
// Moods and ISRCs are owned value objects whose value is also their identity, so a match means there is nothing to change.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Moods,
|
||||
data.Moods,
|
||||
existingMood => existingMood.Name,
|
||||
incomingMood => incomingMood.Name,
|
||||
shouldReplace: (existingMood, incomingMood) => false,
|
||||
createNew: incomingMood => incomingMood);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Isrcs,
|
||||
data.Isrcs,
|
||||
existingIsrc => existingIsrc.Value,
|
||||
incomingIsrc => incomingIsrc.Value,
|
||||
shouldReplace: (existingIsrc, incomingIsrc) => false,
|
||||
createNew: incomingIsrc => incomingIsrc);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciles the tags and genres of <paramref name="foundTrack"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
|
||||
/// </summary>
|
||||
/// <param name="foundTrack">The tracked track whose tags and genres are reconciled.</param>
|
||||
/// <param name="data">The track carrying the desired tags and genres.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task ReconcileTagsAndGenresAsync(TrackEntity foundTrack, TrackEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
|
||||
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
|
||||
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => tagNames.Contains(tag.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => genreNames.Contains(genre.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Tags,
|
||||
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
|
||||
existingTag => existingTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (existingTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Genres,
|
||||
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
|
||||
existingGenre => existingGenre.Name!,
|
||||
incomingGenre => incomingGenre.Name!,
|
||||
shouldReplace: (existingGenre, incomingGenre) => false,
|
||||
createNew: incomingGenre => incomingGenre);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a track by its Id.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Themes;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.Books;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaContributors;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
using Lumina.DataAccess.Core.Repositories.Themes;
|
||||
using Lumina.DataAccess.Core.Repositories.Users;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using System;
|
||||
using System.Threading;
|
||||
@@ -37,6 +43,9 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private IRoleRepository? _roleRepository;
|
||||
private IUserRoleRepository? _userRoleRepository;
|
||||
private IBookRepository? _bookRepository;
|
||||
private IArtistRepository? _artistRepository;
|
||||
private IAlbumRepository? _albumRepository;
|
||||
private ITrackRepository? _trackRepository;
|
||||
private IMediaContributorRepository? _mediaContributorRepository;
|
||||
private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository;
|
||||
private ILibraryRepository? _libraryRepository;
|
||||
@@ -114,6 +123,42 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artist repository.
|
||||
/// </summary>
|
||||
public IArtistRepository ArtistRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository);
|
||||
return _artistRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the album repository.
|
||||
/// </summary>
|
||||
public IAlbumRepository AlbumRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_albumRepository ??= new AlbumRepository(_luminaDbContext);
|
||||
return _albumRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the track repository.
|
||||
/// </summary>
|
||||
public ITrackRepository TrackRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_trackRepository ??= new TrackRepository(_luminaDbContext);
|
||||
return _trackRepository;
|
||||
}
|
||||
}
|
||||
|
||||
public IMediaContributorRepository MediaContributorRepository
|
||||
{
|
||||
get
|
||||
@@ -316,9 +361,33 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async Task SaveChangesAsync(CancellationToken cancellationToken)
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.Success;
|
||||
}
|
||||
// A unique constraint violation is an expected persistence conflict, so it is reported as a failure result instead of bubbling up
|
||||
// as an unhandled exception and being turned into a generic internal server error. Any other exception is unexpected and is left
|
||||
// to propagate to the centralized exception handling middleware.
|
||||
catch (DbUpdateException exception) when (IsUniqueConstraintViolation(exception))
|
||||
{
|
||||
return Errors.Persistence.UniqueConstraintViolation;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided <paramref name="exception"/> was caused by a unique constraint violation of the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to inspect.</param>
|
||||
/// <returns><see langword="true"/> if the exception was caused by a unique constraint violation, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsUniqueConstraintViolation(DbUpdateException exception)
|
||||
{
|
||||
// SQLite reports a generic constraint failure code for several constraints, so the extended code is used to tell a unique violation apart.
|
||||
return exception.InnerException is SqliteException sqliteException
|
||||
&& sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user