diff --git a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs
index 6b77d3dc..c13e4250 100644
--- a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs
+++ b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs
@@ -25,5 +25,5 @@ public record LibraryFilterDto : BaseFilterDto
///
/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
///
- public bool IgnoreThePrefixForAlphaPicker { get; init; }
+ public bool ShouldIgnoreThePrefixForAlphaPicker { get; init; }
}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs
index ef17ab05..a7c07954 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs
@@ -63,7 +63,7 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
///
/// Gets whether this media library should update the metadata of its elements from the web, or not.
///
- public bool DownloadMetadataFromWeb { get; init; }
+ public bool CanDownloadMetadataFromWeb { get; init; }
///
/// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not.
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs
index 524544bb..5e8de0bf 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs
@@ -35,13 +35,18 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
///
/// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
///
- public bool IgnoreThePrefixForAlphaPicker { get; set; }
+ public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; }
///
/// Gets or sets whether the theme data served to this user is cached, or not.
///
public bool IsThemeCachingEnabled { get; set; } = true;
+ ///
+ /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
+ ///
+ public bool ShouldAggregateMetadataWhenMissing { get; set; }
+
///
/// Gets or sets the time and date when the entity was added.
///
diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
index dc49b1f4..17a48b83 100644
--- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
+++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
@@ -71,6 +71,11 @@ public interface IUnitOfWork
///
ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; }
+ ///
+ /// Gets the library artwork provider configuration repository.
+ ///
+ IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; }
+
///
/// Gets the plugin repository.
///
@@ -97,6 +102,11 @@ public interface IUnitOfWork
/// Cancellation token that can be used to stop the execution.
Task SaveChangesAsync(CancellationToken cancellationToken);
+ ///
+ /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
+ ///
+ void ClearTrackedEntities();
+
///
/// Begins a new database transaction.
///
diff --git a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs
index f68feee4..c77c25f4 100644
--- a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs
+++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs
@@ -21,4 +21,9 @@ public class MediaSettingsDto
/// Gets or sets the directory where media library files are stored.
///
public required string LibrariesDirectory { get; init; }
+
+ ///
+ /// Gets or sets the directory where the media item files are stored.
+ ///
+ public required string BooksDirectory { get; init; }
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs
index 8e74f24c..f524961e 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs
@@ -1,9 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
-using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Requests.MediaLibrary.Management;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
@@ -27,7 +24,7 @@ public static class AddMediaLibraryRequestMapping
request.CoverImage,
request.IsEnabled,
request.IsLocked,
- request.DownloadMetadataFromWeb,
+ request.CanDownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan
);
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
index 1484cf34..fe652e54 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
@@ -29,11 +29,11 @@ public static class LibraryEntityMapping
repositoryEntity.UserId,
repositoryEntity.Title,
repositoryEntity.LibraryType,
- repositoryEntity.ContentLocations.Select(location => location.Path).ToList(),
+ [.. repositoryEntity.ContentLocations.Select(location => location.Path)],
repositoryEntity.CoverImage,
repositoryEntity.IsEnabled,
repositoryEntity.IsLocked,
- repositoryEntity.DownloadMetadataFromWeb,
+ repositoryEntity.CanDownloadMetadataFromWeb,
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
repositoryEntity.CreatedOnUtc,
@@ -59,10 +59,10 @@ public static class LibraryEntityMapping
repositoryEntity.CoverImage,
repositoryEntity.IsEnabled,
repositoryEntity.IsLocked,
- repositoryEntity.DownloadMetadataFromWeb,
+ repositoryEntity.CanDownloadMetadataFromWeb,
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
- repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
+ [.. repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
);
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
index dac14f8a..90f36343 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
@@ -25,14 +25,14 @@ public static class LibraryMapping
Title = domainEntity.Title,
LibraryType = domainEntity.LibraryType,
UserId = domainEntity.UserId.Value,
- ContentLocations = domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path }).ToList(),
+ ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })],
CoverImage = domainEntity.CoverImage,
IsEnabled = domainEntity.IsEnabled,
IsLocked = domainEntity.IsLocked,
- DownloadMetadataFromWeb = domainEntity.DownloadMetadataFromWeb,
+ CanDownloadMetadataFromWeb = domainEntity.CanDownloadMetadataFromWeb,
ShouldSaveMetadataInMediaDirectories = domainEntity.ShouldSaveMetadataInMediaDirectories,
ShouldSkipUnchangedDirectoriesDuringScan = domainEntity.ShouldSkipUnchangedDirectoriesDuringScan,
- LibraryScans = domainEntity.ScanIds.Select(scanId => new LibraryScanEntity()
+ LibraryScans = [.. domainEntity.ScanIds.Select(scanId => new LibraryScanEntity()
{
Id = scanId.Value,
LibraryId = domainEntity.Id.Value,
@@ -43,7 +43,7 @@ public static class LibraryMapping
CreatedBy = default,
CreatedOnUtc = default,
UpdatedBy = default,
- }).ToList(),
+ })],
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs
index c0dfc446..374f9e15 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Requests.MediaLibrary.Management;
-using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
@@ -27,7 +26,7 @@ public static class UpdateLibraryRequestMapping
request.CoverImage,
request.IsEnabled,
request.IsLocked,
- request.DownloadMetadataFromWeb,
+ request.CanDownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan
);
diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs
index 23504a3c..aff25a7d 100644
--- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs
@@ -20,7 +20,9 @@ public static class UpdateUserSettingsRequestMapping
return new UpdateUserSettingsCommand(
request.IsPaginationEnabled,
request.ItemsPerPage,
- request.IgnoreThePrefixForAlphaPicker,
- request.IsThemeCachingEnabled);
+ request.ShouldIgnoreThePrefixForAlphaPicker,
+ request.IsThemeCachingEnabled,
+ request.ShouldAggregateMetadataWhenMissing
+ );
}
}
diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs
index b96f8fdb..b53990fd 100644
--- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement.Settings;
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects;
@@ -28,8 +28,10 @@ public static class UserSettingsEntityMapping
UserId.Create(repositoryEntity.UserId),
repositoryEntity.IsPaginationEnabled,
repositoryEntity.ItemsPerPage,
- repositoryEntity.IgnoreThePrefixForAlphaPicker,
- repositoryEntity.IsThemeCachingEnabled);
+ repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
+ repositoryEntity.IsThemeCachingEnabled,
+ repositoryEntity.ShouldAggregateMetadataWhenMissing
+ );
}
///
@@ -43,7 +45,9 @@ public static class UserSettingsEntityMapping
repositoryEntity.UserId,
repositoryEntity.IsPaginationEnabled,
repositoryEntity.ItemsPerPage,
- repositoryEntity.IgnoreThePrefixForAlphaPicker,
- repositoryEntity.IsThemeCachingEnabled);
+ repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
+ repositoryEntity.IsThemeCachingEnabled,
+ repositoryEntity.ShouldAggregateMetadataWhenMissing
+ );
}
}
diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs
index 7a22ee1e..cde37e56 100644
--- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs
@@ -24,8 +24,9 @@ public static class UserSettingsMapping
UserId = domainEntity.UserId.Value,
IsPaginationEnabled = domainEntity.IsPaginationEnabled,
ItemsPerPage = domainEntity.ItemsPerPage,
- IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker,
- IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled
+ ShouldIgnoreThePrefixForAlphaPicker = domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
+ IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled,
+ ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing
};
}
@@ -40,7 +41,9 @@ public static class UserSettingsMapping
domainEntity.UserId.Value,
domainEntity.IsPaginationEnabled,
domainEntity.ItemsPerPage,
- domainEntity.IgnoreThePrefixForAlphaPicker,
- domainEntity.IsThemeCachingEnabled);
+ domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
+ domainEntity.IsThemeCachingEnabled,
+ domainEntity.ShouldAggregateMetadataWhenMissing
+ );
}
}
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs
index a9345eca..995a3ee6 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
-using System;
using System.Diagnostics;
#endregion
@@ -15,7 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
/// The path of the image file used as the cover for the library.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.
-/// Whether this media library should update the metadata of its elements from the web, or not.
+/// Whether this media library should update the metadata of its elements from the web, or not.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.
[DebuggerDisplay("Title: {Title}")]
@@ -26,7 +25,7 @@ public record AddLibraryCommand(
string? CoverImage,
bool IsEnabled,
bool IsLocked,
- bool DownloadMetadataFromWeb,
+ bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs
index 320cd84f..c4ad4181 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -10,14 +8,15 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
-using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -113,7 +112,7 @@ public class AddLibraryCommandHandler : ICommandHandlerThe path of the image file used as the cover for the library.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.
-/// Whether this media library should update the metadata of its elements from the web, or not.
+/// Whether this media library should update the metadata of its elements from the web, or not.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.
[DebuggerDisplay("Title: {Title}")]
@@ -30,7 +30,7 @@ public record UpdateLibraryCommand(
string? CoverImage,
bool IsEnabled,
bool IsLocked,
- bool DownloadMetadataFromWeb,
+ bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs
index 1e13108a..8a210168 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -11,16 +9,17 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
-using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -127,10 +126,10 @@ public class UpdateLibraryCommandHandler : ICommandHandler ScanId.Create(libraryScan.Id)).ToList()
+ [.. getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
);
if (createLibraryResult.IsFailure)
return createLibraryResult.Errors;
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs
index 301727f5..d77ae07f 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs
@@ -60,7 +60,7 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler startScanResult = await _mediaLibraryScanningService.StartScanAsync(
- libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMetadataFromWeb, cancellationToken).ConfigureAwait(false);
+ libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false);
if (startScanResult.IsFailure)
throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors);
diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs
index b04e7a35..8fc10e5b 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs
@@ -1,15 +1,18 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
@@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide
public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler>
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
/// Injected validator for application validation rules.
- public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork, IValidator validator)
+ public ReorderLibraryMetadataProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -47,6 +56,18 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler 0)
return validationResult;
+ // an authenticated request must always carry a user identity
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // admins can reorder the metadata providers of any library; for everyone else, only their own libraries
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs
index 1a9fd05c..95c01884 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs
@@ -2,6 +2,7 @@
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
+using System;
#endregion
namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
@@ -18,6 +19,8 @@ public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator
{
RuleFor(command => command.LibraryId)
.NotEmpty()
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
RuleFor(command => command.PluginIds)
diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs
index d3d8eee5..21e21978 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs
@@ -1,15 +1,18 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
@@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEna
public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler>
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
/// Injected validator for application validation rules.
- public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork, IValidator validator)
+ public SetLibraryMetadataProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -47,6 +56,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler 0)
return validationResult;
+ // an authenticated request must always carry a user identity
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // admins can configure the metadata providers of any library; for everyone else, only their own libraries
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
if (getConfigurationResult.IsFailure)
return getConfigurationResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs
index f631bc44..b910702f 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs
@@ -2,6 +2,7 @@
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
+using System;
#endregion
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
@@ -18,10 +19,14 @@ public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidat
{
RuleFor(command => command.LibraryId)
.NotEmpty()
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
RuleFor(command => command.PluginId)
.NotEmpty()
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
.WithError(Errors.Plugins.PluginIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs
index 283e4bf5..c100995f 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs
@@ -2,6 +2,7 @@
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
+using System;
#endregion
namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings;
@@ -18,6 +19,8 @@ public class UpdatePluginSettingsCommandValidator : AbstractValidator command.PluginId)
.NotEmpty()
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
.WithError(Errors.Plugins.PluginIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs
index 6ed087fe..391cf371 100644
--- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs
@@ -1,16 +1,20 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Contracts.Responses.Plugins;
+using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
@@ -21,14 +25,23 @@ namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler>>
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public GetLibraryMetadataProvidersQueryHandler(IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
_unitOfWork = unitOfWork;
+ _validator = validator;
}
///
@@ -41,6 +54,22 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler
public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(query);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // an authenticated request must always carry a user identity
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // admins can read the metadata providers of any library; for everyone else, only their own libraries
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs
new file mode 100644
index 00000000..931c1ae3
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
+
+///
+/// Validates the needed validation rules for .
+///
+public class GetLibraryMetadataProvidersQueryValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetLibraryMetadataProvidersQueryValidator()
+ {
+ RuleFor(query => query.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
index 5e26b31d..28a8eae3 100644
--- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
@@ -1,13 +1,13 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
using Lumina.Plugins.Contracts.Core.Plugins;
using System.Collections.Generic;
using System.Linq;
@@ -24,16 +24,19 @@ public class GetPluginSettingsQueryHandler : IQueryHandler _validator;
///
/// Initializes a new instance of the class.
///
/// Injected unit of work for interacting with the data access layer repositories.
/// Injected manager of the plugins loaded by the host application.
- public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager)
+ /// Injected validator for application validation rules.
+ public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager, IValidator validator)
{
_unitOfWork = unitOfWork;
_pluginManager = pluginManager;
+ _validator = validator;
}
///
@@ -46,6 +49,10 @@ public class GetPluginSettingsQueryHandler : IQueryHandler
public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(query);
+ if (validationResult.Count > 0)
+ return validationResult;
+
Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsFailure)
return getPluginResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs
new file mode 100644
index 00000000..2a94c3b5
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
+
+///
+/// Validates the needed validation rules for .
+///
+public class GetPluginSettingsQueryValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetPluginSettingsQueryValidator()
+ {
+ RuleFor(query => query.PluginId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs
index 0e798ccc..e29088bf 100644
--- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs
+++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs
@@ -9,11 +9,13 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
///
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
-/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
public record UpdateUserSettingsCommand(
bool IsPaginationEnabled,
int ItemsPerPage,
- bool IgnoreThePrefixForAlphaPicker,
- bool IsThemeCachingEnabled
+ bool ShouldIgnoreThePrefixForAlphaPicker,
+ bool IsThemeCachingEnabled,
+ bool ShouldAggregateMetadataWhenMissing
) : ICommand;
diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs
index 3028518b..9af3a222 100644
--- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs
+++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs
@@ -1,13 +1,12 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
-using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.UsersManagement.Users;
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
using System;
@@ -72,8 +71,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler updateSettingsResult = toDomainEntityResult.Value.UpdateSettings(
command.IsPaginationEnabled,
command.ItemsPerPage,
- command.IgnoreThePrefixForAlphaPicker,
- command.IsThemeCachingEnabled);
+ command.ShouldIgnoreThePrefixForAlphaPicker,
+ command.IsThemeCachingEnabled,
+ command.ShouldAggregateMetadataWhenMissing);
if (updateSettingsResult.IsFailure)
return updateSettingsResult.Errors;
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs
index bfc717ba..df43eb8d 100644
--- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs
@@ -13,7 +13,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// The path of the image file used as the cover for the library. Optional.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.
-/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
+/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.
[DebuggerDisplay("Title: {Title}")]
@@ -24,7 +24,7 @@ public record AddLibraryRequest(
string? CoverImage,
bool IsEnabled,
bool IsLocked,
- bool DownloadMetadataFromWeb,
+ bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
);
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs
index ad62394a..9590f10a 100644
--- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
-using System.Runtime.InteropServices;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.Management;
@@ -18,7 +16,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// The path of the image file used as the cover for the library. Optional.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.
-/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
+/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.
[DebuggerDisplay("Title: {Title}")]
@@ -31,7 +29,7 @@ public record class UpdateLibraryRequest(
string? CoverImage,
bool IsEnabled,
bool IsLocked,
- bool DownloadMetadataFromWeb,
+ bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
);
diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs
index 2b0ad237..b37216ac 100644
--- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs
+++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs
@@ -9,12 +9,14 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings;
///
/// Whether pagination is enabled for the user, or not. Required.
/// The number of library items displayed per page when pagination is enabled. Required.
-/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.
+/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.
/// Whether the theme data served to this user is cached, or not. Required.
+/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required.
[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")]
public sealed record UpdateUserSettingsRequest(
bool IsPaginationEnabled,
int ItemsPerPage,
- bool IgnoreThePrefixForAlphaPicker,
- bool IsThemeCachingEnabled
+ bool ShouldIgnoreThePrefixForAlphaPicker,
+ bool IsThemeCachingEnabled,
+ bool ShouldAggregateMetadataWhenMissing
);
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs
index 9ec7de01..9dff6ddc 100644
--- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs
@@ -16,6 +16,11 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management;
/// The type of the media library.
/// The file system paths of the directories where the media library elements are located.
/// The path of the image file used as the cover for the library.
+/// Whether the media library is enabled or not. A disabled media library is never shown or changed.
+/// Whether the media library is locked or not. A locked media library is displayed, but is never changed or updated.
+/// Whether the media library should update the metadata of its elements from the web, or not.
+/// Whether the media library should copy the downloaded metadata into the media library content locations, or not.
+/// Whether the media library should skip the directories whose contents have not changed since the last scan, during the scan.
/// The date and time when the library was created.
/// The optional date and time when the library was updated.
[DebuggerDisplay("Title: {Title}")]
@@ -28,7 +33,7 @@ public record LibraryResponse(
string? CoverImage,
bool IsEnabled,
bool IsLocked,
- bool DownloadMetadataFromWeb,
+ bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan,
DateTime CreatedOnUtc,
diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs
index 3c362b34..3f5c59e3 100644
--- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs
+++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs
@@ -11,13 +11,15 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings;
/// The unique identifier of the user that owns these settings.
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
-/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
[DebuggerDisplay("UserId: {UserId}")]
public sealed record UserSettingsResponse(
Guid UserId,
bool IsPaginationEnabled,
int ItemsPerPage,
- bool IgnoreThePrefixForAlphaPicker,
- bool IsThemeCachingEnabled
+ bool ShouldIgnoreThePrefixForAlphaPicker,
+ bool IsThemeCachingEnabled,
+ bool ShouldAggregateMetadataWhenMissing
);
diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs
index 6e085ae3..8c27891a 100644
--- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs
+++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs
@@ -46,7 +46,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration
builder.Property(library => library.IsLocked)
.HasColumnOrder(5);
- builder.Property(library => library.DownloadMetadataFromWeb)
+ builder.Property(library => library.CanDownloadMetadataFromWeb)
.HasDefaultValue(true)
.HasColumnOrder(6);
diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs
index ca160a72..84a4f221 100644
--- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs
+++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs
@@ -2,7 +2,6 @@
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
-using System;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
@@ -43,10 +42,14 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.IgnoreThePrefixForAlphaPicker)
+ builder.Property(settings => settings.ShouldIgnoreThePrefixForAlphaPicker)
.IsRequired()
.HasColumnOrder(4);
+ builder.Property(settings => settings.ShouldAggregateMetadataWhenMissing)
+ .IsRequired()
+ .HasColumnOrder(10);
+
builder.Property(settings => settings.IsThemeCachingEnabled)
.IsRequired()
.HasColumnOrder(9);
diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs
index e2927044..1d369cef 100644
--- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs
+++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs
@@ -132,7 +132,7 @@ internal sealed class BookRepository : IBookRepository
booksQuery = booksQuery.Where(filterSpecification.ToExpression());
// apply sorting based on the specified sortBy and sortOrder parameters
- booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.IgnoreThePrefixForAlphaPicker);
+ booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
// if no pagination was requested, return all the books of the library
if (paginationData is null)
@@ -261,8 +261,8 @@ internal sealed class BookRepository : IBookRepository
/// The query to sort.
/// The field to sort by (case-insensitive).
/// The direction of the sorting.
- /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.
- private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool ignoreThePrefixForAlphaPicker)
+ /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.
+ private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker)
{
return sortBy?.ToLower() switch
{
@@ -276,8 +276,8 @@ internal sealed class BookRepository : IBookRepository
? booksQuery.OrderByDescending(book => book.MetadataProvider)
: booksQuery.OrderBy(book => book.MetadataProvider),
_ => sortOrder == SortOrder.Descending
- ? booksQuery.OrderByDescending(BuildTitleSortKey(ignoreThePrefixForAlphaPicker))
- : booksQuery.OrderBy(BuildTitleSortKey(ignoreThePrefixForAlphaPicker)),
+ ? booksQuery.OrderByDescending(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker))
+ : booksQuery.OrderBy(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker)),
};
}
@@ -286,9 +286,9 @@ internal sealed class BookRepository : IBookRepository
/// the title lowercased, falling back to the original title when the title is or empty, and optionally
/// stripped of a leading "the " prefix.
///
- /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.
+ /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.
/// An expression that evaluates to the title sort key of a book.
- private static Expression> BuildTitleSortKey(bool ignoreThePrefixForAlphaPicker)
+ private static Expression> BuildTitleSortKey(bool shouldIgnoreThePrefixForAlphaPicker)
{
ParameterExpression book = Expression.Parameter(typeof(BookEntity), "book");
@@ -306,7 +306,7 @@ internal sealed class BookRepository : IBookRepository
// when ignoring the "The " prefix, strip a leading "the " from the lowercased title
Expression effectiveTitle = lowerTitle;
- if (ignoreThePrefixForAlphaPicker)
+ if (shouldIgnoreThePrefixForAlphaPicker)
{
MethodCallExpression startsWithThe = Expression.Call(lowerTitle, s_startsWithMethod, Expression.Constant("the "));
MethodCallExpression strippedTitle = Expression.Call(lowerTitle, s_substringMethod, Expression.Constant(4));
@@ -332,7 +332,7 @@ internal sealed class BookRepository : IBookRepository
// include the alpha key filter, if provided
if (libraryFilter.FilterAlphaKey is not null)
{
- BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.IgnoreThePrefixForAlphaPicker);
+ BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
filterSpecification = filterSpecification is null
? alphaFilterSpecification
: filterSpecification.And(alphaFilterSpecification);
diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs
index 460726ec..39731c29 100644
--- a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs
+++ b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs
@@ -23,17 +23,17 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification
/// Initializes a new instance of the class.
///
/// The alpha key to filter by. A single ASCII letter, , or .
- /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
- public BookAlphaFilterSpecification(string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker)
+ /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
+ public BookAlphaFilterSpecification(string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker)
{
_filterAlphaKey = filterAlphaKey;
- _ignoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
+ _shouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
}
///
@@ -82,7 +82,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification RolePermissions { get; set; } = null!;
public virtual DbSet Plugins { get; set; } = null!;
public virtual DbSet LibraryMetadataProviderConfigurations { get; set; } = null!;
+ public virtual DbSet LibraryArtworkProviderConfigurations { get; set; } = null!;
public virtual DbSet Themes { get; set; } = null!;
///
diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs
index 0a23313a..96cc1296 100644
--- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs
+++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs
@@ -39,6 +39,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private ILibraryScanSnapshotRepository? _libraryScanSnapshotRepository;
private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository;
private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository;
+ private IArtworkProviderConfigurationRepository? _artworkProviderConfigurationRepository;
private IPluginRepository? _pluginRepository;
private IThemeRepository? _themeRepository;
private IUserRepository? _userRepository;
@@ -176,6 +177,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
+ ///
+ /// Gets the library artwork provider configuration repository.
+ ///
+ public IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository
+ {
+ get
+ {
+ _artworkProviderConfigurationRepository ??= new ArtworkProviderConfigurationRepository(_luminaDbContext);
+ return _artworkProviderConfigurationRepository;
+ }
+ }
+
///
/// Gets the plugin repository.
///
@@ -242,6 +255,14 @@ public class UnitOfWork : IUnitOfWork, IDisposable
await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
+ ///
+ /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
+ ///
+ public void ClearTrackedEntities()
+ {
+ _luminaDbContext.ChangeTracker.Clear();
+ }
+
///
/// Begins a new database transaction.
///
diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs
index 24249be1..c4eeea2d 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
-using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
#endregion
@@ -38,23 +37,41 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService
if (rootPathIdResult.IsFailure)
return rootPathIdResult.Errors;
- // create the libraries directory
- Result librariesPathResult = _pathService.CombinePath(rootPath, "libraries");
- if (librariesPathResult.IsFailure)
- return librariesPathResult.Errors;
+ Result createLibrariesDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "libraries");
+ if (createLibrariesDirectoryResult.IsFailure)
+ return createLibrariesDirectoryResult.Errors;
- Result libraryPathIdResult = FileSystemPathId.Create(librariesPathResult.Value);
- if (libraryPathIdResult.IsFailure)
- return libraryPathIdResult.Errors;
+ Result createBooksDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "books");
+ if (createBooksDirectoryResult.IsFailure)
+ return createBooksDirectoryResult.Errors;
- Result librariesDirectoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value);
- if (librariesDirectoryExistsResult.IsFailure)
- return librariesDirectoryExistsResult.Errors;
+ return Result.Created;
+ }
+
+ ///
+ /// Creates the directory with the provided under the , when it does not already exist.
+ ///
+ /// The id of the root path under which the directory is created.
+ /// The name of the directory to create.
+ /// An representing either a successful operation, or an error.
+ private Result EnsureDirectory(FileSystemPathId rootPathId, string directoryName)
+ {
+ Result directoryPathResult = _pathService.CombinePath(rootPathId.Path, directoryName);
+ if (directoryPathResult.IsFailure)
+ return directoryPathResult.Errors;
+
+ Result directoryPathIdResult = FileSystemPathId.Create(directoryPathResult.Value);
+ if (directoryPathIdResult.IsFailure)
+ return directoryPathIdResult.Errors;
+
+ Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value);
+ if (directoryExistsResult.IsFailure)
+ return directoryExistsResult.Errors;
// only create it if it doesn't already exist
- if (!librariesDirectoryExistsResult.Value)
+ if (!directoryExistsResult.Value)
{
- Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathIdResult.Value, "libraries");
+ Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathId, directoryName);
if (createDirectoryResult.IsFailure)
return createDirectoryResult.Errors;
}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs
index 445d175c..c49151d9 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs
@@ -63,7 +63,7 @@ public class Library : AggregateRoot
///
/// Gets whether this media library should update the metadata of its elements from the web, or not.
///
- public bool DownloadMetadataFromWeb { get; private set; } = true;
+ public bool CanDownloadMetadataFromWeb { get; private set; } = true;
///
/// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not.
@@ -97,7 +97,7 @@ public class Library : AggregateRoot
/// The path of the image file used as the cover for the library.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.
- /// Whether this media library should update the metadata of its elements from the web, or not.
+ /// Whether this media library should update the metadata of its elements from the web, or not.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.
/// The list of objects representing the unique identifier of scans of the media library.
@@ -110,7 +110,7 @@ public class Library : AggregateRoot
string? coverImage,
bool isEnabled,
bool isLocked,
- bool downloadMetadataFromWeb,
+ bool canDownloadMetadataFromWeb,
bool shouldSaveMetadataInMediaDirectories,
bool shouldSkipUnchangedDirectoriesDuringScan,
List scanIds) : base(id)
@@ -122,7 +122,7 @@ public class Library : AggregateRoot
CoverImage = coverImage;
IsEnabled = isEnabled;
IsLocked = isLocked;
- DownloadMetadataFromWeb = downloadMetadataFromWeb;
+ CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb;
ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories;
ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan;
_scanIds = scanIds;
@@ -138,7 +138,7 @@ public class Library : AggregateRoot
/// The path of the image file chosen by the user to be used as the cover for the library.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.
- /// Whether this media library should update the metadata of its elements from the web, or not.
+ /// Whether this media library should update the metadata of its elements from the web, or not.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.
/// The list of objects representing the unique identifier of scans of the media library.
@@ -153,7 +153,7 @@ public class Library : AggregateRoot
string? coverImageSourcePath,
bool isEnabled,
bool isLocked,
- bool downloadMetadataFromWeb,
+ bool canDownloadMetadataFromWeb,
bool shouldSaveMetadataInMediaDirectories,
bool shouldSkipUnchangedDirectoriesDuringScan,
List scanIds)
@@ -176,7 +176,7 @@ public class Library : AggregateRoot
coverImageSourcePath,
isEnabled,
isLocked,
- downloadMetadataFromWeb,
+ canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
scanIds
@@ -194,7 +194,7 @@ public class Library : AggregateRoot
/// The path of the image file chosen by the user to be used as the cover for the library.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.
- /// Whether this media library should update the metadata of its elements from the web, or not.
+ /// Whether this media library should update the metadata of its elements from the web, or not.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.
/// The list of objects representing the unique identifier of scans of the media library.
@@ -210,7 +210,7 @@ public class Library : AggregateRoot
string? coverImageSourcePath,
bool isEnabled,
bool isLocked,
- bool downloadMetadataFromWeb,
+ bool canDownloadMetadataFromWeb,
bool shouldSaveMetadataInMediaDirectories,
bool shouldSkipUnchangedDirectoriesDuringScan,
List scanIds)
@@ -233,7 +233,7 @@ public class Library : AggregateRoot
coverImageSourcePath,
isEnabled,
isLocked,
- downloadMetadataFromWeb,
+ canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
scanIds
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs
index e50f05f1..80f1dacd 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs
@@ -17,10 +17,9 @@ public interface IMediaLibraryScanningService
///
/// The media library scan to start.
/// The type of the media library to be scanned.
- /// Whether the library permits downloading data from the web, or not.
/// Cancellation token that can be used to stop the execution.
/// An representing either a successful operation, or an error.
- Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken);
+ Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken);
///
/// Cancels .
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs
index 2132a9da..211282ad 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
@@ -9,6 +8,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -55,10 +55,9 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
///
/// The media library scan to start.
/// The type of the media library to be scanned.
- /// Whether the library permits downloading data from the web, or not.
/// Cancellation token that can be used to stop the execution.
/// An representing either a successful operation, or an error.
- public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken)
+ public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken)
{
// mark the scan itself as started
Result startScanResult = scan.StartScan();
@@ -81,7 +80,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
IMediaTypeScanner scanner = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType);
// get the list of scan jobs for the retrieved scanner. It is impotant to enumerate them here, because deferred execuction would destroy any graph relationships
// and properties we might set before putting the jobs on the in-memory queue.
- List jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId, downloadMetadataFromWeb)];
+ List jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId)];
// count total jobs in the chain by traversing the job graph
int totalJobs = CountTotalJobs(jobs);
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs
index af55a807..c0027ad4 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs
@@ -21,7 +21,6 @@ public interface IMediaTypeScanner
/// Creates the media library scan jobs for the provided media library.
///
/// The unique identifier of the media library for which to create the media library scan jobs.
- /// Whether the library permits downloading data from the web, or not.
/// A collection of media library scan jobs.
- IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb);
+ IEnumerable CreateScanJobsForLibrary(LibraryId libraryId);
}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs
index 6cd60fc9..b463dd44 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs
@@ -4,7 +4,6 @@ using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects;
-using System;
using System.Diagnostics;
#endregion
@@ -20,6 +19,7 @@ public class UserSettings : AggregateRoot
private const int DEFAULT_ITEMS_PER_PAGE = 48;
private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false;
private const bool DEFAULT_IS_THEME_CACHING_ENABLED = true;
+ private const bool DEFAULT_AGGREGATE_METADATA_WHEN_MISSING = false;
///
/// Gets the object representing the unique identifier of the user that owns these settings.
@@ -39,13 +39,18 @@ public class UserSettings : AggregateRoot
///
/// Gets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
///
- public bool IgnoreThePrefixForAlphaPicker { get; private set; }
+ public bool ShouldIgnoreThePrefixForAlphaPicker { get; private set; }
///
/// Gets whether the theme data served to this user is cached, or not.
///
public bool IsThemeCachingEnabled { get; private set; }
+ ///
+ /// Gets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
+ ///
+ public bool ShouldAggregateMetadataWhenMissing { get; private set; }
+
///
/// Initializes a new instance of the class.
///
@@ -53,21 +58,24 @@ public class UserSettings : AggregateRoot
/// The object representing the unique identifier of the user that owns these settings.
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
- /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+ /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+ /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
private UserSettings(
UserSettingsId id,
UserId userId,
bool isPaginationEnabled,
int itemsPerPage,
- bool ignoreThePrefixForAlphaPicker,
- bool isThemeCachingEnabled) : base(id)
+ bool shouldIgnoreThePrefixForAlphaPicker,
+ bool isThemeCachingEnabled,
+ bool shouldAggregateMetadataWhenMissing) : base(id)
{
UserId = userId;
IsPaginationEnabled = isPaginationEnabled;
ItemsPerPage = itemsPerPage;
- IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
+ ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
IsThemeCachingEnabled = isThemeCachingEnabled;
+ ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing;
}
///
@@ -78,7 +86,7 @@ public class UserSettings : AggregateRoot
///
public static Result Create()
{
- return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED);
+ return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING);
}
///
@@ -90,7 +98,7 @@ public class UserSettings : AggregateRoot
///
public static Result Create(UserId userId)
{
- return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED);
+ return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING);
}
///
@@ -99,8 +107,9 @@ public class UserSettings : AggregateRoot
/// The object representing the unique identifier of the user that owns these settings.
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
- /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+ /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+ /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
///
/// An containing either a successfully created , or an error message.
///
@@ -108,8 +117,9 @@ public class UserSettings : AggregateRoot
UserId userId,
bool isPaginationEnabled,
int itemsPerPage,
- bool ignoreThePrefixForAlphaPicker,
- bool isThemeCachingEnabled)
+ bool shouldIgnoreThePrefixForAlphaPicker,
+ bool isThemeCachingEnabled,
+ bool shouldAggregateMetadataWhenMissing)
{
if (itemsPerPage <= 0)
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
@@ -119,8 +129,9 @@ public class UserSettings : AggregateRoot
userId,
isPaginationEnabled,
itemsPerPage,
- ignoreThePrefixForAlphaPicker,
- isThemeCachingEnabled);
+ shouldIgnoreThePrefixForAlphaPicker,
+ isThemeCachingEnabled,
+ shouldAggregateMetadataWhenMissing);
}
///
@@ -130,8 +141,9 @@ public class UserSettings : AggregateRoot
/// The object representing the unique identifier of the user that owns these settings.
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
- /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+ /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+ /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
///
/// An containing either a successfully created , or an error message.
///
@@ -140,13 +152,14 @@ public class UserSettings : AggregateRoot
UserId userId,
bool isPaginationEnabled,
int itemsPerPage,
- bool ignoreThePrefixForAlphaPicker,
- bool isThemeCachingEnabled)
+ bool shouldIgnoreThePrefixForAlphaPicker,
+ bool isThemeCachingEnabled,
+ bool shouldAggregateMetadataWhenMissing)
{
if (itemsPerPage <= 0)
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
- return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker, isThemeCachingEnabled);
+ return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing);
}
///
@@ -154,22 +167,25 @@ public class UserSettings : AggregateRoot
///
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
- /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+ /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+ /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
/// An representing either a successful update, or an error.
public Result UpdateSettings(
bool isPaginationEnabled,
int itemsPerPage,
- bool ignoreThePrefixForAlphaPicker,
- bool isThemeCachingEnabled)
+ bool shouldIgnoreThePrefixForAlphaPicker,
+ bool isThemeCachingEnabled,
+ bool shouldAggregateMetadataWhenMissing)
{
if (itemsPerPage <= 0)
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
IsPaginationEnabled = isPaginationEnabled;
ItemsPerPage = itemsPerPage;
- IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
+ ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
IsThemeCachingEnabled = isThemeCachingEnabled;
+ ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing;
return Result.Updated;
}
}
diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
index 1c41488f..60244347 100644
--- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
+++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
@@ -14,6 +14,7 @@ public static partial class Errors
public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty));
public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty));
public static Error MediaLibrariesDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaLibrariesDirectoryCannotBeEmpty));
+ public static Error MediaBooksDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaBooksDirectoryCannotBeEmpty));
public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty));
public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String));
public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty));
diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs
index 846b2d86..3c3b9829 100644
--- a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs
+++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs
@@ -23,5 +23,9 @@ public class MediaSettingsDtoValidator : AbstractValidator
RuleFor(settings => settings.LibrariesDirectory)
.NotEmpty()
.WithError(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty);
+
+ RuleFor(settings => settings.BooksDirectory)
+ .NotEmpty()
+ .WithError(Errors.Errors.Configuration.MediaBooksDirectoryCannotBeEmpty);
}
}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
index 2f650ac8..7548e7a7 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Events;
@@ -77,71 +80,140 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
- // get the metadata providers configured for the media library, in their configured order, that support the media library type
+ // load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
+ // whether the providers that require access to the web are used during the enrichment
+ string libraryName = string.Empty;
+ bool canDownloadMetadataFromWeb = false;
+ if (unitOfWork.LibraryRepository is not null)
+ {
+ Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
+ _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used.");
+ else
+ {
+ libraryName = getLibraryResult.Value.Title;
+ canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
+ }
+ }
+
+ // get the metadata providers configured for the media library, in their configured order, that support the media library type,
+ // skipping the providers that require access to the web when the media library does not permit downloading data from the web
Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
- List providers = [];
+ List providers = [];
foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
{
- List configuredProviders = [.. asyncServiceScope.ServiceProvider
- .GetKeyedServices(configuration.PluginId)
- .Where(provider => provider.SupportedLibraryType == LibraryType.Book)];
+ List configuredProviders = [.. asyncServiceScope.ServiceProvider
+ .GetKeyedServices(configuration.PluginId)
+ .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
+ && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
providers.AddRange(configuredProviders);
}
+ // read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing
+ bool shouldAggregateMetadataWhenMissing = false;
+ if (unitOfWork.UserSettingsRepository is not null)
+ {
+ Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false);
+ if (getUserSettingsResult.IsFailure)
+ _logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers.");
+ else
+ shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
+ }
+
+ // get the artwork providers configured for the media library, in their configured order, that support the media library type.
+ // the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the metadata enrichment from proceeding
+ List artworkProviders = [];
+ if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
+ {
+ Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getArtworkConfigurationsResult.IsFailure)
+ _logger.LogWarning("Failed to read the artwork provider configurations.");
+ else
+ {
+ foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
+ {
+ List configuredProviders = [.. asyncServiceScope.ServiceProvider
+ .GetKeyedServices(configuration.PluginId)
+ .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
+ && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
+ if (configuredProviders.Count == 0)
+ _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
+ artworkProviders.AddRange(configuredProviders);
+ }
+ }
+ }
+
+ IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService();
+
// count the books that need their metadata enriched, for progress reporting purposes
- Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
- if (getBooksToEnrichCountResult.IsFailure)
- throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
- int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
-
- // set the initial progress of the scan job
- Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
- if (publishJobProgressResult.IsFailure)
- throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
-
- DateTime lastUpdateTime = DateTime.UtcNow;
- int minUpdateIntervalMs = 100;
- int processedBooksCount = 0;
string? lastPath = null;
- // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
- while (true)
+ // when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely
+ if (providers.Count > 0)
{
- cancellationToken.ThrowIfCancellationRequested();
+ Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getBooksToEnrichCountResult.IsFailure)
+ throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
+ int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
- Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
- if (getBooksPageResult.IsFailure)
- throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
- IReadOnlyList booksPage = getBooksPageResult.Value;
- if (booksPage.Count == 0)
- break;
+ // set the initial progress of the scan job
+ Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishJobProgressResult.IsFailure)
+ throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
- foreach (BookEntity bookEntity in booksPage)
+ DateTime lastUpdateTime = DateTime.UtcNow;
+ int minUpdateIntervalMs = 100;
+ int processedBooksCount = 0;
+
+ // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
+ while (true)
{
cancellationToken.ThrowIfCancellationRequested();
- await EnrichBookAsync(bookEntity, providers, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false);
+ Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
+ if (getBooksPageResult.IsFailure)
+ throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
+ IReadOnlyList booksPage = getBooksPageResult.Value;
+ if (booksPage.Count == 0)
+ break;
- // check if enough time has passed since last update
- DateTime now = DateTime.UtcNow;
- if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
+ foreach (BookEntity bookEntity in booksPage)
{
- // increment the number of processed elements progress
- publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
- if (publishJobProgressResult.IsFailure)
- throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
- lastUpdateTime = now;
- }
- }
+ cancellationToken.ThrowIfCancellationRequested();
- lastPath = booksPage[^1].Path;
+ await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, artworkProviders, bookArtworkService, libraryName, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false);
+
+ // check if enough time has passed since last update
+ DateTime now = DateTime.UtcNow;
+ if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
+ {
+ // increment the number of processed elements progress
+ publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishJobProgressResult.IsFailure)
+ throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
+ lastUpdateTime = now;
+ }
+ }
+
+ // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size
+ await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ unitOfWork.ClearTrackedEntities();
+
+ lastPath = booksPage[^1].Path;
+ }
+ }
+ else
+ {
+ _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value);
}
- await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ // persist the changes when no page was processed, so that the scan still saves even when there are no books to enrich
+ if (lastPath is null)
+ await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// this job finished, and it's the last in the chain, the scan is completed
Status = LibraryScanJobStatus.Completed;
@@ -166,21 +238,29 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
///
- /// Enriches the metadata of the provided , using the provided in their configured order.
+ /// Enriches the metadata and the artwork of the provided , using the provided metadata and artwork providers in their configured order.
///
- /// The book whose metadata is enriched.
- /// The metadata providers, in their configured order.
- /// The repository used to persist the enriched metadata.
+ /// The book whose metadata and artwork are enriched.
+ /// The metadata providers, in their configured order.
+ /// Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not.
+ /// The artwork providers, in their configured order.
+ /// The service used to store the artwork of the book.
+ /// The name of the media library the book belongs to.
+ /// The repository used to persist the enriched book.
/// Cancellation token that can be used to stop the execution.
- private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList providers, IBookRepository bookRepository, CancellationToken cancellationToken)
+ private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, IBookRepository bookRepository, CancellationToken cancellationToken)
{
+ // when no metadata provider is available, the book must not be marked as failed to enrich, so the enrichment is skipped
+ if (metadataProviders.Count == 0)
+ return;
+
// convert the book to a domain object
Result getBookResult = bookEntity.ToDomainEntity();
if (getBookResult.IsFailure)
return;
Book book = getBookResult.Value;
- BookMetadataLookupDto lookup = new(
+ BookMetadataLookupDto bookMetadataLookup = new(
LibraryId: bookEntity.LibraryId,
Path: bookEntity.Path,
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results
@@ -190,24 +270,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
LanguageCode: bookEntity.LanguageCode
);
- // try the metadata providers in order, until one returns usable metadata
- foreach (IRemoteMetadataProvider provider in providers)
+ BookMetadataDto? appliedMetadata = shouldAggregateMetadataWhenMissing
+ ? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false)
+ : await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false);
+
+ if (appliedMetadata is null)
+ {
+ // no metadata provider returned usable metadata, mark the book as failed to enrich
+ book.MarkMetadataAsFailed();
+ Result markFailedResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (markFailedResult.IsFailure)
+ _logger.LogWarning("Failed to persist the failed enrichment state of the book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path);
+ return;
+ }
+
+ // resolve the artwork of the book from the artwork providers, in their configured order
+ await EnrichBookArtworkAsync(book, appliedMetadata, artworkProviders, bookArtworkService, libraryName, cancellationToken).ConfigureAwait(false);
+
+ Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (updateBookResult.IsFailure)
+ _logger.LogWarning("Failed to persist the enriched book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path);
+ }
+
+ ///
+ /// Tries the in order, applying the metadata of the first one that returns usable metadata.
+ ///
+ /// The book onto which the metadata is applied.
+ /// The lookup describing the book.
+ /// The metadata providers, in their configured order.
+ /// Cancellation token that can be used to stop the execution.
+ /// The applied metadata, or when no provider returned usable metadata.
+ private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken)
+ {
+ foreach (IMetadataProvider metadataProvider in metadataProviders)
{
try
{
- MetadataDto? metadataResult = await provider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
+ MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
- Result applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow);
+ Result applyMetadataResult = book.ApplyMetadata(bookMetadata, metadataProvider.Name, DateTime.UtcNow);
if (applyMetadataResult.IsFailure)
continue;
+ return bookMetadata;
+ }
+ catch (Exception)
+ {
+ // a failing metadata provider must not prevent the other providers from being tried
+ }
+ }
+ return null;
+ }
- Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
- if (updateBookResult.IsFailure)
+ ///
+ /// Aggregates the metadata of the from all the , in their configured order, filling the fields that the earlier providers lack with the values of the later ones.
+ ///
+ /// The book onto which the aggregated metadata is applied.
+ /// The lookup describing the book.
+ /// The metadata providers, in their configured order.
+ /// Cancellation token that can be used to stop the execution.
+ /// The applied aggregated metadata, or when no provider returned usable metadata.
+ private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken)
+ {
+ BookMetadataDto? mergedMetadata = null;
+ List contributingProviders = [];
+
+ foreach (IMetadataProvider metadataProvider in metadataProviders)
+ {
+ try
+ {
+ MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
+ if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
- return;
+ mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata);
+ contributingProviders.Add(metadataProvider.Name);
+ // the identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely
+ bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata);
}
catch (Exception)
{
@@ -215,25 +355,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
}
- // no metadata provider returned usable metadata, mark the book as failed to enrich
- book.MarkMetadataAsFailed();
- await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (mergedMetadata is null)
+ return null;
+
+ Result applyMetadataResult = book.ApplyMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)), DateTime.UtcNow);
+ return applyMetadataResult.IsFailure ? null : mergedMetadata;
}
///
- /// Determines whether the provided is usable, meaning it has a title and at least one primary identifier.
+ /// Resolves the artwork of the from the , in their configured order, storing the artwork of the first provider that returns it.
///
- /// The metadata to validate.
- /// when the metadata is usable, otherwise .
- private static bool IsUsableMetadata(BookMetadataDto metadata)
+ /// The book whose artwork is enriched.
+ /// The metadata applied to the book, used to build the directory of the book artwork.
+ /// The artwork providers, in their configured order.
+ /// The service used to store the artwork of the book.
+ /// The name of the media library the book belongs to.
+ /// Cancellation token that can be used to stop the execution.
+ private static async Task EnrichBookArtworkAsync(Book book, BookMetadataDto appliedMetadata, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, CancellationToken cancellationToken)
{
- if (string.IsNullOrWhiteSpace(metadata.Title))
- return false;
- return !string.IsNullOrWhiteSpace(metadata.GoodreadsId)
- || !string.IsNullOrWhiteSpace(metadata.OpenLibraryId)
- || !string.IsNullOrWhiteSpace(metadata.GoogleBooksId)
- || !string.IsNullOrWhiteSpace(metadata.ASIN)
- || (metadata.Isbns is not null && metadata.Isbns.Count > 0);
+ if (bookArtworkService is null || artworkProviders.Count == 0)
+ return;
+
+ foreach (IArtworkProvider provider in artworkProviders)
+ {
+ ArtworkDto? artwork = null;
+ try
+ {
+ artwork = await provider.GetArtworkAsync(new BookMetadataLookupDto(LibraryId: book.LibraryId.Value, Path: book.Path), cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception)
+ {
+ // a failing artwork provider must not prevent the other providers from being tried
+ }
+
+ if (artwork is null)
+ continue;
+
+ // a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract
+ if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess)
+ continue;
+
+ string authorName = appliedMetadata.Contributors?.FirstOrDefault(contributor => contributor.Name?.DisplayName is not null)?.Name?.DisplayName ?? string.Empty;
+ string bookTitle = appliedMetadata.Title ?? book.Metadata.Title;
+ Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(book.LibraryId.Value, book.Id.Value, libraryName, authorName, bookTitle, artwork, cancellationToken).ConfigureAwait(false);
+ if (saveArtworkResult.IsFailure)
+ continue;
+
+ book.SetBookCoverImagePath(saveArtworkResult.Value);
+ return;
+ }
+ }
+
+ ///
+ /// Enriches the with the identifiers and the title discovered by the already queried metadata providers.
+ ///
+ /// The lookup to enrich.
+ /// The metadata discovered by the already queried metadata providers.
+ /// The enriched lookup.
+ private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata)
+ {
+ string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value;
+ string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId;
+ string? title = bookMetadataLookup.Title ?? bookMetadata.Title;
+ return bookMetadataLookup with
+ {
+ Isbn = isbn,
+ OpenLibraryId = openLibraryId,
+ Title = title
+ };
+ }
+
+ ///
+ /// Determines whether the provided is usable, meaning it has a title.
+ ///
+ /// The metadata to validate.
+ /// when the metadata is usable, otherwise .
+ private static bool IsUsableMetadata(BookMetadataDto bookMetadata)
+ {
+ return !string.IsNullOrWhiteSpace(bookMetadata.Title);
}
///
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs
new file mode 100644
index 00000000..3d314e8b
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs
@@ -0,0 +1,127 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
+
+///
+/// Merges the book metadata returned by multiple metadata providers into a single book metadata, giving priority to the first provider that provides a value for each field.
+///
+internal static class MetadataAggregator
+{
+ ///
+ /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields.
+ ///
+ /// The first metadata to merge, whose values have priority.
+ /// The second metadata to merge, filling the fields that the first metadata lacks.
+ /// The merged metadata.
+ public static BookMetadataDto Merge(BookMetadataDto first, BookMetadataDto second)
+ {
+ return new BookMetadataDto(
+ FirstOrDefaultReference(first.Title, second.Title),
+ FirstOrDefaultReference(first.OriginalTitle, second.OriginalTitle),
+ FirstOrDefaultReference(first.Description, second.Description),
+ MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo),
+ Union(first.Genres, second.Genres, genre => genre.Name),
+ Union(first.Tags, second.Tags, tag => tag.Name),
+ FirstOrDefaultReference(first.Language, second.Language),
+ FirstOrDefaultReference(first.OriginalLanguage, second.OriginalLanguage),
+ FirstOrDefaultReference(first.Publisher, second.Publisher),
+ FirstOrDefaultValue(first.PageCount, second.PageCount),
+ FirstOrDefaultValue(first.Format, second.Format),
+ FirstOrDefaultReference(first.Edition, second.Edition),
+ FirstOrDefaultValue(first.VolumeNumber, second.VolumeNumber),
+ FirstOrDefaultReference(first.Series, second.Series),
+ FirstOrDefaultReference(first.ASIN, second.ASIN),
+ FirstOrDefaultReference(first.GoodreadsId, second.GoodreadsId),
+ FirstOrDefaultReference(first.LCCN, second.LCCN),
+ FirstOrDefaultReference(first.OCLCNumber, second.OCLCNumber),
+ FirstOrDefaultReference(first.OpenLibraryId, second.OpenLibraryId),
+ FirstOrDefaultReference(first.LibraryThingId, second.LibraryThingId),
+ FirstOrDefaultReference(first.GoogleBooksId, second.GoogleBooksId),
+ FirstOrDefaultReference(first.BarnesAndNobleId, second.BarnesAndNobleId),
+ FirstOrDefaultReference(first.AppleBooksId, second.AppleBooksId),
+ Union(first.Isbns, second.Isbns, isbn => isbn.Value),
+ Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role?.Name}"),
+ Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()),
+ FirstOrDefaultReference(first.CoverImagePath, second.CoverImagePath));
+ }
+
+ ///
+ /// Merges the release information of the two metadata, keeping the first non-null value of each field.
+ ///
+ /// The first release information, whose values have priority.
+ /// The second release information, filling the fields that the first one lacks.
+ /// The merged release information, or when both are .
+ private static ReleaseInfoDto? MergeReleaseInfo(ReleaseInfoDto? first, ReleaseInfoDto? second)
+ {
+ if (first is null && second is null)
+ return null;
+
+ return new ReleaseInfoDto(
+ FirstOrDefaultValue(first?.OriginalReleaseDate, second?.OriginalReleaseDate),
+ FirstOrDefaultValue(first?.OriginalReleaseYear, second?.OriginalReleaseYear),
+ FirstOrDefaultValue(first?.ReReleaseDate, second?.ReReleaseDate),
+ FirstOrDefaultValue(first?.ReReleaseYear, second?.ReReleaseYear),
+ FirstOrDefaultReference(first?.ReleaseCountry, second?.ReleaseCountry),
+ FirstOrDefaultReference(first?.ReleaseVersion, second?.ReleaseVersion));
+ }
+
+ ///
+ /// Gets the first non-null value of the two reference values.
+ ///
+ /// The type of the reference values.
+ /// The value with priority.
+ /// The fallback value.
+ /// The first non-null value, or when both are .
+ private static T? FirstOrDefaultReference(T? first, T? second)
+ where T : class
+ {
+ return first ?? second;
+ }
+
+ ///
+ /// Gets the first non-null value of the two nullable value types.
+ ///
+ /// The underlying type of the nullable values.
+ /// The value with priority.
+ /// The fallback value.
+ /// The first non-null value, or when both are .
+ private static T? FirstOrDefaultValue(T? first, T? second)
+ where T : struct
+ {
+ return first ?? second;
+ }
+
+ ///
+ /// Returns the union of the two collections, de-duplicated by the key, keeping the items of the first collection on key conflicts.
+ ///
+ /// The type of the collection items.
+ /// The first collection, whose items have priority.
+ /// The second collection.
+ /// The function used to extract the de-duplication key of an item.
+ /// The union of the two collections, or when both are .
+ private static List? Union(List? first, List? second, Func keySelector)
+ where T : class
+ {
+ if (first is null && second is null)
+ return null;
+
+ Dictionary seen = new(StringComparer.OrdinalIgnoreCase);
+ List result = [];
+
+ void AddRange(List? items)
+ {
+ foreach (T item in items ?? [])
+ if (seen.TryAdd(keySelector(item) ?? string.Empty, item))
+ result.Add(item);
+ }
+
+ AddRange(first);
+ AddRange(second);
+ return result;
+ }
+}
diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json
index 7790a2e1..6671a6dd 100644
--- a/src/Lumina.Infrastructure/appsettings.shared.json
+++ b/src/Lumina.Infrastructure/appsettings.shared.json
@@ -1,7 +1,8 @@
{
"MediaSettings": {
"RootDirectory": "media",
- "LibrariesDirectory": "libraries"
+ "LibrariesDirectory": "libraries",
+ "BooksDirectory": "books"
},
"PluginsSettings": {
"Directory": "plugins"
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs
index 2389d2eb..23cc0cd5 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs
@@ -34,7 +34,7 @@ public class AddLibraryEndpointSummary : Summary r.CoverImage, "The path of the image file used as the cover for the library. Optional.");
RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.");
RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.");
- RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
+ RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.");
RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.");
@@ -57,7 +57,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library.");
ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed.");
ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.");
- ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
+ ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.");
ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created.");
@@ -73,7 +73,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library.");
ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed.");
ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.");
- ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
+ ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.");
ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created.");
@@ -53,7 +53,7 @@ public class GetLibraryEndpointSummary : Summary r.CoverImage, "The path of the image file used as the cover for the library. Optional.");
RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.");
RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.");
- RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
+ RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.");
RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.");
@@ -61,7 +61,7 @@ public class UpdateLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library.");
ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed.");
ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.");
- ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
+ ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.");
ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created.");
@@ -77,7 +77,7 @@ public class UpdateLibraryEndpointSummary : Summary r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required.");
RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Required.");
- RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required.");
+ RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required.");
RequestParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not. Required.");
Response(200, "The settings of the current user were successfully updated.");
diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs
index bc43dad9..574d7c33 100644
--- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs
+++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Enums.Library;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -56,7 +55,7 @@ public class LibraryDto
///
/// Gets or sets whether this media library should update the metadata of its elements from the web, or not.
///
- public bool DownloadMetadataFromWeb { get; set; } = true;
+ public bool CanDownloadMetadataFromWeb { get; set; } = true;
///
/// Gets or sets whether this media library should copy the downloaded metadata into the media library content locations, or not.
diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs
index c074a3c6..d38be3b3 100644
--- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs
+++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs
@@ -29,10 +29,15 @@ public class UserSettingsDto
///
/// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
///
- public bool IgnoreThePrefixForAlphaPicker { get; set; }
+ public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; }
///
/// Gets or sets whether the theme data served to this user is cached, or not.
///
public bool IsThemeCachingEnabled { get; set; } = true;
+
+ ///
+ /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
+ ///
+ public bool ShouldAggregateMetadataWhenMissing { get; set; }
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs
index 8f00c2dd..73bc9ef4 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs
@@ -2,7 +2,6 @@
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Libraries;
-using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -29,7 +28,7 @@ public class SaveLibraryEndpointSummary : Summary r.ContentLocations, "The collection of directories that contain the media library files. Required.");
RequestParam(r => r.IsEnabled, "Whether the media library is enabled or not. Optional.");
RequestParam(r => r.IsLocked, "Whether the media library is locked or not. Optional.");
- RequestParam(r => r.DownloadMetadataFromWeb, "Whether the metadata of the media library items should be downloaded from the web, or not. Optional.");
+ RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether the metadata of the media library items should be downloaded from the web, or not. Optional.");
RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether the downloaded metadata should be copied into the media library content locations, or not. Optional.");
RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether the directories whose contents have not changed since the last scan should be skipped during the scan, or not. Optional.");
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs
index ead45202..bd430938 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
-using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -23,7 +22,7 @@ public class UpdateUserSettingsEndpointSummary : Summary r.UserId, "The unique identifier of the user that owns the settings. Optional.");
RequestParam(r => r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Optional.");
RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Optional.");
- RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading 'The' prefix of library item titles is ignored by the alpha picker, or not. Optional.");
+ RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading 'The' prefix of library item titles is ignored by the alpha picker, or not. Optional.");
ExampleRequest = new UserSettingsDto();
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx
index 0884bea3..01372ba1 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx
@@ -1,4 +1,4 @@
-
+