Adds the music library persistence model, its repositories, and the scanning migration

This commit is contained in:
BinaryAlley committed 2026-10-08 20:48:00 +03:00
1 parent 4f0526faa4
commit 00376c8313
63 files changed
+8679 -203

No files matched your search

@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for a catalog number of a music release. A release can carry more than one catalog number at the same time.
/// </summary>
/// <param name="CatalogNumber">The catalog number assigned by the label.</param>
[DebuggerDisplay("CatalogNumber: {CatalogNumber}")]
public record AlbumCatalogNumberEntity(
string CatalogNumber
);
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -40,11 +41,21 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? OriginalTitle { get; set; }
/// <summary>
/// Gets or sets the title of the specific release (edition) the album files match, if different from the release group title.
/// </summary>
public string? ReleaseTitle { get; set; }
/// <summary>
/// Gets or sets the description of the album, if applicable.
/// </summary>
public string? Description { get; set; }
/// <summary>
/// Gets or sets the disambiguation comment of the album, used to distinguish albums with the same title, if applicable.
/// </summary>
public string? Disambiguation { get; set; }
/// <summary>
/// Gets or sets the original release date of the album, if applicable.
/// </summary>
@@ -106,9 +117,9 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
public string? OriginalLanguageNativeName { get; set; }
/// <summary>
/// Gets or sets the type of the release, if applicable.
/// Gets or sets the script used by the language of the release of the album, if applicable.
/// </summary>
public MusicReleaseType? ReleaseType { get; set; }
public string? Script { get; set; }
/// <summary>
/// Gets or sets the status of the release, if applicable.
@@ -130,15 +141,30 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
/// </summary>
public MusicMediaFormat? MediaFormat { get; set; }
/// <summary>
/// Gets or sets the outermost physical packaging of the album, if applicable.
/// </summary>
public MusicReleasePackaging? Packaging { get; set; }
/// <summary>
/// Gets or sets the barcode of the album, if applicable.
/// </summary>
public string? Barcode { get; set; }
/// <summary>
/// Gets or sets the catalog number of the album, if applicable.
/// Gets or sets the catalog numbers of the album.
/// </summary>
public string? CatalogNumber { get; set; }
public List<AlbumCatalogNumberEntity> CatalogNumbers { get; set; } = [];
/// <summary>
/// Gets or sets the name of the label that issued the album, if applicable.
/// </summary>
public string? Label { get; set; }
/// <summary>
/// Gets or sets the ASIN (Amazon Standard Identification Number) of the album, if applicable.
/// </summary>
public string? ASIN { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz identifier of the release, if applicable.
@@ -175,6 +201,11 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
/// </summary>
public List<AlbumContributorEntity> Contributors { get; set; } = [];
/// <summary>
/// Gets or sets the types of the release. A release can carry more than one type at the same time.
/// </summary>
public List<AlbumReleaseTypeEntity> ReleaseTypes { get; set; } = [];
/// <summary>
/// Gets or sets the genres of the album.
/// </summary>
@@ -185,6 +216,21 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
/// </summary>
public HashSet<TagEntity> Tags { get; set; } = [];
/// <summary>
/// Gets or sets the status of the metadata enrichment of the album.
/// </summary>
public MetadataStatus MetadataStatus { get; set; }
/// <summary>
/// Gets or sets the date and time when the metadata of the album was last enriched.
/// </summary>
public DateTime? LastMetadataUpdateUtc { get; set; }
/// <summary>
/// Gets or sets the name of the plugin that enriched the metadata of the album.
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for a type of a music release. A release can carry more than one type at the same time.
/// </summary>
/// <param name="ReleaseType">The type of the release.</param>
[DebuggerDisplay("ReleaseType: {ReleaseType}")]
public record AlbumReleaseTypeEntity(
MusicReleaseType ReleaseType
);
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for an alternative name of a music artist.
/// </summary>
/// <param name="Name">The name of the alias.</param>
/// <param name="SortName">The sort name of the alias, if applicable.</param>
/// <param name="Type">The type of the alias, if applicable.</param>
/// <param name="Locale">The locale the alias is used in, if applicable.</param>
/// <param name="IsPrimary">Whether this is the primary alias of the artist.</param>
/// <param name="BeginDate">The date the alias began being used, if applicable.</param>
/// <param name="EndDate">The date the alias stopped being used, if applicable.</param>
/// <param name="IsEnded">Whether the alias is no longer used.</param>
[DebuggerDisplay("Name: {Name}")]
public record ArtistAliasEntity(
string Name,
string? SortName,
string? Type,
string? Locale,
bool IsPrimary,
DateOnly? BeginDate,
DateOnly? EndDate,
bool IsEnded
);
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -29,6 +30,46 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
/// </summary>
public required string Name { get; set; }
/// <summary>
/// Gets or sets the sort name of the artist, a variant of the name used when sorting artists, if applicable.
/// </summary>
public string? SortName { get; set; }
/// <summary>
/// Gets or sets the disambiguation comment of the artist, used to distinguish artists with the same name, if applicable.
/// </summary>
public string? Disambiguation { get; set; }
/// <summary>
/// Gets or sets the type of the artist, if applicable.
/// </summary>
public MusicArtistType? Type { get; set; }
/// <summary>
/// Gets or sets the gender of the artist, applicable only to artists that are persons or characters, if applicable.
/// </summary>
public MusicArtistGender? Gender { get; set; }
/// <summary>
/// Gets or sets the ISO 3166-1 alpha-2 code of the country the artist is associated with, if applicable.
/// </summary>
public string? Country { get; set; }
/// <summary>
/// Gets or sets the date the artist started existing, if applicable.
/// </summary>
public DateOnly? LifeSpanBegin { get; set; }
/// <summary>
/// Gets or sets the date the artist stopped existing, if applicable.
/// </summary>
public DateOnly? LifeSpanEnd { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the artist no longer exists.
/// </summary>
public bool IsEnded { get; set; }
/// <summary>
/// Gets or sets the website of the artist, if applicable.
/// </summary>
@@ -39,6 +80,51 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
/// </summary>
public Guid? MusicBrainzArtistId { get; set; }
/// <summary>
/// Gets or sets the area the artist is primarily identified with, if applicable.
/// </summary>
public MusicAreaEntity? Area { get; set; }
/// <summary>
/// Gets or sets the area the artist began in, if applicable.
/// </summary>
public MusicAreaEntity? BeginArea { get; set; }
/// <summary>
/// Gets or sets the area the artist ended in, if applicable.
/// </summary>
public MusicAreaEntity? EndArea { get; set; }
/// <summary>
/// Gets or sets the list of alternative names of the artist.
/// </summary>
public List<ArtistAliasEntity> Aliases { get; set; } = [];
/// <summary>
/// Gets or sets the list of IPI (Interested Party Information) codes of the artist.
/// </summary>
public List<ArtistIpiEntity> Ipis { get; set; } = [];
/// <summary>
/// Gets or sets the list of ISNI (International Standard Name Identifier) codes of the artist.
/// </summary>
public List<ArtistIsniEntity> Isnis { get; set; } = [];
/// <summary>
/// Gets or sets the genres of the artist.
/// </summary>
public HashSet<GenreEntity> Genres { get; set; } = [];
/// <summary>
/// Gets or sets the tags of the artist.
/// </summary>
public HashSet<TagEntity> Tags { get; set; } = [];
/// <summary>
/// Gets or sets the list of ratings of the artist.
/// </summary>
public List<AudioRatingEntity> Ratings { get; set; } = [];
/// <summary>
/// Gets or sets the albums of the artist.
/// </summary>
@@ -49,6 +135,21 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
/// </summary>
public List<ArtistContributorEntity> Contributors { get; set; } = [];
/// <summary>
/// Gets or sets the status of the metadata enrichment of the artist.
/// </summary>
public MetadataStatus MetadataStatus { get; set; }
/// <summary>
/// Gets or sets the date and time when the metadata of the artist was last enriched.
/// </summary>
public DateTime? LastMetadataUpdateUtc { get; set; }
/// <summary>
/// Gets or sets the name of the plugin that enriched the metadata of the artist.
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for an IPI (Interested Party Information) code of a music artist.
/// </summary>
/// <param name="Value">The value of the IPI code.</param>
[DebuggerDisplay("Value: {Value}")]
public record ArtistIpiEntity(
string Value
);
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for an ISNI (International Standard Name Identifier) code of a music artist.
/// </summary>
/// <param name="Value">The value of the ISNI code.</param>
[DebuggerDisplay("Value: {Value}")]
public record ArtistIsniEntity(
string Value
);
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for a MusicBrainz area, the geographic area a music artist is associated with.
/// </summary>
/// <param name="MusicBrainzAreaId">The MusicBrainz identifier of the area.</param>
/// <param name="Name">The name of the area.</param>
/// <param name="SortName">The sort name of the area, if applicable.</param>
/// <param name="Disambiguation">The disambiguation comment of the area, if applicable.</param>
/// <param name="Type">The MusicBrainz type of the area, if applicable.</param>
/// <param name="Iso3166Code">The ISO 3166 code of the area, if applicable.</param>
[DebuggerDisplay("Name: {Name}")]
public record MusicAreaEntity(
Guid MusicBrainzAreaId,
string Name,
string? SortName,
string? Disambiguation,
string? Type,
string? Iso3166Code
);
@@ -0,0 +1,171 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for the metadata extracted from a discovered music file, staged during a scan, before the artists, albums and tracks are materialized from it.
/// </summary>
[DebuggerDisplay("Path: {Path}")]
public class MusicLibraryScanItemMetadataEntity : IStorageEntity
{
/// <summary>
/// Gets the Id of the staged music metadata.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets the Id of the media library scan that this staged music metadata belongs to.
/// </summary>
public required Guid LibraryScanId { get; init; }
/// <summary>
/// Gets the Id of the media library that this staged music metadata belongs to.
/// </summary>
public required Guid LibraryId { get; init; }
/// <summary>
/// Gets the file system path of the music file whose metadata was extracted.
/// </summary>
public required string Path { get; init; }
/// <summary>
/// Gets the name of the artist, if applicable.
/// </summary>
public string? ArtistName { get; set; }
/// <summary>
/// Gets the type of the release, if applicable.
/// </summary>
public MusicReleaseType? ReleaseType { get; set; }
/// <summary>
/// Gets the release year, if applicable.
/// </summary>
public int? ReleaseYear { get; set; }
/// <summary>
/// Gets the name of the release, if applicable.
/// </summary>
public string? ReleaseName { get; set; }
/// <summary>
/// Gets the title of the track, if applicable.
/// </summary>
public string? TrackTitle { get; set; }
/// <summary>
/// Gets the number of the track on its disc, if applicable.
/// </summary>
public int? TrackNumber { get; set; }
/// <summary>
/// Gets the number of the disc the track belongs to, if applicable.
/// </summary>
public int? DiscNumber { get; set; }
/// <summary>
/// Gets the duration of the audio in seconds.
/// </summary>
public int DurationInSeconds { get; set; }
/// <summary>
/// Gets the sample rate of the audio in Hz.
/// </summary>
public int SampleRate { get; set; }
/// <summary>
/// Gets the number of audio channels.
/// </summary>
public int Channels { get; set; }
/// <summary>
/// Gets the bit depth of the audio, if applicable.
/// </summary>
public int? BitDepth { get; set; }
/// <summary>
/// Gets the audio codec used, if applicable.
/// </summary>
public string? AudioCodec { get; set; }
/// <summary>
/// Gets or sets the bitrate of the audio in kbps, if applicable.
/// </summary>
public int? Bitrate { get; set; }
/// <summary>
/// Gets or sets the AcoustID fingerprint identifier of the audio file, if applicable.
/// </summary>
public string? AcoustId { get; set; }
/// <summary>
/// Gets or sets the ReplayGain track gain in decibels, if applicable.
/// </summary>
public decimal? ReplayGainTrackGain { get; set; }
/// <summary>
/// Gets or sets the ReplayGain track peak, if applicable.
/// </summary>
public decimal? ReplayGainTrackPeak { get; set; }
/// <summary>
/// Gets or sets the ReplayGain album gain in decibels, if applicable.
/// </summary>
public decimal? ReplayGainAlbumGain { get; set; }
/// <summary>
/// Gets or sets the ReplayGain album peak, if applicable.
/// </summary>
public decimal? ReplayGainAlbumPeak { get; set; }
/// <summary>
/// Gets or sets the moods of the track, read from the tags of the file.
/// </summary>
public List<string> Moods { get; set; } = [];
/// <summary>
/// Gets the MusicBrainz identifier of the artist, read from the tags of the file, if applicable.
/// </summary>
public Guid? MusicBrainzArtistId { get; set; }
/// <summary>
/// Gets the MusicBrainz identifier of the release artist, read from the tags of the file, if applicable.
/// </summary>
public Guid? MusicBrainzReleaseArtistId { get; set; }
/// <summary>
/// Gets the MusicBrainz identifier of the release group, read from the tags of the file, if applicable.
/// </summary>
public Guid? MusicBrainzReleaseGroupId { get; set; }
/// <summary>
/// Gets the MusicBrainz identifier of the release, read from the tags of the file, if applicable.
/// </summary>
public Guid? MusicBrainzReleaseId { get; set; }
/// <summary>
/// Gets the MusicBrainz identifier of the recording, read from the tags of the file, if applicable.
/// </summary>
public Guid? MusicBrainzRecordingId { get; set; }
/// <summary>
/// Gets the MusicBrainz identifier of the track, read from the tags of the file, if applicable.
/// </summary>
public Guid? MusicBrainzTrackId { get; set; }
/// <summary>
/// Gets the MusicBrainz identifier of the work the track is a recording of, read from the tags of the file, if applicable.
/// </summary>
public Guid? MusicBrainzWorkId { get; set; }
/// <summary>
/// Gets the title of the work the track is a recording of, read from the tags of the file, if applicable.
/// </summary>
public string? WorkTitle { get; set; }
}
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -50,6 +51,11 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? Description { get; set; }
/// <summary>
/// Gets or sets the disambiguation comment of the track, used to distinguish tracks with the same title, if applicable.
/// </summary>
public string? Disambiguation { get; set; }
/// <summary>
/// Gets or sets the original release date of the track, if applicable.
/// </summary>
@@ -140,6 +146,31 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// </summary>
public int? Bitrate { get; set; }
/// <summary>
/// Gets or sets the AcoustID fingerprint identifier of the audio file, if applicable.
/// </summary>
public string? AcoustId { get; set; }
/// <summary>
/// Gets or sets the ReplayGain track gain in decibels, if applicable.
/// </summary>
public decimal? ReplayGainTrackGain { get; set; }
/// <summary>
/// Gets or sets the ReplayGain track peak, if applicable.
/// </summary>
public decimal? ReplayGainTrackPeak { get; set; }
/// <summary>
/// Gets or sets the ReplayGain album gain in decibels, if applicable.
/// </summary>
public decimal? ReplayGainAlbumGain { get; set; }
/// <summary>
/// Gets or sets the ReplayGain album peak, if applicable.
/// </summary>
public decimal? ReplayGainAlbumPeak { get; set; }
/// <summary>
/// Gets or sets the number of the track on its disc.
/// </summary>
@@ -165,10 +196,20 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// </summary>
public int? Bpm { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the recording of the track is a video recording.
/// </summary>
public bool IsVideo { get; set; }
/// <summary>
/// Gets or sets the title of the work the track is a recording of, if applicable.
/// </summary>
public string? Work { get; set; }
public string? WorkTitle { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz type of the work the track is a recording of, if applicable.
/// </summary>
public string? WorkType { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz identifier of the recording, if applicable.
@@ -200,6 +241,16 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// </summary>
public List<TrackIsrcEntity> Isrcs { get; set; } = [];
/// <summary>
/// Gets or sets the list of the languages of the work the track is a recording of.
/// </summary>
public List<TrackWorkLanguageEntity> WorkLanguages { get; set; } = [];
/// <summary>
/// Gets or sets the list of ISWC (International Standard Musical Work Code) of the work the track is a recording of.
/// </summary>
public List<TrackWorkIswcEntity> WorkIswcs { get; set; } = [];
/// <summary>
/// Gets or sets the list of the media contributors of the track.
/// </summary>
@@ -220,6 +271,21 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// </summary>
public HashSet<TagEntity> Tags { get; set; } = [];
/// <summary>
/// Gets or sets the status of the metadata enrichment of the track.
/// </summary>
public MetadataStatus MetadataStatus { get; set; }
/// <summary>
/// Gets or sets the date and time when the metadata of the track was last enriched.
/// </summary>
public DateTime? LastMetadataUpdateUtc { get; set; }
/// <summary>
/// Gets or sets the name of the plugin that enriched the metadata of the track.
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for an ISWC (International Standard Musical Work Code) of the work a track is a recording of.
/// </summary>
/// <param name="Value">The value of the ISWC.</param>
[DebuggerDisplay("Value: {Value}")]
public record TrackWorkIswcEntity(
string Value
);
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Repository entity for a language of the work a track is a recording of.
/// </summary>
/// <param name="LanguageCode">The ISO 639-1 two-letter language code.</param>
/// <param name="LanguageName">The full name of the language in English.</param>
/// <param name="NativeName">The native name of the language, if applicable.</param>
[DebuggerDisplay("LanguageCode: {LanguageCode}")]
public record TrackWorkLanguageEntity(
string LanguageCode,
string LanguageName,
string? NativeName
);
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -47,6 +47,11 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
/// </summary>
public bool ShouldAggregateMetadataWhenMissing { get; set; }
/// <summary>
/// Gets or sets whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not.
/// </summary>
public bool ShouldAggregateArtworkWhenMissing { get; set; }
/// <summary>
/// Gets or sets whether PDF books are rendered as page images for the user, or not. Rendering PDFs as images preserves the
/// original layout, but the pages are not selectable or searchable, unlike their text layer.
@@ -40,6 +40,15 @@ public interface IBookRepository : IRepository<BookEntity>,
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="BookEntity"/> stored at the provided path, or an error.</returns>
Task<Result<BookEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken);
/// <summary>
/// Gets the subset of <paramref name="paths"/> that is already used by a book of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library whose books are searched.</param>
/// <param name="paths">The book paths to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the paths that are already used, or an error.</returns>
Task<Result<IReadOnlyCollection<string>>> GetExistingPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken);
/// <summary>
/// Gets a page of the books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet,
/// ordered by path, using keyset pagination.
@@ -55,6 +55,15 @@ public interface ILibraryScanStagingResultsRepository : IRepository<LibraryScanS
/// <returns>An <see cref="Result{TValue}"/> containing either the paths of the changed staging results, or an error.</returns>
Task<Result<IReadOnlyList<string>>> GetChangedPathsAsync(Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Gets the paths of the media library scan staging results of the current scan that are new or changed, meaning they need their content hashed
/// and their metadata extracted.
/// </summary>
/// <param name="scanId">The unique identifier of the media library scan whose staging result paths 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 paths of the staging results that need rehashing, or an error.</returns>
Task<Result<IReadOnlyList<string>>> GetPathsNeedingRehashAsync(Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Updates the content hashes of the provided media library scan staging results.
/// </summary>
@@ -20,7 +20,8 @@ public interface IAlbumRepository : IRepository<AlbumEntity>,
IInsertRepositoryAction<AlbumEntity>,
IUpdateRepositoryAction<AlbumEntity>,
IApplyUpdateRepositoryAction<AlbumEntity>,
IGetByIdRepositoryAction<AlbumEntity, Guid>
IGetByIdRepositoryAction<AlbumEntity, Guid>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets all the albums of the artist identified by <paramref name="artistId"/>.
@@ -38,4 +39,67 @@ public interface IAlbumRepository : IRepository<AlbumEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="AlbumLiteRow"/>, or an error.</returns>
Task<Result<PaginatedResultDto<AlbumLiteRow>>> GetAlbumsLiteByArtistIdAsync(Guid artistId, PaginationDataDto? paginationData, CancellationToken cancellationToken);
/// <summary>
/// Gets the album of the artist identified by <paramref name="artistId"/> that has the provided <paramref name="title"/>.
/// </summary>
/// <param name="artistId">The Id of the artist whose album is retrieved.</param>
/// <param name="title">The title of the album to retrieve.</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"/> with the provided title, or an error.</returns>
Task<Result<AlbumEntity?>> GetByTitleAsync(Guid artistId, string title, CancellationToken cancellationToken);
/// <summary>
/// Gets the album of the artist identified by <paramref name="artistId"/> that owns a track stored in the provided <paramref name="directoryPath"/>.
/// </summary>
/// <param name="artistId">The Id of the artist whose album is retrieved.</param>
/// <param name="directoryPath">The file system path of the album directory the album owns.</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"/> owning the directory, or an error.</returns>
Task<Result<AlbumEntity?>> GetByTrackDirectoryAsync(Guid artistId, string directoryPath, CancellationToken cancellationToken);
/// <summary>
/// Gets the number of albums of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of albums needing their metadata enriched, or an error.</returns>
Task<Result<int>> GetAlbumsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the number of albums of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet,
/// meaning they have no artwork that is either enriched or confirmed as unavailable.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of albums needing their artwork resolved, or an error.</returns>
Task<Result<int>> GetAlbumsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets a page of the albums of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet,
/// together with their artist, ordered by Id, excluding the provided albums.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are retrieved.</param>
/// <param name="excludedAlbumIds">The Ids of the albums that were already processed in the current run and must not be retrieved again.</param>
/// <param name="pageSize">The maximum number of albums to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a page of albums needing their artwork resolved, or an error.</returns>
Task<Result<IReadOnlyList<AlbumEntity>>> GetAlbumsNeedingArtworkAsync(Guid libraryId, IReadOnlyCollection<Guid> excludedAlbumIds, int pageSize, CancellationToken cancellationToken);
/// <summary>
/// Gets the file system path of one track of each of the albums identified by <paramref name="albumIds"/>, keyed by the Id of the album.
/// </summary>
/// <param name="albumIds">The Ids of the albums whose track path is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the file system path of a track of each album, or an error.</returns>
Task<Result<IReadOnlyDictionary<Guid, string>>> GetFirstTrackPathsByAlbumIdsAsync(IReadOnlyCollection<Guid> albumIds, CancellationToken cancellationToken);
/// <summary>
/// Resets the metadata enrichment status of all the albums of the media library identified by <paramref name="libraryId"/>,
/// so that they are re-enriched, because the metadata provider configuration of the library changed.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are reset.</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>
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -3,7 +3,11 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
@@ -19,4 +23,59 @@ public interface IArtistRepository : IRepository<ArtistEntity>,
IGetAllLiteRepositoryAction<ArtistEntity, ArtistLiteRow>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets the artist of the library identified by <paramref name="libraryId"/> that has the provided <paramref name="name"/>.
/// </summary>
/// <param name="libraryId">The Id of the library whose artist is retrieved.</param>
/// <param name="name">The name of the artist to retrieve.</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="ArtistEntity"/> with the provided name, or an error.</returns>
Task<Result<ArtistEntity?>> GetByNameAsync(Guid libraryId, string name, CancellationToken cancellationToken);
/// <summary>
/// Gets a page of the artists of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet,
/// together with their albums and tracks and the collections needed to enrich them, ordered by name, using keyset pagination.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are retrieved.</param>
/// <param name="lastName">The name of the last retrieved artist, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
/// <param name="pageSize">The maximum number of artists to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a page of artists needing their metadata enriched, or an error.</returns>
Task<Result<IReadOnlyList<ArtistEntity>>> GetArtistsNeedingMetadataAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken);
/// <summary>
/// Gets the number of artists of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of artists needing their metadata enriched, or an error.</returns>
Task<Result<int>> GetArtistsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the number of artists of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of artists needing their artwork resolved, or an error.</returns>
Task<Result<int>> GetArtistsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets a page of the artists of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet,
/// together with their albums and tracks, ordered by name, using keyset pagination.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are retrieved.</param>
/// <param name="lastName">The name of the last retrieved artist, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
/// <param name="pageSize">The maximum number of artists to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a page of artists needing their artwork resolved, or an error.</returns>
Task<Result<IReadOnlyList<ArtistEntity>>> GetArtistsNeedingArtworkAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken);
/// <summary>
/// Resets the metadata enrichment status of all the artists of the media library identified by <paramref name="libraryId"/>,
/// so that they are re-enriched, because the metadata provider configuration of the library changed.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are reset.</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>
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
/// <summary>
/// Interface for the repository for the music metadata staged during a media library scan.
/// </summary>
public interface IMusicLibraryScanItemMetadataRepository : IRepository<MusicLibraryScanItemMetadataEntity>,
IInsertRangeRepositoryAction<MusicLibraryScanItemMetadataEntity>
{
/// <summary>
/// Gets all the staged music metadata items of the media library scan identified by <paramref name="scanId"/>.
/// </summary>
/// <param name="scanId">The Id of the media library scan whose staged music metadata is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicLibraryScanItemMetadataEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>> GetByScanIdAsync(Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the staged music metadata items of the media library scan identified by <paramref name="scanId"/>.
/// </summary>
/// <param name="scanId">The Id of the media library scan whose staged music metadata is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken);
}
@@ -20,7 +20,8 @@ public interface ITrackRepository : IRepository<TrackEntity>,
IInsertRepositoryAction<TrackEntity>,
IUpdateRepositoryAction<TrackEntity>,
IApplyUpdateRepositoryAction<TrackEntity>,
IGetByIdRepositoryAction<TrackEntity, Guid>
IGetByIdRepositoryAction<TrackEntity, Guid>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets the subset of <paramref name="paths"/> that is already used by a track of the library identified by <paramref name="libraryId"/>.
@@ -47,4 +48,40 @@ public interface ITrackRepository : IRepository<TrackEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="TrackLiteRow"/>, or an error.</returns>
Task<Result<PaginatedResultDto<TrackLiteRow>>> GetTracksLiteByAlbumIdAsync(Guid albumId, PaginationDataDto? paginationData, CancellationToken cancellationToken);
/// <summary>
/// Gets the track of the library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary>
/// <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>
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="TrackEntity"/> stored at the provided path, or an error.</returns>
Task<Result<TrackEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken);
/// <summary>
/// Resets the enrichment state of the tracks stored at the provided <paramref name="paths"/> in the media library identified by
/// <paramref name="libraryId"/>, together with their albums and artists, so that they are re-enriched, because their content changed since the last scan.
/// </summary>
/// <param name="libraryId">The Id of the media library whose tracks are reset.</param>
/// <param name="paths">The file system paths of the tracks whose enrichment state is reset.</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>
Task<Result<Updated>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken);
/// <summary>
/// Gets the number of tracks of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose tracks are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of tracks needing their metadata enriched, or an error.</returns>
Task<Result<int>> GetTracksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Resets the metadata enrichment status of all the tracks of the media library identified by <paramref name="libraryId"/>,
/// so that they are re-enriched, because the metadata provider configuration of the library changed.
/// </summary>
/// <param name="libraryId">The Id of the media library whose tracks are reset.</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>
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -60,6 +60,16 @@ public interface IUnitOfWork
/// </summary>
ITrackRepository TrackRepository { get; }
/// <summary>
/// Gets the repository for the artwork of the music library items.
/// </summary>
IMusicArtworkRepository MusicArtworkRepository { get; }
/// <summary>
/// Gets the repository for the music metadata staged during a media library scan.
/// </summary>
IMusicLibraryScanItemMetadataRepository MusicLibraryScanItemMetadataRepository { get; }
/// <summary>
/// Gets the media contributor repository.
/// </summary>
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
@@ -39,73 +40,96 @@ public class AlbumConfiguration : IEntityTypeConfiguration<AlbumEntity>
builder.Property(album => album.OriginalTitle)
.HasMaxLength(255)
.HasColumnOrder(4);
builder.Property(album => album.ReleaseTitle)
.HasMaxLength(255)
.HasColumnOrder(26);
builder.Property(album => album.Description)
.HasMaxLength(2000)
.HasColumnOrder(5);
builder.Property(album => album.OriginalReleaseDate)
builder.Property(album => album.Disambiguation)
.HasMaxLength(255)
.HasColumnOrder(6);
builder.Property(album => album.OriginalReleaseYear)
builder.Property(album => album.OriginalReleaseDate)
.HasColumnOrder(7);
builder.Property(album => album.ReReleaseDate)
builder.Property(album => album.OriginalReleaseYear)
.HasColumnOrder(8);
builder.Property(album => album.ReReleaseYear)
builder.Property(album => album.ReReleaseDate)
.HasColumnOrder(9);
builder.Property(album => album.ReReleaseYear)
.HasColumnOrder(10);
builder.Property(album => album.ReleaseCountry)
.HasConversion<string>()
.HasMaxLength(2)
.HasColumnOrder(10);
builder.Property(album => album.ReleaseVersion)
.HasColumnOrder(11);
builder.Property(album => album.LanguageCode)
builder.Property(album => album.ReleaseVersion)
.HasColumnOrder(12);
builder.Property(album => album.LanguageName)
builder.Property(album => album.LanguageCode)
.HasColumnOrder(13);
builder.Property(album => album.LanguageNativeName)
builder.Property(album => album.LanguageName)
.HasColumnOrder(14);
builder.Property(album => album.OriginalLanguageCode)
builder.Property(album => album.LanguageNativeName)
.HasColumnOrder(15);
builder.Property(album => album.OriginalLanguageName)
builder.Property(album => album.OriginalLanguageCode)
.HasColumnOrder(16);
builder.Property(album => album.OriginalLanguageNativeName)
builder.Property(album => album.OriginalLanguageName)
.HasColumnOrder(17);
builder.Property(album => album.ReleaseType)
.HasConversion<string>()
.HasMaxLength(50)
builder.Property(album => album.OriginalLanguageNativeName)
.HasColumnOrder(18);
builder.Property(album => album.Script)
.HasMaxLength(50)
.HasColumnOrder(19);
builder.Property(album => album.ReleaseStatus)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(19);
builder.Property(album => album.TotalDiscs)
.HasColumnOrder(20);
builder.Property(album => album.TotalTracks)
builder.Property(album => album.TotalDiscs)
.HasColumnOrder(21);
builder.Property(album => album.TotalTracks)
.HasColumnOrder(22);
builder.Property(album => album.MediaFormat)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(22);
builder.Property(album => album.Barcode)
.HasMaxLength(13)
.HasColumnOrder(23);
builder.Property(album => album.CatalogNumber)
builder.Property(album => album.Packaging)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(24);
builder.Property(album => album.MusicBrainzReleaseId)
builder.Property(album => album.Barcode)
.HasMaxLength(13)
.HasColumnOrder(25);
builder.Property(album => album.MusicBrainzReleaseGroupId)
.HasColumnOrder(26);
builder.Property(album => album.MusicBrainzReleaseArtistId)
builder.Property(album => album.Label)
.HasMaxLength(255)
.HasColumnOrder(27);
builder.Property(album => album.ASIN)
.HasMaxLength(20)
.HasColumnOrder(28);
builder.Property(album => album.MusicBrainzReleaseId)
.HasColumnOrder(29);
builder.Property(album => album.MusicBrainzReleaseGroupId)
.HasColumnOrder(30);
builder.Property(album => album.MusicBrainzReleaseArtistId)
.HasColumnOrder(31);
builder.Property(album => album.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(28);
.HasColumnOrder(32);
builder.Property(album => album.CreatedBy)
.IsRequired()
.HasColumnOrder(29);
.HasColumnOrder(33);
builder.Property(album => album.UpdatedOnUtc)
.HasColumnOrder(30);
.HasColumnOrder(34);
builder.Property(album => album.UpdatedBy)
.HasColumnOrder(31);
.HasColumnOrder(35);
builder.Property(album => album.MetadataStatus)
.HasConversion<string>()
.HasMaxLength(20)
.IsRequired()
.HasDefaultValue(MetadataStatus.Pending)
.HasColumnOrder(36);
builder.Property(album => album.LastMetadataUpdateUtc)
.HasColumnOrder(37);
builder.Property(album => album.MetadataProvider)
.HasMaxLength(100)
.HasColumnOrder(38);
builder.HasOne(album => album.Artist)
.WithMany(artist => artist.Albums)
@@ -146,6 +170,35 @@ public class AlbumConfiguration : IEntityTypeConfiguration<AlbumEntity>
j.ToTable("AlbumGenres");
});
builder.OwnsMany(album => album.ReleaseTypes, releaseTypeBuilder =>
{
releaseTypeBuilder.ToTable("AlbumReleaseTypes");
releaseTypeBuilder.WithOwner()
.HasForeignKey("AlbumId");
releaseTypeBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
releaseTypeBuilder.HasKey("Id");
releaseTypeBuilder.Property(releaseType => releaseType.ReleaseType)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired();
});
builder.OwnsMany(album => album.CatalogNumbers, catalogNumberBuilder =>
{
catalogNumberBuilder.ToTable("AlbumCatalogNumbers");
catalogNumberBuilder.WithOwner()
.HasForeignKey("AlbumId");
catalogNumberBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
catalogNumberBuilder.HasKey("Id");
catalogNumberBuilder.Property(catalogNumber => catalogNumber.CatalogNumber)
.HasMaxLength(50)
.IsRequired();
});
builder.OwnsMany(album => album.Ratings, ratingBuilder =>
{
ratingBuilder.ToTable("AlbumRatings");
@@ -1,8 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
@@ -31,21 +34,168 @@ public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
.IsRequired()
.HasMaxLength(255)
.HasColumnOrder(2);
builder.Property(artist => artist.SortName)
.HasMaxLength(255)
.HasColumnOrder(3);
builder.Property(artist => artist.Disambiguation)
.HasMaxLength(255)
.HasColumnOrder(4);
builder.Property(artist => artist.Type)
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(5);
builder.Property(artist => artist.Gender)
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(6);
builder.Property(artist => artist.Country)
.HasMaxLength(2)
.HasColumnOrder(7);
builder.Property(artist => artist.LifeSpanBegin)
.HasColumnOrder(8);
builder.Property(artist => artist.LifeSpanEnd)
.HasColumnOrder(9);
builder.Property(artist => artist.IsEnded)
.HasColumnOrder(10);
builder.Property(artist => artist.Website)
.HasMaxLength(2048)
.HasColumnOrder(3);
.HasColumnOrder(11);
builder.Property(artist => artist.MusicBrainzArtistId)
.HasColumnOrder(4);
.HasColumnOrder(12);
builder.Property(artist => artist.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(5);
.HasColumnOrder(13);
builder.Property(artist => artist.CreatedBy)
.IsRequired()
.HasColumnOrder(6);
.HasColumnOrder(14);
builder.Property(artist => artist.UpdatedOnUtc)
.HasColumnOrder(7);
.HasColumnOrder(15);
builder.Property(artist => artist.UpdatedBy)
.HasColumnOrder(8);
.HasColumnOrder(16);
builder.Property(artist => artist.MetadataStatus)
.HasConversion<string>()
.HasMaxLength(20)
.IsRequired()
.HasDefaultValue(MetadataStatus.Pending)
.HasColumnOrder(17);
builder.Property(artist => artist.LastMetadataUpdateUtc)
.HasColumnOrder(18);
builder.Property(artist => artist.MetadataProvider)
.HasMaxLength(100)
.HasColumnOrder(19);
// 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());
builder.OwnsOne(artist => artist.BeginArea, beginAreaBuilder => beginAreaBuilder.ToJson());
builder.OwnsOne(artist => artist.EndArea, endAreaBuilder => endAreaBuilder.ToJson());
builder.OwnsMany(artist => artist.Aliases, aliasBuilder =>
{
aliasBuilder.ToTable("ArtistAliases");
aliasBuilder.WithOwner()
.HasForeignKey("ArtistId");
aliasBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
aliasBuilder.HasKey("Id");
aliasBuilder.Property(alias => alias.Name)
.IsRequired()
.HasMaxLength(255);
aliasBuilder.Property(alias => alias.SortName)
.HasMaxLength(255);
aliasBuilder.Property(alias => alias.Type)
.HasMaxLength(50);
aliasBuilder.Property(alias => alias.Locale)
.HasMaxLength(20);
});
builder.OwnsMany(artist => artist.Ipis, ipiBuilder =>
{
ipiBuilder.ToTable("ArtistIpis");
ipiBuilder.WithOwner()
.HasForeignKey("ArtistId");
ipiBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
ipiBuilder.HasKey("Id");
ipiBuilder.Property(ipi => ipi.Value)
.IsRequired()
.HasMaxLength(20);
});
builder.OwnsMany(artist => artist.Isnis, isniBuilder =>
{
isniBuilder.ToTable("ArtistIsnis");
isniBuilder.WithOwner()
.HasForeignKey("ArtistId");
isniBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
isniBuilder.HasKey("Id");
isniBuilder.Property(isni => isni.Value)
.IsRequired()
.HasMaxLength(20);
});
// since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key
builder.HasMany(artist => artist.Tags)
.WithMany()
.UsingEntity<Dictionary<string, object>>(
"ArtistTags",
j => j.HasOne<TagEntity>()
.WithMany()
.HasForeignKey("TagId"),
j => j.HasOne<ArtistEntity>()
.WithMany()
.HasForeignKey("ArtistId"),
j =>
{
j.HasKey("ArtistId", "TagId");
j.ToTable("ArtistTags");
});
builder.HasMany(artist => artist.Genres)
.WithMany()
.UsingEntity<Dictionary<string, object>>(
"ArtistGenres",
j => j.HasOne<GenreEntity>()
.WithMany()
.HasForeignKey("GenreId"),
j => j.HasOne<ArtistEntity>()
.WithMany()
.HasForeignKey("ArtistId"),
j =>
{
j.HasKey("ArtistId", "GenreId");
j.ToTable("ArtistGenres");
});
builder.OwnsMany(artist => artist.Ratings, ratingBuilder =>
{
ratingBuilder.ToTable("ArtistRatings");
ratingBuilder.WithOwner()
.HasForeignKey("ArtistId");
ratingBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
ratingBuilder.HasKey("Id");
ratingBuilder.Property(rating => rating.Value)
.HasColumnType("decimal(3,2)")
.IsRequired();
ratingBuilder.Property(rating => rating.MaxValue)
.HasColumnType("decimal(3,2)")
.IsRequired();
ratingBuilder.Property(rating => rating.VoteCount)
.IsRequired(false);
ratingBuilder.Property(rating => rating.Source)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired(false);
});
builder.HasMany(artist => artist.Contributors)
.WithOne()
@@ -0,0 +1,105 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="MusicLibraryScanItemMetadataEntity"/> entity.
/// </summary>
public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguration<MusicLibraryScanItemMetadataEntity>
{
/// <summary>
/// Configures the <see cref="MusicLibraryScanItemMetadataEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<MusicLibraryScanItemMetadataEntity> builder)
{
builder.ToTable("MusicLibraryScanItemMetadata");
builder.HasKey(musicMetadata => musicMetadata.Id);
builder.Property(musicMetadata => musicMetadata.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(musicMetadata => musicMetadata.LibraryScanId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(musicMetadata => musicMetadata.LibraryId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(musicMetadata => musicMetadata.Path)
.IsRequired()
.HasMaxLength(2048)
.HasColumnOrder(3);
builder.Property(musicMetadata => musicMetadata.ArtistName)
.HasMaxLength(255)
.HasColumnOrder(4);
builder.Property(musicMetadata => musicMetadata.ReleaseType)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(5);
builder.Property(musicMetadata => musicMetadata.ReleaseYear)
.HasColumnOrder(6);
builder.Property(musicMetadata => musicMetadata.ReleaseName)
.HasMaxLength(255)
.HasColumnOrder(7);
builder.Property(musicMetadata => musicMetadata.TrackTitle)
.HasMaxLength(255)
.HasColumnOrder(8);
builder.Property(musicMetadata => musicMetadata.TrackNumber)
.HasColumnOrder(9);
builder.Property(musicMetadata => musicMetadata.DiscNumber)
.HasColumnOrder(10);
builder.Property(musicMetadata => musicMetadata.DurationInSeconds)
.HasColumnOrder(11);
builder.Property(musicMetadata => musicMetadata.SampleRate)
.HasColumnOrder(12);
builder.Property(musicMetadata => musicMetadata.Channels)
.HasColumnOrder(13);
builder.Property(musicMetadata => musicMetadata.BitDepth)
.HasColumnOrder(14);
builder.Property(musicMetadata => musicMetadata.AudioCodec)
.HasMaxLength(50)
.HasColumnOrder(15);
builder.Property(musicMetadata => musicMetadata.Bitrate)
.HasColumnOrder(16);
builder.Property(musicMetadata => musicMetadata.MusicBrainzArtistId)
.HasColumnOrder(17);
builder.Property(musicMetadata => musicMetadata.MusicBrainzReleaseArtistId)
.HasColumnOrder(18);
builder.Property(musicMetadata => musicMetadata.MusicBrainzReleaseGroupId)
.HasColumnOrder(19);
builder.Property(musicMetadata => musicMetadata.MusicBrainzReleaseId)
.HasColumnOrder(20);
builder.Property(musicMetadata => musicMetadata.MusicBrainzRecordingId)
.HasColumnOrder(21);
builder.Property(musicMetadata => musicMetadata.MusicBrainzTrackId)
.HasColumnOrder(22);
builder.Property(musicMetadata => musicMetadata.MusicBrainzWorkId)
.HasColumnOrder(23);
builder.Property(musicMetadata => musicMetadata.WorkTitle)
.HasMaxLength(255)
.HasColumnOrder(24);
builder.Property(musicMetadata => musicMetadata.AcoustId)
.HasMaxLength(64)
.HasColumnOrder(25);
builder.Property(musicMetadata => musicMetadata.ReplayGainTrackGain)
.HasColumnType("decimal(8,2)")
.HasColumnOrder(26);
builder.Property(musicMetadata => musicMetadata.ReplayGainTrackPeak)
.HasColumnType("decimal(8,6)")
.HasColumnOrder(27);
builder.Property(musicMetadata => musicMetadata.ReplayGainAlbumGain)
.HasColumnType("decimal(8,2)")
.HasColumnOrder(28);
builder.Property(musicMetadata => musicMetadata.ReplayGainAlbumPeak)
.HasColumnType("decimal(8,6)")
.HasColumnOrder(29);
builder.PrimitiveCollection(musicMetadata => musicMetadata.Moods)
.HasColumnOrder(30);
builder.HasIndex(musicMetadata => new { musicMetadata.LibraryScanId, musicMetadata.Path })
.IsUnique(); // the metadata of the same physical file cannot be staged twice during the same scan
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
@@ -46,77 +47,111 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
builder.Property(track => track.Description)
.HasMaxLength(2000)
.HasColumnOrder(6);
builder.Property(track => track.OriginalReleaseDate)
builder.Property(track => track.Disambiguation)
.HasMaxLength(255)
.HasColumnOrder(7);
builder.Property(track => track.OriginalReleaseYear)
builder.Property(track => track.OriginalReleaseDate)
.HasColumnOrder(8);
builder.Property(track => track.ReReleaseDate)
builder.Property(track => track.OriginalReleaseYear)
.HasColumnOrder(9);
builder.Property(track => track.ReReleaseYear)
builder.Property(track => track.ReReleaseDate)
.HasColumnOrder(10);
builder.Property(track => track.ReReleaseYear)
.HasColumnOrder(11);
builder.Property(track => track.ReleaseCountry)
.HasConversion<string>()
.HasMaxLength(2)
.HasColumnOrder(11);
builder.Property(track => track.ReleaseVersion)
.HasColumnOrder(12);
builder.Property(track => track.LanguageCode)
builder.Property(track => track.ReleaseVersion)
.HasColumnOrder(13);
builder.Property(track => track.LanguageName)
builder.Property(track => track.LanguageCode)
.HasColumnOrder(14);
builder.Property(track => track.LanguageNativeName)
builder.Property(track => track.LanguageName)
.HasColumnOrder(15);
builder.Property(track => track.OriginalLanguageCode)
builder.Property(track => track.LanguageNativeName)
.HasColumnOrder(16);
builder.Property(track => track.OriginalLanguageName)
builder.Property(track => track.OriginalLanguageCode)
.HasColumnOrder(17);
builder.Property(track => track.OriginalLanguageNativeName)
builder.Property(track => track.OriginalLanguageName)
.HasColumnOrder(18);
builder.Property(track => track.DurationInSeconds)
builder.Property(track => track.OriginalLanguageNativeName)
.HasColumnOrder(19);
builder.Property(track => track.SampleRate)
builder.Property(track => track.DurationInSeconds)
.HasColumnOrder(20);
builder.Property(track => track.Channels)
builder.Property(track => track.SampleRate)
.HasColumnOrder(21);
builder.Property(track => track.BitDepth)
builder.Property(track => track.Channels)
.HasColumnOrder(22);
builder.Property(track => track.BitDepth)
.HasColumnOrder(23);
builder.Property(track => track.AudioCodec)
.HasMaxLength(50)
.HasColumnOrder(23);
builder.Property(track => track.Bitrate)
.HasColumnOrder(24);
builder.Property(track => track.TrackNumber)
builder.Property(track => track.Bitrate)
.HasColumnOrder(25);
builder.Property(track => track.DiscNumber)
builder.Property(track => track.TrackNumber)
.HasColumnOrder(26);
builder.Property(track => track.DiscNumber)
.HasColumnOrder(27);
builder.Property(track => track.Script)
.HasMaxLength(50)
.HasColumnOrder(27);
.HasColumnOrder(28);
builder.Property(track => track.Key)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(28);
builder.Property(track => track.Bpm)
.HasColumnOrder(29);
builder.Property(track => track.Work)
.HasMaxLength(255)
builder.Property(track => track.Bpm)
.HasColumnOrder(30);
builder.Property(track => track.MusicBrainzRecordingId)
builder.Property(track => track.IsVideo)
.HasColumnOrder(31);
builder.Property(track => track.MusicBrainzTrackId)
builder.Property(track => track.WorkTitle)
.HasMaxLength(255)
.HasColumnOrder(32);
builder.Property(track => track.MusicBrainzWorkId)
builder.Property(track => track.WorkType)
.HasMaxLength(50)
.HasColumnOrder(33);
builder.Property(track => track.MusicBrainzRecordingId)
.HasColumnOrder(34);
builder.Property(track => track.MusicBrainzTrackId)
.HasColumnOrder(35);
builder.Property(track => track.MusicBrainzWorkId)
.HasColumnOrder(36);
builder.Property(track => track.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(34);
.HasColumnOrder(37);
builder.Property(track => track.CreatedBy)
.IsRequired()
.HasColumnOrder(35);
.HasColumnOrder(38);
builder.Property(track => track.UpdatedOnUtc)
.HasColumnOrder(36);
.HasColumnOrder(39);
builder.Property(track => track.UpdatedBy)
.HasColumnOrder(37);
.HasColumnOrder(40);
builder.Property(track => track.MetadataStatus)
.HasConversion<string>()
.HasMaxLength(20)
.IsRequired()
.HasDefaultValue(MetadataStatus.Pending)
.HasColumnOrder(41);
builder.Property(track => track.LastMetadataUpdateUtc)
.HasColumnOrder(42);
builder.Property(track => track.MetadataProvider)
.HasMaxLength(100)
.HasColumnOrder(43);
builder.Property(track => track.AcoustId)
.HasMaxLength(64)
.HasColumnOrder(44);
builder.Property(track => track.ReplayGainTrackGain)
.HasColumnType("decimal(8,2)")
.HasColumnOrder(45);
builder.Property(track => track.ReplayGainTrackPeak)
.HasColumnType("decimal(8,6)")
.HasColumnOrder(46);
builder.Property(track => track.ReplayGainAlbumGain)
.HasColumnType("decimal(8,2)")
.HasColumnOrder(47);
builder.Property(track => track.ReplayGainAlbumPeak)
.HasColumnType("decimal(8,6)")
.HasColumnOrder(48);
builder.HasOne(track => track.Album)
.WithMany(album => album.Tracks)
@@ -186,6 +221,39 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
.IsRequired();
});
builder.OwnsMany(track => track.WorkLanguages, workLanguageBuilder =>
{
workLanguageBuilder.ToTable("TrackWorkLanguages");
workLanguageBuilder.WithOwner()
.HasForeignKey("TrackId");
workLanguageBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
workLanguageBuilder.HasKey("Id");
workLanguageBuilder.Property(workLanguage => workLanguage.LanguageCode)
.IsRequired()
.HasMaxLength(5);
workLanguageBuilder.Property(workLanguage => workLanguage.LanguageName)
.IsRequired()
.HasMaxLength(100);
workLanguageBuilder.Property(workLanguage => workLanguage.NativeName)
.HasMaxLength(100);
});
builder.OwnsMany(track => track.WorkIswcs, workIswcBuilder =>
{
workIswcBuilder.ToTable("TrackWorkIswcs");
workIswcBuilder.WithOwner()
.HasForeignKey("TrackId");
workIswcBuilder.Property<Guid>("Id")
.ValueGeneratedOnAdd();
workIswcBuilder.HasKey("Id");
workIswcBuilder.Property(workIswc => workIswc.Value)
.HasMaxLength(20)
.IsRequired();
});
builder.HasMany(track => track.Contributors)
.WithOne()
.HasForeignKey(contributor => contributor.TrackId)
@@ -50,6 +50,10 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
.IsRequired()
.HasColumnOrder(10);
builder.Property(settings => settings.ShouldAggregateArtworkWhenMissing)
.IsRequired()
.HasColumnOrder(13);
builder.Property(settings => settings.ShouldRenderPdfAsImages)
.IsRequired()
.HasColumnOrder(11);
@@ -308,6 +308,27 @@ internal sealed class BookRepository : IBookRepository
.FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the subset of <paramref name="paths"/> that is already used by a book of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library whose books are searched.</param>
/// <param name="paths">The book paths to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the paths that are already used, or an error.</returns>
public async Task<Result<IReadOnlyCollection<string>>> GetExistingPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
{
if (paths.Count == 0)
return Result.From<IReadOnlyCollection<string>>([]);
// The stored paths are compared ordinally, matching the case sensitive comparison used by the unique index of the storage medium.
List<string> distinctPaths = [.. paths.Distinct(StringComparer.Ordinal)];
List<string> existingPaths = await _luminaDbContext.Books
.Where(repositoryBook => repositoryBook.LibraryId == libraryId && distinctPaths.Contains(repositoryBook.Path))
.Select(repositoryBook => repositoryBook.Path)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From<IReadOnlyCollection<string>>(existingPaths);
}
/// <summary>
/// Gets a page of the books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet,
/// ordered by path, using keyset pagination.
@@ -169,6 +169,29 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR
return paths.ToList();
}
/// <summary>
/// Gets the paths of the media library scan staging results of the current scan that are new or changed, meaning they need their content hashed
/// and their metadata extracted.
/// </summary>
/// <param name="scanId">The unique identifier of the media library scan whose staging result paths 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 paths of the staging results that need rehashing, or an error.</returns>
public async Task<Result<IReadOnlyList<string>>> GetPathsNeedingRehashAsync(Guid scanId, CancellationToken cancellationToken)
{
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
const string GET_PATHS_SQL = """
SELECT Path
FROM LibraryScanStagingResults
WHERE LibraryScanId = @scanId
AND NeedsRehash = 1;
""";
CommandDefinition command = new(GET_PATHS_SQL, new { scanId }, cancellationToken: cancellationToken);
IEnumerable<string> paths = await connection.QueryAsync<string>(command).ConfigureAwait(false);
return paths.ToList();
}
/// <summary>
/// Updates the content hashes of the provided media library scan staging results.
/// </summary>
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
@@ -37,6 +38,19 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(MediaContributorEntity contributor, CancellationToken cancellationToken)
{
bool doesContributorExist = await _luminaDbContext.MediaContributors
.AnyAsync(repositoryContributor => repositoryContributor.Id == contributor.Id, cancellationToken: cancellationToken)
.ConfigureAwait(false);
if (doesContributorExist)
return Errors.MediaContributor.MediaContributorAlreadyExists;
// A contributor is unique by its display name, so the same person can never be registered twice under different spellings of the same name.
bool doesContributorNameExist = await _luminaDbContext.MediaContributors
.AnyAsync(repositoryContributor => EF.Functions.Collate(repositoryContributor.DisplayName, "NOCASE") == contributor.DisplayName, cancellationToken: cancellationToken)
.ConfigureAwait(false);
if (doesContributorNameExist)
return Errors.MediaContributor.MediaContributorAlreadyExists;
_luminaDbContext.MediaContributors.Add(contributor);
return Result.Created;
}
@@ -54,8 +68,19 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository
// the comparison is case-insensitive, so that "Stephen King" and "stephen king" are never treated as distinct contributors
string normalizedDisplayName = displayName.ToLowerInvariant();
// Contributors added earlier in the same unit of work are not returned by a database query, so the change tracker is consulted
// first; without this, the same contributor discovered for several items of the same save would be inserted more than once and
// violate the unique index on the display name.
MediaContributorEntity? trackedContributor = _luminaDbContext.MediaContributors.Local
.FirstOrDefault(contributor => contributor.DisplayName.ToLowerInvariant() == normalizedDisplayName);
if (trackedContributor is not null)
return trackedContributor;
// The lookup must use the same case-insensitive collation as the unique index on the display name, so that a name whose case is
// not folded by the storage medium (for example one that starts with a non-ASCII uppercase letter) is still matched, instead of
// being inserted again and violating the unique index.
MediaContributorEntity? existingContributor = await _luminaDbContext.MediaContributors
.FirstOrDefaultAsync(contributor => contributor.DisplayName.ToLower() == normalizedDisplayName, cancellationToken)
.FirstOrDefaultAsync(contributor => EF.Functions.Collate(contributor.DisplayName, "NOCASE") == displayName, cancellationToken)
.ConfigureAwait(false);
if (existingContributor is not null)
return existingContributor;
@@ -8,9 +8,12 @@ using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -170,6 +173,24 @@ internal sealed class AlbumRepository : IAlbumRepository
shouldReplace: (existingContributor, incomingContributor) => false,
createNew: incomingContributor => incomingContributor);
// The types of the release are owned value objects whose value is also their identity, so a match means there is nothing to change.
CollectionReconciler.Reconcile(
foundAlbum.ReleaseTypes,
data.ReleaseTypes,
existingReleaseType => existingReleaseType.ReleaseType,
incomingReleaseType => incomingReleaseType.ReleaseType,
shouldReplace: (existingReleaseType, incomingReleaseType) => false,
createNew: incomingReleaseType => incomingReleaseType);
// The catalog numbers of the release are owned value objects whose value is also their identity, so a match means there is nothing to change.
CollectionReconciler.Reconcile(
foundAlbum.CatalogNumbers,
data.CatalogNumbers,
existingCatalogNumber => existingCatalogNumber.CatalogNumber,
incomingCatalogNumber => incomingCatalogNumber.CatalogNumber,
shouldReplace: (existingCatalogNumber, incomingCatalogNumber) => false,
createNew: incomingCatalogNumber => incomingCatalogNumber);
return Result.Updated;
}
@@ -297,4 +318,152 @@ internal sealed class AlbumRepository : IAlbumRepository
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Gets the album of the artist identified by <paramref name="artistId"/> that has the provided <paramref name="title"/>.
/// </summary>
/// <param name="artistId">The Id of the artist whose album is retrieved.</param>
/// <param name="title">The title of the album to retrieve.</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"/> with the provided title, or an error.</returns>
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);
return album;
}
/// <summary>
/// Gets the album of the artist identified by <paramref name="artistId"/> that owns a track stored in the provided <paramref name="directoryPath"/>.
/// </summary>
/// <param name="artistId">The Id of the artist whose album is retrieved.</param>
/// <param name="directoryPath">The file system path of the album directory the album owns.</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"/> owning the directory, or an error.</returns>
public async Task<Result<AlbumEntity?>> GetByTrackDirectoryAsync(Guid artistId, string directoryPath, CancellationToken cancellationToken)
{
// The trailing separator is part of the prefix, so a directory whose name is a prefix of another directory does not match it.
string directoryPrefix = directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
AlbumEntity? album = await _luminaDbContext.Albums
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId
&& repositoryAlbum.Tracks.Any(track => track.Path.StartsWith(directoryPrefix)), cancellationToken).ConfigureAwait(false);
return album;
}
/// <summary>
/// Deletes the album identified by <paramref name="id"/>, together with its tracks and its contributions, by the database cascade.
/// </summary>
/// <param name="id">The Id of the album to 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<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
AlbumEntity? album = await _luminaDbContext.Albums
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == id, cancellationToken).ConfigureAwait(false);
if (album is null)
return Errors.Music.AlbumNotFound;
_luminaDbContext.Albums.Remove(album);
return Result.Deleted;
}
/// <summary>
/// Gets the number of albums of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of albums needing their metadata enriched, or an error.</returns>
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);
}
/// <summary>
/// Gets the number of albums of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of albums needing their artwork resolved, or an error.</returns>
public async Task<Result<int>> GetAlbumsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Albums
.CountAsync(album => album.LibraryId == libraryId
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album
&& musicArtwork.OwnerId == album.Id
&& (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a page of the albums of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet,
/// together with their artist, ordered by Id, excluding the provided albums.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are retrieved.</param>
/// <param name="excludedAlbumIds">The Ids of the albums that were already processed in the current run and must not be retrieved again.</param>
/// <param name="pageSize">The maximum number of albums to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a page of albums needing their artwork resolved, or an error.</returns>
public async Task<Result<IReadOnlyList<AlbumEntity>>> GetAlbumsNeedingArtworkAsync(Guid libraryId, IReadOnlyCollection<Guid> excludedAlbumIds, int pageSize, CancellationToken cancellationToken)
{
List<Guid> excludedIds = [.. excludedAlbumIds];
return await _luminaDbContext.Albums
.AsNoTracking()
.Include(album => album.Artist)
.Where(album => album.LibraryId == libraryId
&& !excludedIds.Contains(album.Id)
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album
&& musicArtwork.OwnerId == album.Id
&& (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)))
.OrderBy(album => album.Id)
.Take(pageSize)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the file system path of one track of each of the albums identified by <paramref name="albumIds"/>, keyed by the Id of the album.
/// </summary>
/// <param name="albumIds">The Ids of the albums whose track path is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the file system path of a track of each album, or an error.</returns>
public async Task<Result<IReadOnlyDictionary<Guid, string>>> GetFirstTrackPathsByAlbumIdsAsync(IReadOnlyCollection<Guid> albumIds, CancellationToken cancellationToken)
{
List<Guid> albumIdsList = [.. albumIds];
if (albumIdsList.Count == 0)
return new Dictionary<Guid, string>();
List<AlbumTrackPathRow> rows = await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => albumIdsList.Contains(track.AlbumId))
.OrderBy(track => track.AlbumId)
.ThenBy(track => track.Path)
.Select(track => new AlbumTrackPathRow(track.AlbumId, track.Path))
.ToListAsync(cancellationToken).ConfigureAwait(false);
// Only one track path is needed per album, so the first one, in the deterministic order above, is kept for each album.
Dictionary<Guid, string> firstTrackPaths = [];
foreach (AlbumTrackPathRow row in rows)
firstTrackPaths.TryAdd(row.AlbumId, row.Path);
return firstTrackPaths;
}
/// <summary>
/// Resets the metadata enrichment status of all the albums of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose albums are reset.</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>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{
await _luminaDbContext.Albums
.Where(album => album.LibraryId == libraryId)
.ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
/// <summary>
/// The file system path of one track of an album, used to describe the album in an artwork lookup.
/// </summary>
/// <param name="AlbumId">The Id of the album the track belongs to.</param>
/// <param name="Path">The file system path of the track.</param>
private sealed record AlbumTrackPathRow(Guid AlbumId, string Path);
}
@@ -11,7 +11,9 @@ using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -72,7 +74,7 @@ internal sealed class ArtistRepository : IArtistRepository
// neither a stored row nor a name shared by several albums or tracks of the same request is tracked more than once.
Result<IReadOnlyDictionary<string, TagEntity>> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
artist.Albums.SelectMany(album => album.Tags).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))),
artist.Tags.Concat(artist.Albums.SelectMany(album => album.Tags)).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))),
Errors.Metadata.TagNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveTagsResult.IsFailure)
@@ -80,12 +82,15 @@ internal sealed class ArtistRepository : IArtistRepository
Result<IReadOnlyDictionary<string, GenreEntity>> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
artist.Albums.SelectMany(album => album.Genres).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))),
artist.Genres.Concat(artist.Albums.SelectMany(album => album.Genres)).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))),
Errors.Metadata.GenreNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveGenresResult.IsFailure)
return resolveGenresResult.Errors;
artist.Tags = [.. SharedReferenceResolver.Normalize(artist.Tags, resolveTagsResult.Value)];
artist.Genres = [.. SharedReferenceResolver.Normalize(artist.Genres, resolveGenresResult.Value)];
foreach (AlbumEntity album in artist.Albums)
{
album.Tags = [.. SharedReferenceResolver.Normalize(album.Tags, resolveTagsResult.Value)];
@@ -113,6 +118,8 @@ internal sealed class ArtistRepository : IArtistRepository
// The whole aggregate is loaded once, including every collection that the album and track repositories reconcile, so that those repositories can apply the
// edit to the already tracked children instead of loading each album and each track again.
ArtistEntity? foundArtist = await _luminaDbContext.Artists
.Include(repositoryArtist => repositoryArtist.Tags)
.Include(repositoryArtist => repositoryArtist.Genres)
.Include(repositoryArtist => repositoryArtist.Contributors)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tags)
@@ -160,6 +167,47 @@ internal sealed class ArtistRepository : IArtistRepository
shouldReplace: (existingContributor, incomingContributor) => false,
createNew: incomingContributor => incomingContributor);
// The tags and the genres of the artist are shared across the whole database, so the stored rows whose names already exist are reused.
Result<Updated> reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundArtist.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileTagsResult.IsFailure)
return reconcileTagsResult.Errors;
Result<Updated> reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundArtist.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileGenresResult.IsFailure)
return reconcileGenresResult.Errors;
// The ratings, the aliases and the identifiers of the artist are owned value objects with no identity anyone could reference, so a changed value is replaced as a whole.
CollectionReconciler.Reconcile(
foundArtist.Ratings,
data.Ratings,
existingRating => existingRating.Source?.ToString() ?? string.Empty,
incomingRating => incomingRating.Source?.ToString() ?? string.Empty,
shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating),
createNew: incomingRating => incomingRating);
CollectionReconciler.Reconcile(
foundArtist.Aliases,
data.Aliases,
existingAlias => existingAlias.Name,
incomingAlias => incomingAlias.Name,
shouldReplace: (existingAlias, incomingAlias) => !existingAlias.Equals(incomingAlias),
createNew: incomingAlias => incomingAlias);
CollectionReconciler.Reconcile(
foundArtist.Ipis,
data.Ipis,
existingIpi => existingIpi.Value,
incomingIpi => incomingIpi.Value,
shouldReplace: (existingIpi, incomingIpi) => false,
createNew: incomingIpi => incomingIpi);
CollectionReconciler.Reconcile(
foundArtist.Isnis,
data.Isnis,
existingIsni => existingIsni.Value,
incomingIsni => incomingIsni.Value,
shouldReplace: (existingIsni, incomingIsni) => false,
createNew: incomingIsni => incomingIsni);
// A track is unique within its library by its file system path, so a track that is about to be inserted during this update can never reference a file
// that is already registered, nor a file that another track of the same update already references. The check runs before anything is written.
List<string> newTrackPaths = [.. GetNewTrackPaths(foundArtist, data)];
@@ -171,19 +219,22 @@ internal sealed class ArtistRepository : IArtistRepository
// and a name that is already stored is reused, before the album and track repositories reconcile their own collections.
Result<IReadOnlyDictionary<string, TagEntity>> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
data.Albums.SelectMany(album => album.Tags).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))),
data.Tags.Concat(data.Albums.SelectMany(album => album.Tags)).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))),
Errors.Metadata.TagNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveTagsResult.IsFailure)
return resolveTagsResult.Errors;
Result<IReadOnlyDictionary<string, GenreEntity>> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
data.Albums.SelectMany(album => album.Genres).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))),
data.Genres.Concat(data.Albums.SelectMany(album => album.Genres)).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))),
Errors.Metadata.GenreNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveGenresResult.IsFailure)
return resolveGenresResult.Errors;
data.Tags = [.. SharedReferenceResolver.Normalize(data.Tags, resolveTagsResult.Value)];
data.Genres = [.. SharedReferenceResolver.Normalize(data.Genres, resolveGenresResult.Value)];
foreach (AlbumEntity dataAlbum in data.Albums)
{
dataAlbum.Tags = [.. SharedReferenceResolver.Normalize(dataAlbum.Tags, resolveTagsResult.Value)];
@@ -324,6 +375,8 @@ internal sealed class ArtistRepository : IArtistRepository
if (shouldIncludeNavigationProperties)
{
query = query
.Include(artist => artist.Tags)
.Include(artist => artist.Genres)
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Ratings)
@@ -393,6 +446,8 @@ internal sealed class ArtistRepository : IArtistRepository
if (shouldIncludeNavigationProperties)
{
artistsQuery = artistsQuery
.Include(artist => artist.Tags)
.Include(artist => artist.Genres)
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Ratings)
@@ -587,4 +642,155 @@ internal sealed class ArtistRepository : IArtistRepository
: artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id),
};
}
/// <summary>
/// Gets the artist of the library identified by <paramref name="libraryId"/> that has the provided <paramref name="name"/>.
/// </summary>
/// <param name="libraryId">The Id of the library whose artist is retrieved.</param>
/// <param name="name">The name of the artist to retrieve.</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="ArtistEntity"/> with the provided name, or an error.</returns>
public async Task<Result<ArtistEntity?>> GetByNameAsync(Guid libraryId, string name, CancellationToken cancellationToken)
{
ArtistEntity? artist = await _luminaDbContext.Artists
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.LibraryId == libraryId && repositoryArtist.Name == name, cancellationToken).ConfigureAwait(false);
return artist;
}
/// <summary>
/// Gets a page of the artists of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet,
/// together with their albums and tracks and the collections needed to enrich them, ordered by name, using keyset pagination.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are retrieved.</param>
/// <param name="lastName">The name of the last retrieved artist, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
/// <param name="pageSize">The maximum number of artists to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a page of artists needing their metadata enriched, or an error.</returns>
public async Task<Result<IReadOnlyList<ArtistEntity>>> GetArtistsNeedingMetadataAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken)
{
return await _luminaDbContext.Artists
.Include(artist => artist.Area)
.Include(artist => artist.BeginArea)
.Include(artist => artist.EndArea)
.Include(artist => artist.Aliases)
.Include(artist => artist.Ipis)
.Include(artist => artist.Isnis)
.Include(artist => artist.Genres)
.Include(artist => artist.Tags)
.Include(artist => artist.Ratings)
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.ReleaseTypes)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Genres)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Tags)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Ratings)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Moods)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Isrcs)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Contributors)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.WorkLanguages)
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.WorkIswcs)
.AsSplitQuery()
.Where(artist => artist.LibraryId == libraryId
&& (artist.MetadataStatus != MetadataStatus.Enriched
|| artist.Albums.Any(album => album.MetadataStatus != MetadataStatus.Enriched)
|| artist.Albums.Any(album => album.Tracks.Any(track => track.MetadataStatus != MetadataStatus.Enriched)))
&& (lastName == null || artist.Name.CompareTo(lastName) > 0))
.OrderBy(artist => artist.Name)
.Take(pageSize)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the number of artists of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of artists needing their metadata enriched, or an error.</returns>
public async Task<Result<int>> GetArtistsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Artists
.CountAsync(artist => artist.LibraryId == libraryId
&& (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);
}
/// <summary>
/// Gets the number of artists of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of artists needing their artwork resolved, or an error.</returns>
public async Task<Result<int>> GetArtistsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Artists
.CountAsync(artist => artist.LibraryId == libraryId
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist
&& musicArtwork.OwnerId == artist.Id
&& (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a page of the artists of the media library identified by <paramref name="libraryId"/> whose artwork has not been resolved yet,
/// together with their albums and tracks, ordered by name, using keyset pagination.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are retrieved.</param>
/// <param name="lastName">The name of the last retrieved artist, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
/// <param name="pageSize">The maximum number of artists to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a page of artists needing their artwork resolved, or an error.</returns>
public async Task<Result<IReadOnlyList<ArtistEntity>>> GetArtistsNeedingArtworkAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken)
{
return await _luminaDbContext.Artists
.AsNoTracking()
.Include(artist => artist.Albums)
.ThenInclude(album => album.Tracks)
.AsSplitQuery()
.Where(artist => artist.LibraryId == libraryId
&& !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist
&& musicArtwork.OwnerId == artist.Id
&& (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable))
&& (lastName == null || artist.Name.CompareTo(lastName) > 0))
.OrderBy(artist => artist.Name)
.Take(pageSize)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resets the metadata enrichment status of all the artists of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are reset.</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>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{
await _luminaDbContext.Artists
.Where(artist => artist.LibraryId == libraryId)
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
}
@@ -0,0 +1,74 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
/// <summary>
/// Repository for the music metadata staged during a media library scan.
/// </summary>
internal sealed class MusicLibraryScanItemMetadataRepository : IMusicLibraryScanItemMetadataRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryScanItemMetadataRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public MusicLibraryScanItemMetadataRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a range of staged music metadata items.
/// </summary>
/// <param name="items">The staged music metadata items to add.</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 Task<Result<Created>> InsertRangeAsync(IReadOnlyCollection<MusicLibraryScanItemMetadataEntity> items, CancellationToken cancellationToken)
{
if (items.Count > 0)
_luminaDbContext.MusicLibraryScanItemMetadata.AddRange(items);
return Task.FromResult<Result<Created>>(Result.Created);
}
/// <summary>
/// Gets all the staged music metadata items of the media library scan identified by <paramref name="scanId"/>.
/// </summary>
/// <param name="scanId">The Id of the media library scan whose staged music metadata is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicLibraryScanItemMetadataEntity"/>, or an error.</returns>
public async Task<Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>> GetByScanIdAsync(Guid scanId, CancellationToken cancellationToken)
{
IReadOnlyList<MusicLibraryScanItemMetadataEntity> items = await _luminaDbContext.MusicLibraryScanItemMetadata
.AsNoTracking()
.Where(musicMetadata => musicMetadata.LibraryScanId == scanId)
.OrderBy(musicMetadata => musicMetadata.Path)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From(items);
}
/// <summary>
/// Deletes all the staged music metadata items of the media library scan identified by <paramref name="scanId"/>.
/// </summary>
/// <param name="scanId">The Id of the media library scan whose staged music metadata is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken)
{
await _luminaDbContext.MusicLibraryScanItemMetadata
.Where(musicMetadata => musicMetadata.LibraryScanId == scanId)
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
}
@@ -8,6 +8,7 @@ using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -175,6 +176,23 @@ internal sealed class TrackRepository : ITrackRepository
shouldReplace: (existingIsrc, incomingIsrc) => false,
createNew: incomingIsrc => incomingIsrc);
// The languages and the ISWCs of the work are owned value objects whose value is also their identity, so a match means there is nothing to change.
CollectionReconciler.Reconcile(
foundTrack.WorkLanguages,
data.WorkLanguages,
existingWorkLanguage => existingWorkLanguage.LanguageCode,
incomingWorkLanguage => incomingWorkLanguage.LanguageCode,
shouldReplace: (existingWorkLanguage, incomingWorkLanguage) => !existingWorkLanguage.Equals(incomingWorkLanguage),
createNew: incomingWorkLanguage => incomingWorkLanguage);
CollectionReconciler.Reconcile(
foundTrack.WorkIswcs,
data.WorkIswcs,
existingWorkIswc => existingWorkIswc.Value,
incomingWorkIswc => incomingWorkIswc.Value,
shouldReplace: (existingWorkIswc, incomingWorkIswc) => false,
createNew: incomingWorkIswc => incomingWorkIswc);
return Result.Updated;
}
@@ -286,4 +304,107 @@ internal sealed class TrackRepository : ITrackRepository
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Gets the track of the library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary>
/// <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>
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="TrackEntity"/> stored at the provided path, or an error.</returns>
public async Task<Result<TrackEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken)
{
TrackEntity? track = await _luminaDbContext.Tracks
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.LibraryId == libraryId && repositoryTrack.Path == path, cancellationToken).ConfigureAwait(false);
return track;
}
/// <summary>
/// Deletes the track identified by <paramref name="id"/>, together with its owned collections and contributions, by the database cascade.
/// </summary>
/// <param name="id">The Id of the track to 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<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
TrackEntity? track = await _luminaDbContext.Tracks
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == id, cancellationToken).ConfigureAwait(false);
if (track is null)
return Errors.Music.TrackNotFound;
_luminaDbContext.Tracks.Remove(track);
return Result.Deleted;
}
/// <summary>
/// Resets the enrichment state of the tracks stored at the provided <paramref name="paths"/> in the media library identified by
/// <paramref name="libraryId"/>, together with their albums and artists.
/// </summary>
/// <param name="libraryId">The Id of the media library whose tracks are reset.</param>
/// <param name="paths">The file system paths of the tracks whose enrichment state is reset.</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>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
{
List<string> pathList = [.. paths];
if (pathList.Count == 0)
return Result.Updated;
// The tracks stored at the changed paths are reset, together with the albums and the artists they belong to, because the metadata of the whole release is re-evaluated.
List<Guid> trackIds = await _luminaDbContext.Tracks
.Where(track => track.LibraryId == libraryId && pathList.Contains(track.Path))
.Select(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (trackIds.Count == 0)
return Result.Updated;
List<Guid> albumIds = await _luminaDbContext.Tracks
.Where(track => trackIds.Contains(track.Id))
.Select(track => track.AlbumId)
.Distinct()
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> artistIds = await _luminaDbContext.Albums
.Where(album => albumIds.Contains(album.Id))
.Select(album => album.ArtistId)
.Distinct()
.ToListAsync(cancellationToken).ConfigureAwait(false);
await _luminaDbContext.Tracks
.Where(track => trackIds.Contains(track.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
await _luminaDbContext.Albums
.Where(album => albumIds.Contains(album.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
await _luminaDbContext.Artists
.Where(artist => artistIds.Contains(artist.Id))
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
/// <summary>
/// Gets the number of tracks of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose tracks are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the number of tracks needing their metadata enriched, or an error.</returns>
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);
}
/// <summary>
/// Resets the metadata enrichment status of all the tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose tracks are reset.</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>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{
await _luminaDbContext.Tracks
.Where(track => track.LibraryId == libraryId)
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
}
@@ -24,6 +24,8 @@ public class LuminaDbContext : DbContext
public virtual DbSet<ArtistEntity> Artists { get; set; } = null!;
public virtual DbSet<AlbumEntity> Albums { get; set; } = null!;
public virtual DbSet<TrackEntity> Tracks { get; set; } = null!;
public virtual DbSet<MusicArtworkEntity> MusicArtwork { get; set; } = null!;
public virtual DbSet<MusicLibraryScanItemMetadataEntity> MusicLibraryScanItemMetadata { get; set; } = null!;
public virtual DbSet<UserEntity> Users { get; set; } = null!;
public virtual DbSet<UserSettingsEntity> UserSettings { get; set; } = null!;
public virtual DbSet<LibraryEntity> Libraries { get; set; } = null!;
@@ -46,6 +46,8 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private IArtistRepository? _artistRepository;
private IAlbumRepository? _albumRepository;
private ITrackRepository? _trackRepository;
private IMusicArtworkRepository? _musicArtworkRepository;
private IMusicLibraryScanItemMetadataRepository? _musicLibraryScanItemMetadataRepository;
private IMediaContributorRepository? _mediaContributorRepository;
private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository;
private ILibraryRepository? _libraryRepository;
@@ -159,6 +161,30 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
/// <summary>
/// Gets the repository for the artwork of the music library items.
/// </summary>
public IMusicArtworkRepository MusicArtworkRepository
{
get
{
_musicArtworkRepository ??= new MusicArtworkRepository(_luminaDbContext);
return _musicArtworkRepository;
}
}
/// <summary>
/// Gets the repository for the music metadata staged during a media library scan.
/// </summary>
public IMusicLibraryScanItemMetadataRepository MusicLibraryScanItemMetadataRepository
{
get
{
_musicLibraryScanItemMetadataRepository ??= new MusicLibraryScanItemMetadataRepository(_luminaDbContext);
return _musicLibraryScanItemMetadataRepository;
}
}
public IMediaContributorRepository MediaContributorRepository
{
get
@@ -22,6 +22,7 @@ public static partial class Errors
public static Error ContributorsListCannotBeNull => Error.Validation(description: nameof(ContributorsListCannotBeNull));
public static Error MediaContributorIdCannotBeEmpty => Error.Validation(description: nameof(MediaContributorIdCannotBeEmpty));
public static Error MediaContributorNotFound => Error.NotFound(description: nameof(MediaContributorNotFound));
public static Error MediaContributorAlreadyExists => Error.Conflict(description: nameof(MediaContributorAlreadyExists));
public static Error UnknownMediaContributorRole => Error.Validation(description: nameof(UnknownMediaContributorRole));
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="AlbumCatalogNumberEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AlbumCatalogNumberEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="AlbumCatalogNumberEntity"/>.
/// </summary>
/// <param name="catalogNumber">Optional. The catalog number assigned by the label.</param>
/// <returns>The created <see cref="AlbumCatalogNumberEntity"/>.</returns>
public AlbumCatalogNumberEntity Create(
string? catalogNumber = null)
{
return new AlbumCatalogNumberEntity(catalogNumber ?? _faker.Random.String2(_faker.Random.Number(1, 50)));
}
/// <summary>
/// Creates a list of <see cref="AlbumCatalogNumberEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<AlbumCatalogNumberEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -6,6 +6,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -24,6 +25,8 @@ public class AlbumEntityFixture
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly AlbumReleaseTypeEntityFixture _albumReleaseTypeEntityFixture = new();
private readonly AlbumCatalogNumberEntityFixture _albumCatalogNumberEntityFixture = new();
private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new();
private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
@@ -71,10 +74,11 @@ public class AlbumEntityFixture
/// <param name="includeReleaseStatus">Whether the release status should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTotalDiscs">Whether the total number of discs should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMediaFormat">Whether the media format should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCatalogNumber">Whether the catalog number should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCatalogNumbers">Whether the catalog number should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="metadataStatus">Optional. The metadata enrichment status of the album.</param>
/// <returns>The created <see cref="AlbumEntity"/>.</returns>
public AlbumEntity Create(
Guid? id = null,
@@ -99,7 +103,7 @@ public class AlbumEntityFixture
MusicReleaseStatus? releaseStatus = null,
int? totalDiscs = null,
MusicMediaFormat? mediaFormat = null,
string? catalogNumber = null,
List<string>? catalogNumbers = null,
Guid? musicBrainzReleaseId = null,
Guid? musicBrainzReleaseGroupId = null,
Guid? musicBrainzReleaseArtistId = null,
@@ -118,10 +122,11 @@ public class AlbumEntityFixture
bool includeReleaseStatus = true,
bool includeTotalDiscs = true,
bool includeMediaFormat = true,
bool includeCatalogNumber = true,
bool includeCatalogNumbers = true,
bool includeMusicBrainzReleaseId = true,
bool includeMusicBrainzReleaseGroupId = true,
bool includeMusicBrainzReleaseArtistId = true)
bool includeMusicBrainzReleaseArtistId = true,
MetadataStatus? metadataStatus = null)
{
Guid resolvedId = id ?? Guid.NewGuid();
Guid resolvedArtistId = artistId ?? Guid.NewGuid();
@@ -140,6 +145,7 @@ public class AlbumEntityFixture
Id = resolvedId,
ArtistId = resolvedArtistId,
LibraryId = resolvedLibraryId,
MetadataStatus = metadataStatus ?? MetadataStatus.Pending,
Title = default!,
CreatedOnUtc = default,
CreatedBy = default,
@@ -147,6 +153,7 @@ public class AlbumEntityFixture
})
.RuleFor(x => x.Title, f => title ?? f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.OriginalTitle, f => includeOriginalTitle ? (originalTitle ?? f.Random.String2(f.Random.Number(1, 255))) : null)
.RuleFor(x => x.ReleaseTitle, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.Description, f => includeDescription ? (description ?? f.Random.String2(f.Random.Number(1, 2000))) : null)
.RuleFor(x => x.OriginalReleaseDate, includeOriginalReleaseDate ? resolvedOriginalReleaseDate : (DateOnly?)null)
.RuleFor(x => x.OriginalReleaseYear, includeOriginalReleaseYear ? resolvedOriginalReleaseYear : (int?)null)
@@ -160,13 +167,13 @@ public class AlbumEntityFixture
.RuleFor(x => x.OriginalLanguageCode, f => includeOriginalLanguage ? (originalLanguageCode ?? f.Random.String2(2)) : null)
.RuleFor(x => x.OriginalLanguageName, f => includeOriginalLanguage ? (originalLanguageName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
.RuleFor(x => x.OriginalLanguageNativeName, f => includeOriginalLanguage ? (originalLanguageNativeName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
.RuleFor(x => x.ReleaseType, f => includeReleaseType ? (releaseType ?? f.PickRandom<MusicReleaseType>()) : (MusicReleaseType?)null)
.RuleFor(x => x.ReleaseTypes, f => includeReleaseType ? [_albumReleaseTypeEntityFixture.Create(releaseType: releaseType)] : [])
.RuleFor(x => x.ReleaseStatus, f => includeReleaseStatus ? (releaseStatus ?? f.PickRandom<MusicReleaseStatus>()) : (MusicReleaseStatus?)null)
.RuleFor(x => x.TotalDiscs, includeTotalDiscs ? (totalDiscs ?? Random.Shared.Next(1, 3)) : (int?)null)
.RuleFor(x => x.TotalTracks, resolvedTracks.Count)
.RuleFor(x => x.MediaFormat, f => includeMediaFormat ? (mediaFormat ?? f.PickRandom<MusicMediaFormat>()) : (MusicMediaFormat?)null)
.RuleFor(x => x.Barcode, f => includeBarcode ? (barcode ?? f.Random.String2(f.Random.Number(12, 13), "0123456789")) : null)
.RuleFor(x => x.CatalogNumber, f => includeCatalogNumber ? (catalogNumber ?? f.Random.String2(f.Random.Number(1, 50))) : null)
.RuleFor(x => x.CatalogNumbers, f => includeCatalogNumbers ? [.. (catalogNumbers ?? [f.Random.String2(f.Random.Number(1, 50))]).Select(catalogNumber => _albumCatalogNumberEntityFixture.Create(catalogNumber: catalogNumber))] : [])
.RuleFor(x => x.MusicBrainzReleaseId, f => includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? f.Random.Guid()) : (Guid?)null)
.RuleFor(x => x.MusicBrainzReleaseGroupId, f => includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? f.Random.Guid()) : (Guid?)null)
.RuleFor(x => x.MusicBrainzReleaseArtistId, f => includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? f.Random.Guid()) : (Guid?)null)
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="AlbumReleaseTypeEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AlbumReleaseTypeEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="AlbumReleaseTypeEntity"/>.
/// </summary>
/// <param name="releaseType">Optional. The type of the release.</param>
/// <returns>The created <see cref="AlbumReleaseTypeEntity"/>.</returns>
public AlbumReleaseTypeEntity Create(
MusicReleaseType? releaseType = null)
{
return new AlbumReleaseTypeEntity(releaseType ?? _faker.PickRandom<MusicReleaseType>());
}
/// <summary>
/// Creates a list of <see cref="AlbumReleaseTypeEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<AlbumReleaseTypeEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="ArtistAliasEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistAliasEntityFixture
{
private const int MINIMUM_ALIAS_YEAR = 1900;
private const int MAXIMUM_ALIAS_YEAR = 2026;
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ArtistAliasEntity"/>.
/// </summary>
/// <param name="name">Optional. The name of the alias.</param>
/// <param name="sortName">Optional. The sort name of the alias.</param>
/// <param name="type">Optional. The type of the alias.</param>
/// <param name="locale">Optional. The locale the alias is used in.</param>
/// <param name="isPrimary">Optional. Whether this is the primary alias of the artist.</param>
/// <param name="beginDate">Optional. The date the alias began being used.</param>
/// <param name="endDate">Optional. The date the alias stopped being used.</param>
/// <param name="isEnded">Optional. Whether the alias is no longer used.</param>
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeLocale">Whether the locale should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBeginDate">Whether the begin date should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeEndDate">Whether the end date should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="ArtistAliasEntity"/>.</returns>
public ArtistAliasEntity Create(
string? name = null,
string? sortName = null,
string? type = null,
string? locale = null,
bool? isPrimary = null,
DateOnly? beginDate = null,
DateOnly? endDate = null,
bool? isEnded = null,
bool includeSortName = true,
bool includeType = true,
bool includeLocale = true,
bool includeBeginDate = true,
bool includeEndDate = true)
{
int beginYear = Random.Shared.Next(MINIMUM_ALIAS_YEAR, MAXIMUM_ALIAS_YEAR);
int endYear = Random.Shared.Next(beginYear, Math.Max(beginYear + 1, MAXIMUM_ALIAS_YEAR));
return new ArtistAliasEntity(
name ?? _faker.Name.FullName(),
includeSortName ? (sortName ?? _faker.Name.FullName()) : null,
includeType ? (type ?? _faker.Random.ArrayElement(["Artist name", "Search hint"])) : null,
includeLocale ? (locale ?? _faker.Random.String2(2)) : null,
isPrimary ?? _faker.Random.Bool(),
includeBeginDate ? (beginDate ?? new DateOnly(beginYear, 1, 1)) : null,
includeEndDate ? (endDate ?? new DateOnly(endYear, 1, 1)) : null,
isEnded ?? _faker.Random.Bool());
}
/// <summary>
/// Creates a list of <see cref="ArtistAliasEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ArtistAliasEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="ArtistIpiEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistIpiEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ArtistIpiEntity"/>.
/// </summary>
/// <param name="value">Optional. The value of the IPI code.</param>
/// <returns>The created <see cref="ArtistIpiEntity"/>.</returns>
public ArtistIpiEntity Create(
string? value = null)
{
return new ArtistIpiEntity(value ?? _faker.Random.String2(_faker.Random.Number(1, 20), "0123456789"));
}
/// <summary>
/// Creates a list of <see cref="ArtistIpiEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ArtistIpiEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="ArtistIsniEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistIsniEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ArtistIsniEntity"/>.
/// </summary>
/// <param name="value">Optional. The value of the ISNI code.</param>
/// <returns>The created <see cref="ArtistIsniEntity"/>.</returns>
public ArtistIsniEntity Create(
string? value = null)
{
return new ArtistIsniEntity(value ?? _faker.Random.String2(_faker.Random.Number(1, 20), "0123456789X"));
}
/// <summary>
/// Creates a list of <see cref="ArtistIsniEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<ArtistIsniEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="MusicAreaEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicAreaEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MusicAreaEntity"/>.
/// </summary>
/// <param name="musicBrainzAreaId">Optional. The MusicBrainz identifier of the area.</param>
/// <param name="name">Optional. The name of the area.</param>
/// <param name="sortName">Optional. The sort name of the area.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the area.</param>
/// <param name="type">Optional. The MusicBrainz type of the area.</param>
/// <param name="iso3166Code">Optional. The ISO 3166 code of the area.</param>
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeIso3166Code">Whether the ISO 3166 code should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="MusicAreaEntity"/>.</returns>
public MusicAreaEntity Create(
Guid? musicBrainzAreaId = null,
string? name = null,
string? sortName = null,
string? disambiguation = null,
string? type = null,
string? iso3166Code = null,
bool includeSortName = true,
bool includeDisambiguation = true,
bool includeType = true,
bool includeIso3166Code = true)
{
return new MusicAreaEntity(
musicBrainzAreaId ?? _faker.Random.Guid(),
name ?? _faker.Address.Country(),
includeSortName ? (sortName ?? _faker.Address.Country()) : null,
includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null,
includeType ? (type ?? _faker.Random.ArrayElement(["Country", "City", "Area"])) : null,
includeIso3166Code ? (iso3166Code ?? _faker.Address.CountryCode()) : null);
}
/// <summary>
/// Creates a list of <see cref="MusicAreaEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<MusicAreaEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="MusicLibraryScanItemMetadataEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryScanItemMetadataEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MusicLibraryScanItemMetadataEntity"/>.
/// </summary>
/// <param name="id">Optional. The Id of the staged metadata.</param>
/// <param name="libraryScanId">Optional. The Id of the media library scan the staged metadata belongs to.</param>
/// <param name="libraryId">Optional. The Id of the media library the staged metadata belongs to.</param>
/// <param name="path">Optional. The file system path of the music file.</param>
/// <param name="artistName">Optional. The name of the artist.</param>
/// <param name="releaseName">Optional. The name of the release.</param>
/// <param name="trackTitle">Optional. The title of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="musicBrainzReleaseArtistId">Optional. The MusicBrainz identifier of the release artist.</param>
/// <param name="musicBrainzReleaseGroupId">Optional. The MusicBrainz identifier of the release group.</param>
/// <param name="musicBrainzReleaseId">Optional. The MusicBrainz identifier of the release.</param>
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
/// <param name="workTitle">Optional. The title of the work.</param>
/// <param name="includeMusicBrainzTags">Whether the MusicBrainz identifiers and the work title should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="MusicLibraryScanItemMetadataEntity"/>.</returns>
public MusicLibraryScanItemMetadataEntity Create(
Guid? id = null,
Guid? libraryScanId = null,
Guid? libraryId = null,
string? path = null,
string? artistName = null,
string? releaseName = null,
string? trackTitle = null,
int? trackNumber = null,
int? discNumber = null,
Guid? musicBrainzArtistId = null,
Guid? musicBrainzReleaseArtistId = null,
Guid? musicBrainzReleaseGroupId = null,
Guid? musicBrainzReleaseId = null,
Guid? musicBrainzRecordingId = null,
Guid? musicBrainzTrackId = null,
Guid? musicBrainzWorkId = null,
string? workTitle = null,
bool includeMusicBrainzTags = true)
{
return new MusicLibraryScanItemMetadataEntity
{
Id = id ?? Guid.NewGuid(),
LibraryScanId = libraryScanId ?? Guid.NewGuid(),
LibraryId = libraryId ?? Guid.NewGuid(),
Path = path ?? _faker.System.FilePath(),
ArtistName = artistName ?? _faker.Name.FullName(),
ReleaseType = _faker.PickRandom<MusicReleaseType>(),
ReleaseYear = Random.Shared.Next(1900, 2026),
ReleaseName = releaseName ?? _faker.Music.Genre(),
TrackTitle = trackTitle ?? _faker.Music.Genre(),
TrackNumber = trackNumber ?? _faker.Random.Int(1, 20),
DiscNumber = discNumber ?? _faker.Random.Int(1, 3),
DurationInSeconds = Random.Shared.Next(60, 7200),
SampleRate = _faker.PickRandom(44100, 48000, 96000),
Channels = _faker.PickRandom(1, 2, 6),
BitDepth = Random.Shared.Next(8, 32),
AudioCodec = _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC"),
Bitrate = Random.Shared.Next(96, 1411),
MusicBrainzArtistId = includeMusicBrainzTags ? musicBrainzArtistId ?? Guid.NewGuid() : null,
MusicBrainzReleaseArtistId = includeMusicBrainzTags ? musicBrainzReleaseArtistId ?? Guid.NewGuid() : null,
MusicBrainzReleaseGroupId = includeMusicBrainzTags ? musicBrainzReleaseGroupId ?? Guid.NewGuid() : null,
MusicBrainzReleaseId = includeMusicBrainzTags ? musicBrainzReleaseId ?? Guid.NewGuid() : null,
MusicBrainzRecordingId = includeMusicBrainzTags ? musicBrainzRecordingId ?? Guid.NewGuid() : null,
MusicBrainzTrackId = includeMusicBrainzTags ? musicBrainzTrackId ?? Guid.NewGuid() : null,
MusicBrainzWorkId = includeMusicBrainzTags ? musicBrainzWorkId ?? Guid.NewGuid() : null,
WorkTitle = includeMusicBrainzTags ? workTitle ?? _faker.Music.Genre() : null
};
}
/// <summary>
/// Creates a list of <see cref="MusicLibraryScanItemMetadataEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<MusicLibraryScanItemMetadataEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -6,6 +6,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -46,6 +47,7 @@ public class TrackEntityFixture
/// <param name="includeOriginalReleaseYear">Whether the original release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReReleaseDate">Whether the re-release date should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReReleaseYear">Whether the re-release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="metadataStatus">Optional. The metadata enrichment status of the track.</param>
/// <returns>The created <see cref="TrackEntity"/>.</returns>
public TrackEntity Create(
Guid? id = null,
@@ -62,7 +64,8 @@ public class TrackEntityFixture
bool includeOriginalReleaseDate = true,
bool includeOriginalReleaseYear = true,
bool includeReReleaseDate = true,
bool includeReReleaseYear = true)
bool includeReReleaseYear = true,
MetadataStatus? metadataStatus = null)
{
Guid resolvedId = id ?? Guid.NewGuid();
Guid resolvedAlbumId = albumId ?? Guid.NewGuid();
@@ -80,6 +83,7 @@ public class TrackEntityFixture
Id = resolvedId,
AlbumId = resolvedAlbumId,
LibraryId = resolvedLibraryId,
MetadataStatus = metadataStatus ?? MetadataStatus.Pending,
Path = default!,
Title = default!,
CreatedOnUtc = default,
@@ -113,7 +117,9 @@ public class TrackEntityFixture
.RuleFor(x => x.Script, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.Key, f => f.PickRandom<MusicKey>())
.RuleFor(x => x.Bpm, Random.Shared.Next(40, 240))
.RuleFor(x => x.Work, f => f.Music.Genre())
.RuleFor(x => x.IsVideo, f => f.Random.Bool())
.RuleFor(x => x.WorkTitle, f => f.Music.Genre())
.RuleFor(x => x.WorkType, f => f.Music.Genre())
.RuleFor(x => x.MusicBrainzRecordingId, f => f.Random.Guid())
.RuleFor(x => x.MusicBrainzTrackId, f => f.Random.Guid())
.RuleFor(x => x.MusicBrainzWorkId, f => f.Random.Guid())
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="TrackWorkIswcEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackWorkIswcEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TrackWorkIswcEntity"/>.
/// </summary>
/// <param name="value">Optional. The value of the ISWC.</param>
/// <returns>The created <see cref="TrackWorkIswcEntity"/>.</returns>
public TrackWorkIswcEntity Create(
string? value = null)
{
return new TrackWorkIswcEntity(value ?? $"T{_faker.Random.AlphaNumeric(10)}");
}
/// <summary>
/// Creates a list of <see cref="TrackWorkIswcEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<TrackWorkIswcEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="TrackWorkLanguageEntity"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackWorkLanguageEntityFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TrackWorkLanguageEntity"/>.
/// </summary>
/// <param name="languageCode">Optional. The ISO 639-1 two-letter language code.</param>
/// <param name="languageName">Optional. The full name of the language in English.</param>
/// <param name="nativeName">Optional. The native name of the language.</param>
/// <param name="includeNativeName">Whether the native name should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="TrackWorkLanguageEntity"/>.</returns>
public TrackWorkLanguageEntity Create(
string? languageCode = null,
string? languageName = null,
string? nativeName = null,
bool includeNativeName = true)
{
return new TrackWorkLanguageEntity(
languageCode ?? _faker.PickRandom("en", "fr", "de", "es", "it", "ja", "ko", "zh", "pt", "ru"),
languageName ?? _faker.Lorem.Word(),
includeNativeName ? (nativeName ?? _faker.Lorem.Word()) : null);
}
/// <summary>
/// Creates a list of <see cref="TrackWorkLanguageEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<TrackWorkLanguageEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,8 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.Setup;using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
@@ -19,6 +20,10 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Wr
public class BookEntityFixture
{
private readonly Faker _faker = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly IsbnEntityFixture _isbnEntityFixture = new();
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
/// <summary>
/// Creates a random valid <see cref="BookEntity"/>.
@@ -60,8 +65,8 @@ public class BookEntityFixture
.RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2))
.RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.Tags, f => includeMetadata ? [.. CreateTags(f.Random.Number(1, 5))] : [])
.RuleFor(x => x.Genres, f => includeMetadata ? [.. CreateGenres(f.Random.Number(1, 5))] : [])
.RuleFor(x => x.Tags, f => includeMetadata ? [.. _tagEntityFixture.CreateMany(f.Random.Number(1, 5))] : [])
.RuleFor(x => x.Genres, f => includeMetadata ? [.. _genreEntityFixture.CreateMany(f.Random.Number(1, 5))] : [])
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, Random.Shared.Next(100, 300))
.RuleFor(x => x.Format, f => f.PickRandom<BookFormat>())
@@ -76,8 +81,8 @@ public class BookEntityFixture
.RuleFor(x => x.GoogleBooksId, CreateGoogleBooksId)
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
.RuleFor(x => x.ISBNs, f => includeMetadata ? CreateIsbns(f.Random.Number(1, 5)) : [])
.RuleFor(x => x.Ratings, f => includeMetadata ? CreateBookRatings(f.Random.Number(1, 5)) : [])
.RuleFor(x => x.ISBNs, f => includeMetadata ? _isbnEntityFixture.CreateMany(f.Random.Number(1, 5)) : [])
.RuleFor(x => x.Ratings, f => includeMetadata ? _bookRatingEntityFixture.CreateMany(f.Random.Number(1, 5)) : [])
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
.Generate();
@@ -93,30 +98,6 @@ public class BookEntityFixture
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates a list of tag entities with random data.
/// </summary>
/// <param name="count">The number of tags to create.</param>
/// <returns>A list of randomly generated tag entities.</returns>
private static List<TagEntity> CreateTags(int count)
{
return new Faker<TagEntity>()
.CustomInstantiator(f => new TagEntity(f.Random.String2(f.Random.Number(1, 50))))
.Generate(count);
}
/// <summary>
/// Creates a list of genre entities with random data.
/// </summary>
/// <param name="count">The number of genres to create.</param>
/// <returns>A list of randomly generated genre entities.</returns>
private static List<GenreEntity> CreateGenres(int count)
{
return new Faker<GenreEntity>()
.CustomInstantiator(f => new GenreEntity(f.Random.String2(f.Random.Number(1, 50))))
.Generate(count);
}
/// <summary>
/// Creates a valid Library of Congress Control Number (LCCN).
/// </summary>
@@ -172,73 +153,4 @@ public class BookEntityFixture
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])]);
}
/// <summary>
/// Creates a list of ISBN entities with random data.
/// </summary>
/// <param name="count">The number of ISBNs to create.</param>
/// <returns>A list of randomly generated ISBN entities.</returns>
private static List<IsbnEntity> CreateIsbns(int count)
{
return new Faker<IsbnEntity>()
.CustomInstantiator(f =>
{
string isbnValue = CreateIsbn(f);
return new IsbnEntity(isbnValue, isbnValue.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10);
})
.Generate(count);
}
/// <summary>
/// Creates a valid ISBN (International Standard Book Number).
/// </summary>
/// <param name="f">The Faker instance used for generating random data.</param>
/// <returns>A properly formatted ISBN-10 or ISBN-13 string with valid checksum.</returns>
private static string CreateIsbn(Faker f)
{
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
{
string prefix = f.Random.Bool() ? "978" : "979";
string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - (sum % 10)) % 10;
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
else
{
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = f.Random.Number(0, 9);
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (10 - i) * digits[i];
int checkDigit = (11 - (sum % 11)) % 11;
string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString();
return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}";
}
}
/// <summary>
/// Creates a list of book rating entities with random data.
/// </summary>
/// <param name="count">The number of ratings to create.</param>
/// <returns>A list of randomly generated book rating entities.</returns>
private static List<BookRatingEntity> CreateBookRatings(int count)
{
return new Faker<BookRatingEntity>()
.CustomInstantiator(f => new BookRatingEntity(
f.Random.Decimal(1, 5),
5,
f.PickRandom<BookRatingSource>(),
f.Random.Number(1, 1000)
))
.Generate(count);
}
}
@@ -18,20 +18,22 @@ public class IsbnEntityFixture
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="IsbnEntity"/>.
/// Creates a random valid <see cref="IsbnEntity"/>, with a value that satisfies the ISBN checksum and a format that matches it.
/// </summary>
/// <param name="value">Optional. The ISBN value.</param>
/// <param name="format">Optional. The format of the ISBN.</param>
/// <param name="includeValue">Whether the value should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeFormat">Whether the format should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="IsbnEntity"/>.</returns>
public IsbnEntity Create(
string? value = null,
IsbnFormat? format = null,
bool includeValue = true)
string? value = null,
IsbnFormat? format = null,
bool includeValue = true,
bool includeFormat = true)
{
return new IsbnEntity(
includeValue ? value ?? _faker.Random.String2(13, "0123456789") : null,
format);
string? resolvedValue = includeValue ? value ?? CreateValidIsbn13() : null;
IsbnFormat? resolvedFormat = includeFormat ? format ?? InferFormat(resolvedValue) : null;
return new IsbnEntity(resolvedValue, resolvedFormat);
}
/// <summary>
@@ -43,4 +45,33 @@ public class IsbnEntityFixture
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Infers the format of an ISBN from the number of digits of its value.
/// </summary>
/// <param name="value">The ISBN value whose format is inferred.</param>
/// <returns>The inferred ISBN format.</returns>
private static IsbnFormat InferFormat(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return IsbnFormat.Isbn13;
int digitCount = value.Count(char.IsLetterOrDigit);
return digitCount is 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13;
}
/// <summary>
/// Generates a random ISBN-13 value with a valid check digit.
/// </summary>
/// <returns>A valid ISBN-13 value of 13 digits.</returns>
private string CreateValidIsbn13()
{
string prefix = _faker.Random.Bool() ? "978" : "979";
string firstTwelveDigits = prefix + _faker.Random.String2(9, "0123456789");
int sum = 0;
for (int index = 0; index < 12; index++)
sum += index % 2 == 0 ? firstTwelveDigits[index] - '0' : 3 * (firstTwelveDigits[index] - '0');
int checkDigit = (10 - (sum % 10)) % 10;
return firstTwelveDigits + checkDigit;
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MediaContributors;
/// <summary>
/// Contains integration tests for the <see cref="MediaContributorRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorRepositoryTests
{
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
[Fact]
public async Task InsertAsync_WhenContributorWithSameDisplayNameInDifferentCaseExists_ShouldReturnError()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
MediaContributorRepository sut = new(context);
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King");
context.MediaContributors.Add(existingContributor);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
// The comparison is case-insensitive, matching the unique index on the display name.
Result<Created> result = await sut.InsertAsync(_mediaContributorEntityFixture.Create(displayName: "stephen king"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
@@ -47,7 +48,7 @@ public class LuminaDbContextTests : IDisposable
// Assert
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
Assert.Equal(46, tableNames.Length);
Assert.Equal(62, tableNames.Length);
Assert.Contains("Books", tableNames);
Assert.Contains("Users", tableNames);
Assert.Contains("UserSettings", tableNames);
@@ -69,6 +70,7 @@ public class LuminaDbContextTests : IDisposable
Assert.Contains("Tags", tableNames);
Assert.Contains("Genres", tableNames);
Assert.Contains("LibraryContentLocations", tableNames);
Assert.Contains("LibraryPathTemplateParts", tableNames);
Assert.Contains("BookTags", tableNames);
Assert.Contains("BookGenres", tableNames);
Assert.Contains("BookRatings", tableNames);
@@ -81,19 +83,31 @@ public class LuminaDbContextTests : IDisposable
Assert.Contains("ScheduledJobExecutions", tableNames);
Assert.Contains("SchedulerDisplayPreferences", tableNames);
Assert.Contains("Artists", tableNames);
Assert.Contains("ArtistAliases", tableNames);
Assert.Contains("ArtistIpis", tableNames);
Assert.Contains("ArtistIsnis", tableNames);
Assert.Contains("ArtistTags", tableNames);
Assert.Contains("ArtistGenres", tableNames);
Assert.Contains("ArtistRatings", tableNames);
Assert.Contains("Albums", tableNames);
Assert.Contains("Tracks", tableNames);
Assert.Contains("ArtistContributors", tableNames);
Assert.Contains("AlbumContributors", tableNames);
Assert.Contains("AlbumReleaseTypes", tableNames);
Assert.Contains("AlbumCatalogNumbers", tableNames);
Assert.Contains("AlbumGenres", tableNames);
Assert.Contains("AlbumRatings", tableNames);
Assert.Contains("AlbumTags", tableNames);
Assert.Contains("Tracks", tableNames);
Assert.Contains("TrackContributors", tableNames);
Assert.Contains("TrackGenres", tableNames);
Assert.Contains("TrackIsrcs", tableNames);
Assert.Contains("TrackMoods", tableNames);
Assert.Contains("TrackRatings", tableNames);
Assert.Contains("TrackTags", tableNames);
Assert.Contains("TrackWorkLanguages", tableNames);
Assert.Contains("TrackWorkIswcs", tableNames);
Assert.Contains("ArtistContributors", tableNames);
Assert.Contains("AlbumContributors", tableNames);
Assert.Contains("MusicArtwork", tableNames);
Assert.Contains("MusicLibraryScanItemMetadata", tableNames);
}
[Fact]
@@ -70,11 +70,11 @@ public class AlbumConfigurationTests : IDisposable
IProperty originalTitleProperty = entityType.GetProperty(nameof(AlbumEntity.OriginalTitle));
IProperty descriptionProperty = entityType.GetProperty(nameof(AlbumEntity.Description));
IProperty releaseCountryProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseCountry));
IProperty releaseTypeProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseType));
IProperty releaseTypeProperty = entityType.FindNavigation(nameof(AlbumEntity.ReleaseTypes))!.TargetEntityType.GetProperty(nameof(AlbumReleaseTypeEntity.ReleaseType));
IProperty releaseStatusProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseStatus));
IProperty mediaFormatProperty = entityType.GetProperty(nameof(AlbumEntity.MediaFormat));
IProperty barcodeProperty = entityType.GetProperty(nameof(AlbumEntity.Barcode));
IProperty catalogNumberProperty = entityType.GetProperty(nameof(AlbumEntity.CatalogNumber));
IProperty catalogNumberProperty = entityType.FindNavigation(nameof(AlbumEntity.CatalogNumbers))!.TargetEntityType.GetProperty(nameof(AlbumCatalogNumberEntity.CatalogNumber));
IProperty languageCodeProperty = entityType.GetProperty(nameof(AlbumEntity.LanguageCode));
// Assert
@@ -87,7 +87,7 @@ public class AlbumConfigurationTests : IDisposable
Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType);
Assert.Equal("TEXT", releaseCountryProperty.GetColumnType());
Assert.Equal(2, releaseCountryProperty.GetMaxLength());
Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType);
Assert.Equal(typeof(MusicReleaseType), releaseTypeProperty.ClrType);
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
Assert.Equal(typeof(MusicReleaseStatus?), releaseStatusProperty.ClrType);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryScanItemMetadataConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryScanItemMetadataConfigurationTests : IDisposable
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryScanItemMetadataConfigurationTests"/> class.
/// </summary>
public MusicLibraryScanItemMetadataConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("MusicLibraryScanItemMetadata", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldNotGenerateTheIdValue()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty idProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Id));
// Assert
Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRequiredScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty libraryScanIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId));
IProperty libraryIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryId));
IProperty pathProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Path));
// Assert
Assert.False(libraryScanIdProperty.IsNullable);
Assert.False(libraryIdProperty.IsNullable);
Assert.False(pathProperty.IsNullable);
Assert.Equal(2048, pathProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOptionalScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty artistNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ArtistName));
IProperty releaseTypeProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseType));
IProperty releaseYearProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseYear));
IProperty releaseNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseName));
IProperty trackTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.TrackTitle));
IProperty audioCodecProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AudioCodec));
IProperty workTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.WorkTitle));
IProperty acoustIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AcoustId));
// Assert
Assert.True(artistNameProperty.IsNullable);
Assert.Equal(255, artistNameProperty.GetMaxLength());
Assert.True(releaseTypeProperty.IsNullable);
Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType);
Assert.Equal("TEXT", releaseTypeProperty.GetColumnType());
Assert.Equal(50, releaseTypeProperty.GetMaxLength());
Assert.True(releaseYearProperty.IsNullable);
Assert.Equal(255, releaseNameProperty.GetMaxLength());
Assert.Equal(255, trackTitleProperty.GetMaxLength());
Assert.Equal(50, audioCodecProperty.GetMaxLength());
Assert.Equal(255, workTitleProperty.GetMaxLength());
Assert.Equal(64, acoustIdProperty.GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureReplayGainDecimalPrecision()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty trackGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackGain));
IProperty trackPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackPeak));
IProperty albumGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumGain));
IProperty albumPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumPeak));
// Assert
Assert.Equal("decimal(8,2)", trackGainProperty.GetColumnType());
Assert.Equal("decimal(8,6)", trackPeakProperty.GetColumnType());
Assert.Equal("decimal(8,2)", albumGainProperty.GetColumnType());
Assert.Equal("decimal(8,6)", albumPeakProperty.GetColumnType());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureMoodsAsPrimitiveCollection()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
IProperty moodsProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Moods));
// Assert
Assert.True(moodsProperty.IsPrimitiveCollection);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureUniqueScanIdPathIndex()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!;
// Act
List<IIndex> indexes = [.. entityType.GetIndexes()];
// Assert
IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique);
Assert.Equal(
[nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId), nameof(MusicLibraryScanItemMetadataEntity.Path)],
uniqueIndex.Properties.Select(property => property.Name));
}
/// <summary>
/// Disposes the database context.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
}
@@ -72,7 +72,7 @@ public class TrackConfigurationTests : IDisposable
IProperty scriptProperty = entityType.GetProperty(nameof(TrackEntity.Script));
IProperty keyProperty = entityType.GetProperty(nameof(TrackEntity.Key));
IProperty audioCodecProperty = entityType.GetProperty(nameof(TrackEntity.AudioCodec));
IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.Work));
IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.WorkTitle));
// Assert
Assert.False(pathProperty.IsNullable);
@@ -118,9 +118,11 @@ public class TrackConfigurationTests : IDisposable
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
// Assert
Assert.Equal(3, ownedTypes.Count);
Assert.Equal(5, ownedTypes.Count);
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackMoodEntity) && ownedType.GetTableName() == "TrackMoods");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackIsrcEntity) && ownedType.GetTableName() == "TrackIsrcs");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkLanguageEntity) && ownedType.GetTableName() == "TrackWorkLanguages");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkIswcEntity) && ownedType.GetTableName() == "TrackWorkIswcs");
Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(AudioRatingEntity) && ownedType.GetTableName() == "TrackRatings");
}
@@ -314,6 +314,74 @@ public class BookRepositoryTests
Assert.Null(result.Value);
}
[Fact]
public async Task GetExistingPathsAsync_WhenPathsIsEmpty_ShouldReturnAnEmptyCollection()
{
// Arrange
IReadOnlyCollection<string> paths = [];
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(Guid.NewGuid(), paths, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetExistingPathsAsync_WhenCalled_ShouldReturnOnlyThePathsUsedByBooksOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/tolkien/the-hobbit.epub");
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/books/tolkien/the-lord-of-the-rings.epub");
_mockContext.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub", "/books/tolkien/the-lord-of-the-rings.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
string existingPath = Assert.Single(result.Value);
Assert.Equal("/books/tolkien/the-hobbit.epub", existingPath);
}
[Fact]
public async Task GetExistingPathsAsync_WhenInputContainsDuplicatePaths_ShouldDeDuplicateTheResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/tolkien/the-hobbit.epub");
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub", "/books/tolkien/the-hobbit.epub", "/books/tolkien/the-hobbit.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal("/books/tolkien/the-hobbit.epub", result.Value.First());
}
[Fact]
public async Task GetExistingPathsAsync_WhenPathDiffersOnlyByCase_ShouldNotReportItAsExisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: "/Books/Tolkien/The-Hobbit.epub");
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetBooksNeedingMetadataAsync_WhenCalled_ShouldReturnOnlyBooksWhoseMetadataIsNotEnriched()
{
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
@@ -91,6 +92,42 @@ public class MediaContributorRepositoryTests
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
}
[Fact]
public async Task FindOrCreateByDisplayNameAsync_WhenExistingNameStartsWithNonAsciiUppercase_ShouldReturnTheExistingContributor()
{
// Arrange
// The storage medium folds only ASCII case, so a name starting with a non-ASCII uppercase letter would previously not be found by the lookup
// and would be inserted again, violating the unique index on the display name.
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Лев Ошанин");
_mockContext.MediaContributors.Add(existingContributor);
await _mockContext.SaveChangesAsync();
// Act
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("Лев Ошанин", null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(existingContributor.Id, result.Value.Id);
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
}
[Fact]
public async Task FindOrCreateByDisplayNameAsync_WhenContributorWasAddedButNotSaved_ShouldReturnTheTrackedContributor()
{
// Arrange
Result<MediaContributorEntity> firstResult = await _sut.FindOrCreateByDisplayNameAsync("Bob Ludwig", null, CancellationToken.None);
Assert.False(firstResult.IsFailure);
// Act
Result<MediaContributorEntity> secondResult = await _sut.FindOrCreateByDisplayNameAsync("BOB LUDWIG", null, CancellationToken.None);
// Assert
Assert.False(secondResult.IsFailure);
// The contributor added earlier in the same unit of work is tracked, so it is returned instead of a duplicate being added.
Assert.Equal(firstResult.Value.Id, secondResult.Value.Id);
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>(), entityEntry => entityEntry.State == EntityState.Added);
}
[Fact]
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheContributorsWithTheProvidedIds()
{
@@ -128,4 +165,21 @@ public class MediaContributorRepositoryTests
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == contributor.Id);
Assert.NotNull(addedContributor);
}
[Fact]
public async Task InsertAsync_WhenContributorWithSameIdAlreadyExists_ShouldReturnError()
{
// Arrange
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create();
_mockContext.MediaContributors.Add(existingContributor);
await _mockContext.SaveChangesAsync();
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(id: existingContributor.Id);
// Act
Result<Created> result = await _sut.InsertAsync(contributor, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError);
}
}
@@ -14,6 +14,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using NSubstitute;
@@ -499,6 +500,32 @@ public class AlbumRepositoryTests
Assert.Single(_mockContext.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre"));
}
[Fact]
public async Task UpdateAsync_WhenCatalogNumbersChange_ShouldAddTheNewAndRemoveTheMissingOnes()
{
// Arrange
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "OC 062 o 94519"]);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "EMTC 104"]);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
AlbumEntity? retrievedAlbum = await _mockContext.Albums
.Include(album => album.CatalogNumbers)
.FirstOrDefaultAsync(album => album.Id == storedAlbum.Id);
Assert.NotNull(retrievedAlbum);
Assert.Equal(2, retrievedAlbum!.CatalogNumbers.Count);
Assert.Contains(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "EMC 3006");
Assert.Contains(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "EMTC 104");
Assert.DoesNotContain(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "OC 062 o 94519");
}
[Fact]
public async Task GetByIdAsync_WhenAlbumExists_ShouldReturnTheAlbum()
{
@@ -714,6 +741,26 @@ public class AlbumRepositoryTests
Assert.Equal(12, row.TotalTracks);
}
[Fact]
public async Task GetAlbumsNeedingMetadataCountAsync_WhenAlbumsHaveMixedMetadataStatuses_ShouldCountOnlyTheNotEnrichedOnesOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity pendingAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
AlbumEntity failedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Failed);
AlbumEntity enrichedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Enriched);
AlbumEntity albumOfAnotherLibrary = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
_mockContext.Albums.AddRange(pendingAlbum, failedAlbum, enrichedAlbum, albumOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetAlbumsNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value);
}
/// <summary>
/// Creates an album that belongs to the artist identified by <paramref name="artistId"/>, with every related collection populated deterministically.
/// </summary>
@@ -16,6 +16,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -1118,6 +1119,104 @@ public class ArtistRepositoryTests
Assert.Equal(expectedRowCount, page.Data.Count);
}
[Fact]
public async Task GetArtistsNeedingMetadataAsync_WhenAnArtistAndAllItsDescendantsAreEnriched_ShouldNotReturnIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity enriched = CreateArtistWithFullAggregate();
enriched.LibraryId = libraryId;
MarkEnriched(enriched);
ArtistEntity pending = _artistEntityFixture.Create(libraryId: libraryId, name: "Pending Artist", includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(enriched, pending);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistEntity onlyArtist = Assert.Single(result.Value);
Assert.Equal(pending.Id, onlyArtist.Id);
}
[Fact]
public async Task GetArtistsNeedingMetadataAsync_WhenATrackIsNotEnriched_ShouldReturnTheArtist()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = CreateArtistWithFullAggregate();
artist.LibraryId = libraryId;
MarkEnriched(artist);
artist.Albums[0].Tracks[0].MetadataStatus = MetadataStatus.Pending;
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistEntity onlyArtist = Assert.Single(result.Value);
Assert.Equal(artist.Id, onlyArtist.Id);
}
[Fact]
public async Task GetArtistsNeedingMetadataAsync_WhenLastNameIsProvided_ShouldReturnOnlyArtistsAfterIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity alpha = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false);
ArtistEntity beta = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false);
ArtistEntity gamma = _artistEntityFixture.Create(libraryId: libraryId, name: "Gamma", includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(alpha, beta, gamma);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, "Beta", 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistEntity onlyArtist = Assert.Single(result.Value);
Assert.Equal(gamma.Id, onlyArtist.Id);
}
[Fact]
public async Task GetArtistsNeedingMetadataCountAsync_ShouldCountArtistsWithPendingMetadataIncludingDescendants()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity enriched = CreateArtistWithFullAggregate();
enriched.LibraryId = libraryId;
MarkEnriched(enriched);
ArtistEntity pending = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
ArtistEntity otherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(enriched, pending, otherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetArtistsNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
/// <summary>
/// Marks the provided artist, its albums and its tracks as enriched.
/// </summary>
/// <param name="artist">The artist whose metadata enrichment status is set.</param>
private static void MarkEnriched(ArtistEntity artist)
{
artist.MetadataStatus = MetadataStatus.Enriched;
foreach (AlbumEntity album in artist.Albums)
{
album.MetadataStatus = MetadataStatus.Enriched;
foreach (TrackEntity track in album.Tracks)
track.MetadataStatus = MetadataStatus.Enriched;
}
}
/// <summary>
/// Creates an artist that owns an album which in turn owns a track, with every related collection of the aggregate populated deterministically.
/// </summary>
@@ -0,0 +1,130 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryScanItemMetadataRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryScanItemMetadataRepositoryTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly MusicLibraryScanItemMetadataRepository _sut;
private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryScanItemMetadataRepositoryTests"/> class.
/// </summary>
public MusicLibraryScanItemMetadataRepositoryTests()
{
// the repository deletes in bulk, which translates to SQL, so it can only be exercised against a real SQLite database
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
_sut = new MusicLibraryScanItemMetadataRepository(_context);
}
[Fact]
public async Task InsertRangeAsync_WhenCalledWithItems_ShouldAddThemToContextAndReturnCreated()
{
// Arrange
List<MusicLibraryScanItemMetadataEntity> items = _musicLibraryScanItemMetadataEntityFixture.CreateMany(3);
// Act
Result<Created> result = await _sut.InsertRangeAsync(items, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Equal(3, await _context.MusicLibraryScanItemMetadata.CountAsync());
}
[Fact]
public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutAddingAnyItems()
{
// Act
Result<Created> result = await _sut.InsertRangeAsync([], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await _context.SaveChangesAsync();
Assert.Empty(await _context.MusicLibraryScanItemMetadata.ToListAsync());
}
[Fact]
public async Task GetByScanIdAsync_WhenCalled_ShouldReturnOnlyTheItemsOfTheScanOrderedByPath()
{
// Arrange
Guid scanId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity bicycleItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bicycle-race.flac");
MusicLibraryScanItemMetadataEntity bohemianItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/dont-stop-me-now.flac");
_context.MusicLibraryScanItemMetadata.AddRange(bicycleItem, bohemianItem, itemOfAnotherScan);
await _context.SaveChangesAsync();
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByScanIdAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([bicycleItem.Id, bohemianItem.Id], result.Value.Select(item => item.Id));
}
[Fact]
public async Task GetByScanIdAsync_WhenNoItemsExistForTheScan_ShouldReturnAnEmptyCollection()
{
// Act
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> result = await _sut.GetByScanIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByScanIdAsync_WhenCalled_ShouldDeleteOnlyTheItemsOfTheScan()
{
// Arrange
Guid scanId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity itemOfScan = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac");
MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/love-of-my-life.flac");
_context.MusicLibraryScanItemMetadata.AddRange(itemOfScan, itemOfAnotherScan);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByScanIdAsync(scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
MusicLibraryScanItemMetadataEntity remainingItem = Assert.Single(await _context.MusicLibraryScanItemMetadata.ToListAsync());
Assert.Equal(itemOfAnotherScan.Id, remainingItem.Id);
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -13,6 +13,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -792,4 +793,24 @@ public class TrackRepositoryTests
Assert.Equal(9, row.TrackNumber);
Assert.Equal(3, row.DiscNumber);
}
[Fact]
public async Task GetTracksNeedingMetadataCountAsync_WhenTracksHaveMixedMetadataStatuses_ShouldCountOnlyTheNotEnrichedOnesOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
TrackEntity pendingTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
TrackEntity failedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Failed);
TrackEntity enrichedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Enriched);
TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(includeMetadata: false, metadataStatus: MetadataStatus.Pending);
_mockContext.Tracks.AddRange(pendingTrack, failedTrack, enrichedTrack, trackOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetTracksNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value);
}
}