From c4246d2e69a434e0f33dc3e220a2ab364479474b Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 16 Feb 2025 21:45:26 +0200 Subject: [PATCH] Moves media library scanning to domain layer --- .../architecture-decission-record-0001.md | 103 +++ .../MediaLibrary/Management/LibraryEntity.cs | 7 +- .../Management/LibraryScanEntity.cs | 66 ++ .../Entities/UsersManagement/UserEntity.cs | 7 +- .../MediaLibrary/ILibraryScanRepository.cs | 37 + .../DataAccess/Seed/IDataSeedService.cs | 8 +- .../ApplicationLayerServices.cs | 23 +- .../Authorization/IAuthorizationService.cs | 8 +- .../Common/Base/IAuthorizationPolicy.cs | 2 +- .../Models/Scanning/MediaScanTrackerModel.cs | 4 +- .../Common/Metadata/GenreDtoMapping.cs | 8 +- .../Common/Metadata/GenreEntityMapping.cs | 8 +- .../Mapping/Common/Metadata/TagDtoMapping.cs | 8 +- .../Common/Metadata/TagEntityMapping.cs | 8 +- .../CancelLibraryScanRequestMapping.cs | 3 +- .../Management/LibraryEntityMapping.cs | 15 +- .../MediaLibrary/Management/LibraryMapping.cs | 12 + .../Management/LibraryScanEntityMapping.cs | 50 ++ .../Management/LibraryScanMapping.cs | 35 + .../BookLibrary/Books/BookEntityMapping.cs | 2 +- .../Common/BookRatingDtoMapping.cs | 8 +- .../Common/BookRatingEntityMapping.cs | 8 +- .../BookLibrary/Common/IsbnDtoMapping.cs | 4 +- .../BookLibrary/Common/IsbnEntityMapping.cs | 8 +- .../Commands/DeleteRole/DeleteRoleCommand.cs | 2 +- .../DeleteRole/DeleteRoleCommandHandler.cs | 4 +- .../Commands/UpdateRole/UpdateRoleCommand.cs | 2 +- .../GetRolePermissionsQuery.cs | 2 +- .../SetupApplicationCommandHandler.cs | 3 +- .../AddLibrary/AddLibraryCommandHandler.cs | 25 +- .../CancelLibrariesScanCommand.cs | 2 +- .../CancelLibrariesScanCommandHandler.cs | 81 +- .../CancelLibraryScanCommand.cs | 10 +- .../CancelLibraryScanCommandHandler.cs | 73 +- .../CancelLibraryScanCommandValidator.cs | 5 +- .../DeleteLibrary/DeleteLibraryCommand.cs | 2 +- .../DeleteLibraryCommandHandler.cs | 7 +- .../ScanLibrariesCommandHandler.cs | 67 +- .../ScanLibrary/ScanLibraryCommand.cs | 2 +- .../ScanLibrary/ScanLibraryCommandHandler.cs | 66 +- .../UpdateLibrary/UpdateLibraryCommand.cs | 4 +- .../UpdateLibraryCommandHandler.cs | 23 +- .../Events/LibrarySavedDomainEventHandler.cs | 12 +- .../LibraryScanCancelledDomainEventHandler.cs | 62 ++ .../LibraryScanFailedDomainEventHandler.cs | 69 ++ ...ryScanProgressChangedDomainEventHandler.cs | 24 + .../LibraryScanQueuedDomainEventHandler.cs | 74 ++ .../LibraryScanStartedDomainEventHandler.cs | 47 + .../Queries/GetLibrary/GetLibraryQuery.cs | 2 +- .../MediaLibrariesScanCancellationTracker.cs} | 21 +- .../Scanning/IMediaLibraryScanningService.cs | 28 - .../Jobs/Common/FileSystemDiscoveryJob.cs | 76 +- .../Scanning/Jobs/Common/HashComparerJob.cs | 15 +- .../Common/RepositoryMetadataDiscoveryJob.cs | 9 +- .../Books/GoodReadsMetadataScrapJob.cs | 11 +- .../Scanning/MediaLibraryScanningService.cs | 84 -- .../Queue/IMediaLibrariesScanQueue.cs | 22 - .../Scanning/Queue/MediaLibrariesScanQueue.cs | 26 +- .../Queue/MediaLibraryScanJobProcessorJob.cs | 16 +- .../WrittenContent/IBookLibraryTypeScanner.cs | 12 - .../RegisterUserCommandHandler.cs | 3 +- .../UpdateUserRoleAndPermissionsCommand.cs | 4 +- ...ateUserRoleAndPermissionsCommandHandler.cs | 3 +- .../GetAuthorization/GetAuthorizationQuery.cs | 2 +- .../GetUserPermissionsQuery.cs | 2 +- .../Queries/GetUserRole/GetUserRoleQuery.cs | 2 +- .../DTO/Authentication/PermissionDto.cs | 2 +- .../DTO/Authentication/RoleDto.cs | 2 +- .../Authorization/DeleteRoleRequest.cs | 2 +- .../Authorization/GetAuthorizationRequest.cs | 2 +- .../GetUserPermissionsRequest.cs | 2 +- .../Authorization/GetUserRoleRequest.cs | 2 +- .../Authorization/UpdateRoleRequest.cs | 2 +- .../UpdateUserRoleAndPermissionsRequest.cs | 4 +- .../Management/CancelLibraryScanRequest.cs | 10 +- .../Management/DeleteLibraryRequest.cs | 2 +- .../Management/GetLibraryRequest.cs | 2 +- .../Management/ScanLibraryRequest.cs | 2 +- .../Management/UpdateLibraryRequest.cs | 4 +- .../BookLibrary/Books/GetBookRequest.cs | 2 +- .../Responses/Authentication/LoginResponse.cs | 2 +- .../Authentication/RegistrationResponse.cs | 2 +- .../Authorization/AuthorizationResponse.cs | 2 +- .../Authorization/PermissionResponse.cs | 2 +- .../Responses/Authorization/RoleResponse.cs | 2 +- .../Management/LibraryResponse.cs | 4 +- .../Management/ScanLibraryResponse.cs | 4 +- .../Common/Configuration/BookConfiguration.cs | 17 + .../Configuration/LibraryConfiguration.cs | 23 + .../Configuration/LibraryScanConfiguration.cs | 61 ++ .../UpdateAuditableEntitiesInterceptor.cs | 4 +- ...0409_AddsMediaLibraryScanTable.Designer.cs | 808 ++++++++++++++++++ ...0250215190409_AddsMediaLibraryScanTable.cs | 217 +++++ .../LuminaDbContextModelSnapshot.cs | 90 +- .../Libraries/LibraryScanRepository.cs | 108 +++ .../Core/Seed/DataSeedService.cs | 8 +- .../Core/UoW/LuminaDbContext.cs | 1 + .../DomainLayerServices.cs | 8 + .../MediaLibrary/LibraryScanJobStatus.cs | 4 +- .../Common/Errors/Errors.LibraryScanning.cs | 26 + .../Common/Models/Core/AggregateRoot.cs | 10 +- .../Common/Models/Core/Entity.cs | 14 +- .../Events/LibraryDeletedDomainEvent.cs | 2 +- .../Events/LibrarySavedDomainEvent.cs | 2 +- .../LibraryAggregate/Library.cs | 65 +- .../Events/LibraryScanCancelledDomainEvent.cs | 24 + .../Events/LibraryScanCompletedDomainEvent.cs | 21 + .../Events/LibraryScanFailedDomainEvent.cs | 24 + .../LibraryScanProgressChangedDomainEvent.cs | 24 + .../Events/LibraryScanQueuedDomainEvent.cs | 24 + .../Events/LibraryScanStartedDomainEvent.cs | 20 + .../LibraryScanAggregate/LibraryScan.cs | 151 ++++ ...IMediaLibrariesScanCancellationTracker.cs} | 20 +- .../Services/IMediaLibraryScanningService.cs | 31 + .../Services/Jobs/IFileSystemDiscoveryJob.cs | 8 + .../Services/Jobs/IHashComparerJob.cs | 8 + .../Services/Jobs/IMediaLibraryScanJob.cs | 69 ++ .../Jobs}/IMediaLibraryScanJobFactory.cs | 7 +- .../Jobs/IRepositoryMetadataDiscoveryJob.cs | 9 + .../Services/Jobs}/MediaLibraryScanJob.cs | 37 +- .../Jobs}/MediaLibraryScanJobFactory.cs | 11 +- .../Services/MediaLibraryScanningService.cs | 92 ++ .../Queue/IMediaLibrariesScanQueue.cs | 22 + .../Common/IMediaLibraryScannerFactory.cs | 2 +- .../Scanners/Common/IMediaTypeScanner.cs | 13 +- .../Common/MediaLibraryScannerFactory.cs | 4 +- .../ValueObjects/ScanId.cs | 48 ++ .../ValueObjects/ScanJobProgress.cs | 88 ++ .../MediaContributor.cs | 2 +- .../UserAggregate/User.cs | 23 +- .../MovieLibraryAggregate/Movie.cs | 10 - .../Entities/Episode.cs | 4 +- .../TvShowLibraryAggregate/Entities/Season.cs | 6 +- .../TvShowLibraryAggregate/TvShow.cs | 4 +- .../BookLibraryAggregate/Book.cs | 22 +- .../Entities/BookSeries.cs | 4 +- .../Jobs/IGoodReadsMetadataScrapJob.cs | 13 + .../Scanners}/BookLibraryTypeScanner.cs | 22 +- .../Scanners/IBookLibraryTypeScanner.cs | 12 + src/Lumina.Domain/Lumina.Domain.csproj | 4 + .../Authorization/AuthorizationService.cs | 6 +- .../Policies/Over18/Over18Policy.cs | 2 +- .../Library/Management/ApiRoutes.Libraries.cs | 9 +- .../DeleteRole/DeleteRoleEndpointSummary.cs | 2 +- .../UpdateRole/UpdateRoleEndpointSummary.cs | 2 +- .../AddLibrary/AddLibraryEndpointSummary.cs | 2 +- .../CancelLibrariesScanEndpoint.cs | 2 +- .../CancelLibrariesScanEndpointSummary.cs | 8 +- .../CancelLibraryScanEndpoint.cs | 6 +- .../CancelLibraryScanEndpointSummary.cs | 27 +- .../DeleteLibraryEndpointSummary.cs | 2 +- .../GetLibrary/GetLibraryEndpointSummary.cs | 4 +- .../ScanLibraries/ScanLibrariesEndpoint.cs | 2 +- .../ScanLibrariesEndpointSummary.cs | 6 +- .../ScanLibrary/ScanLibraryEndpoint.cs | 4 +- .../ScanLibrary/ScanLibraryEndpointSummary.cs | 16 +- .../UpdateLibraryEndpointSummary.cs | 6 +- .../GetAuthorizationEndpointSummary.cs | 2 +- .../GetUserPermissionsEndpointSummary.cs | 2 +- .../GetUserRole/GetUserRoleEndpointSummary.cs | 2 +- ...teUserRoleAndPermissionsEndpointSummary.cs | 4 +- .../GetAuthorizationResponseModel.cs | 2 +- .../Models/Authorization/PermissionModel.cs | 2 +- .../Common/Models/Authorization/RoleModel.cs | 2 +- .../Authorization/UpdateRoleRequestModel.cs | 2 +- ...pdateUserRoleAndPermissionsRequestModel.cs | 4 +- .../UsersManagement/LoginResponseModel.cs | 2 +- .../Models/UsersManagement/UserModel.cs | 2 +- .../Controllers/AdminController.cs | 8 +- .../Management/LibraryManagementController.cs | 19 +- .../ExceptionHandlingMiddleware.de-DE.resx | 24 + .../ExceptionHandlingMiddleware.en-US.resx | 24 + .../ExceptionHandlingMiddleware.es-ES.resx | 24 + .../ExceptionHandlingMiddleware.fr-FR.resx | 24 + .../ExceptionHandlingMiddleware.it-IT.resx | 24 + .../ExceptionHandlingMiddleware.ja-JP.resx | 24 + .../ExceptionHandlingMiddleware.resx | 24 + .../ExceptionHandlingMiddleware.ro-RO.resx | 24 + .../ExceptionHandlingMiddleware.ru-RU.resx | 24 + .../ExceptionHandlingMiddleware.zh-CN.resx | 24 + .../Views/Library/Management/Index.de-DE.resx | 3 + .../Views/Library/Management/Index.en-US.resx | 3 + .../Views/Library/Management/Index.es-ES.resx | 3 + .../Views/Library/Management/Index.fr-FR.resx | 3 + .../Views/Library/Management/Index.it-IT.resx | 3 + .../Views/Library/Management/Index.ja-JP.resx | 3 + .../Views/Library/Management/Index.resx | 3 + .../Views/Library/Management/Index.ro-RO.resx | 3 + .../Views/Library/Management/Index.ru-RU.resx | 3 + .../Views/Library/Management/Index.zh-CN.resx | 3 + .../Views/Library/Management/Index.cshtml | 25 +- .../wwwroot/js/site.js | 2 +- src/Lumina.sln | 9 + .../GetDirectoriesEndpointTests.cs | 2 +- .../Files/GetFilesEndpointTests.cs | 2 +- .../Files/GetTreeFilesEndpointTests.cs | 2 +- .../Path/CheckPathExistsEndpointTests.cs | 2 +- .../Path/CombinePathEndpointTests.cs | 2 +- .../Path/GetPathParentEndpointTests.cs | 2 +- .../Path/GetPathRootEndpointTests.cs | 2 +- .../Path/GetPathSeparatorEndpointTests.cs | 2 +- .../Path/SplitPathEndpointTests.cs | 2 +- .../Path/ValidatePathEndpointTests.cs | 2 +- .../Thumbnails/GetThumbnailEndpointTests.cs | 2 +- .../Books/GetBooksEndpointTests.cs | 2 +- .../Management/LibraryEntityMappingTests.cs | 4 +- .../Management/LibraryMappingTests.cs | 62 +- .../Fixtures/DomainLibraryFixture.cs | 20 +- .../Users/Fixtures/UserEntityFixture.cs | 2 +- 209 files changed, 3793 insertions(+), 641 deletions(-) create mode 100644 docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/{Tracking/MediaLibrariesScanTracker.cs => Cancellation/MediaLibrariesScanCancellationTracker.cs} (75%) delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaLibraryScanningService.cs delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaLibraryScanningService.cs delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/IMediaLibrariesScanQueue.cs delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCompletedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs => Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs} (51%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanJob.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common => Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs}/IMediaLibraryScanJobFactory.cs (70%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common => Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs}/MediaLibraryScanJob.cs (70%) rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common => Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs}/MediaLibraryScanJobFactory.cs (75%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning => Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services}/Scanners/Common/IMediaLibraryScannerFactory.cs (86%) rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning => Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services}/Scanners/Common/IMediaTypeScanner.cs (53%) rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning => Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services}/Scanners/Common/MediaLibraryScannerFactory.cs (95%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanId.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanJobProgress.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IGoodReadsMetadataScrapJob.cs rename src/{Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent => Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners}/BookLibraryTypeScanner.cs (59%) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md new file mode 100644 index 00000000..173a293e --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md @@ -0,0 +1,103 @@ +# Architecture Decision Record (ADR): 0001 - Use of `IServiceScopeFactory` for EF Core Lifetime Management in Library Scan Background Jobs + +## Status +**Accepted** (2025-02-15) + +## Context +The media library scanning system requires complex job graphs with parent-child relationships that cannot be recreated during execution. The conflict arises from: + +1. **Complex creational pattern**: Library scan jobs have complex parent-child dynamic relationships that needs to be established during the initiation of a library scan. This complex creational logic requires encapsulation (see `IMediaTypeScanner.CreateScanJobsForLibrary()`). +2. **Special job execution treatment**: Only top level library scan jobs with no parents are placed on an in-memory queue, from where they will be processed. The children are not placed in this queue because their processing depends on the payload(s) delivered by their parent(s). Therefor, it is the responsibility of the parents to fire the execution of their children's jobs, when their processing is done, and not by the background queue processing job. +3. **Discrepancy between user scope and background processing scope**: Processing of queued jobs is done in a singleton context, due to some jobs being long running processes that need to run in a background service. This means that any scoped services created when the user triggered the library scan are long disposed when child jobs are triggered by their parents. This includes unit of works, repositories and DbContexts. +1. **EF Core Lifetime Requirements**: DbContext (scoped) becomes disposed before background jobs execute. +2. **Domain Integrity Constraints**: Jobs are first-class domain objects with established relationships that must persist. +3. **Architecture Layer Boundaries**: Application layer must not reference EF Core directly. + +## Decission +`IServiceScopeFactory` will be used in a controlled manner to create execution contexts for background jobs: + +```chsarp +// sample job class (simplified) +internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob +{ + private readonly IServiceScopeFactory _scopeFactory; + + protected FileSystemDiscoveryJob(IServiceScopeFactory scopeFactory) + { + _scopeFactory = scopeFactory; + } + + public async Task ExecuteAsync() + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService(); + ILibraryRepository libraryRepository = unitOfWork.GetRepository(); + // execution logic + } +} +``` +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|-----------------------|-----------------------------------------------------------| +| Lifetime Management | Ensures fresh DbContext per job execution | +| Domain Model | Preserves job graph relationships | +| Performance | Enables parallel processing without shared state | +| Layer Integrity | Maintains application layer purity | + +### Risks and Tradeoffs + +| Risk | Mitigation Strategy | +|---------------------------|-------------------------------------------------------------------| +| Service Locator Pattern | Strictly limit usage to job classes by marking them as `sealed` | +| Scope Leakage | `await using` ensures deterministic disposal | +| Testing Complexity | Provide base test fixtures for contributors | + +## Alternatives Considered + +### 1. Job recreation at the background job processor end +```csharp +internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken cancellationToken) + { + await foreach (IMediaLibraryScanJob job in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken)) + { + await using AsyncServiceScope scope = _scopeFactory.CreateAsyncScope(); + { + IMediaLibraryScanJob scopedJob = (IMediaLibraryScanJob)scope.ServiceProvider.GetRequiredService(job.GetType()); + scopedJob.ScanId = originalJob.ScanId; + scopedJob.UserId = originalJob.UserId; + scopedJob.LibraryId = originalJob.LibraryId; + await scopedJob.ExecuteAsync(Guid.NewGuid(), new { }, cancellationToken); + } + } + } +} +``` + +**Rejected**: Destroys parent-child relationships between jobs. The domain model relies on pre-established directed acyclic graphs that cannot be rehydrated without violating encapsulation (See `IMediaTypeScanner.CreateScanJobsForLibrary()`). + +### 2. Stateful handler pattern +```csharp +// requires splitting jobs into configuration/execution phases +public record JobState(ScanId, UserId, LibraryId); +public class JobHandler +{ + public Task ExecuteAsync(JobState state) { /* ... */ } +} +``` + +**Rejected**: Would require complete architectural redesign of the library scanning aggregate, and would not easily scale to multiple jobs requiring different payload types. + +### 3. Registration of `DbContextFactory` instead of `DbContext` +```csharp +services.AddDbContextFactory(options => +{ + options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}"); +} +``` + +**Rejected**: Would require a dependency on EF Core in the Application layer, and even when using an abstraction, would completely defeat the purpose of using the Repository + Unit of Work patterns used everywhere else in the Application layer. 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 fc3a189f..080dc156 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -41,10 +41,15 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity public required LibraryType LibraryType { get; set; } /// - /// Gets or sets the list of file system paths that make up the media library. + /// Gets the list of file system paths that make up the media library. /// public required ICollection ContentLocations { get; init; } = []; + /// + /// Gets the list of scans of the media library. + /// + public ICollection LibraryScans { get; init; } = []; + /// /// Gets whether this media library is enabled or not. A disabled media library is never shown or changed. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanEntity.cs new file mode 100644 index 00000000..d3b771ca --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanEntity.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Repository entity for a media library. +/// +[DebuggerDisplay("Id: {Id}; Status: {Status}")] +public class LibraryScanEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the media library. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the media library that is scanned. + /// + public required Guid LibraryId { get; init; } + + /// + /// Gets the Id of the user that initiated the media library scan. + /// + public required Guid UserId { get; init; } + + /// + /// Gets the status of the media library scan. + /// + public required LibraryScanJobStatus Status { get; init; } + + /// + /// Gets the media library that is scanned. + /// + public required LibraryEntity Library { get; init; } = null!; + + /// + /// Gets the user that initiated the media library scan. + /// + public required UserEntity User { get; init; } = null!; + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs index 651d32bf..00d579b4 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs @@ -48,7 +48,12 @@ public class UserEntity : IStorageEntity, IAuditableEntity /// /// Gets the collection of libraries owned by this user. /// - public required ICollection Libraries { get; init; } = []; + public ICollection Libraries { get; init; } = []; + + /// + /// Gets the collection of library scans initiated by this user. + /// + public ICollection LibraryScans { get; init; } = []; /// /// Gets the user roles association that includes this user. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs new file mode 100644 index 00000000..42c45804 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; + +/// +/// Interface for the repository for media library scans. +/// +public interface ILibraryScanRepository : IRepository, + IGetByIdRepositoryAction, + IInsertRepositoryAction, + IUpdateRepositoryAction +{ + /// + /// Gets the media library scans that belong to a media library identified by , for the previous month, from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the media library scans have a status, from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetRunningScansAsync(CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs index 63a9ca8d..f6da07f6 100644 --- a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs +++ b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs @@ -15,7 +15,7 @@ public interface IDataSeedService /// /// Sets up default authorization permissions in the system. /// - /// The Id of the admin admin user who will own these permissions. + /// The unique identifier of the admin admin user who will own these permissions. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken); @@ -23,7 +23,7 @@ public interface IDataSeedService /// /// Sets up default authorization roles in the system. /// - /// The Id of the admin user for whom roles will be set. + /// The unique identifier of the admin user for whom roles will be set. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken); @@ -31,7 +31,7 @@ public interface IDataSeedService /// /// Assigns admin role permissions to the admin user. /// - /// The Id of the admin user to receive admin role permissions. + /// The unique identifier of the admin user to receive admin role permissions. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken); @@ -39,7 +39,7 @@ public interface IDataSeedService /// /// Assigns admin role to the admin user. /// - /// The Id of the admin user to receive the admin role. + /// The unique identifier of the admin user to receive the admin role. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken); diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 4c702442..c7eb4276 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -2,13 +2,14 @@ using FluentValidation; using Lumina.Application.Common.Behaviors; using Lumina.Application.Common.DomainEvents; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Cancellation; using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books; using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +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.Queue; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Mediator; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; @@ -44,17 +45,13 @@ public static class ApplicationLayerServices services.AddScoped(); services.AddSingleton(); - services.AddSingleton(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + services.AddSingleton(); services.AddHostedService(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); return services; } diff --git a/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs b/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs index 96f72470..5dc68ac8 100644 --- a/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs @@ -18,7 +18,7 @@ public interface IAuthorizationService /// /// Determines whether the specified user has a specific permission. /// - /// The Id of the user for whom to check the permission. + /// The unique identifier of the user for whom to check the permission. /// The permission to check. /// Cancellation token that can be used to stop the execution. /// if the user has the specified permission, otherwise. @@ -27,7 +27,7 @@ public interface IAuthorizationService /// /// Determines whether the specified user belongs to a specific role. /// - /// The Id of the user for whom to check the role. + /// The unique identifier of the user for whom to check the role. /// The role to check. /// Cancellation token that can be used to stop the execution. /// if the user is in the specified role, otherwise. @@ -37,7 +37,7 @@ public interface IAuthorizationService /// Evaluates whether the specified user meets the conditions defined in the specified authorization policy. /// /// The type of authorization policy to evaluate. - /// The Id of the user for whom to evaluate the policy. + /// The unique identifier of the user for whom to evaluate the policy. /// Cancellation token that can be used to stop the execution. /// if the user satisfies the policy, otherwise. Task EvaluatePolicyAsync(Guid userId, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy; @@ -45,7 +45,7 @@ public interface IAuthorizationService /// /// Retrieves all authorization roles and permissions of a user identified by . /// - /// The id of the user for whom to retrieve the authorization roles and permissions. + /// The unique identifier of the user for whom to retrieve the authorization roles and permissions. /// Cancellation token that can be used to stop the execution. /// An containing either a , or an error. Task> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken); diff --git a/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/Common/Base/IAuthorizationPolicy.cs b/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/Common/Base/IAuthorizationPolicy.cs index 29d3228c..9121a9e0 100644 --- a/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/Common/Base/IAuthorizationPolicy.cs +++ b/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/Common/Base/IAuthorizationPolicy.cs @@ -14,7 +14,7 @@ public interface IAuthorizationPolicy /// /// Evaluates a policy for a user identified by . /// - /// The Id of the user for which to evaluate the policy. + /// The unique identifier of the user for which to evaluate the policy. /// Cancellation token that can be used to stop the execution. /// if the policy evaluation succeeds, otherwise. Task EvaluateAsync(Guid userId, CancellationToken cancellationToken); diff --git a/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs b/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs index 27e0df92..029bb64c 100644 --- a/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs @@ -7,6 +7,6 @@ namespace Lumina.Application.Common.Infrastructure.Models.Scanning; /// /// Model for tracking media library scans. /// -/// The Id of the media library scan to be tracked. -/// The Id of the username who initiated the media library scan. +/// The unique identifier of the media library scan to be tracked. +/// The unique identifier of the username who initiated the media library scan. public record MediaScanTrackerModel(Guid ScanId, Guid UserId); diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs index 7406368b..77962f7e 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs @@ -17,7 +17,9 @@ public static class GenreDtoMapping /// Converts to . /// /// The DTO to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this GenreDto dto) { return Genre.Create( @@ -29,7 +31,9 @@ public static class GenreDtoMapping /// Converts to a collection of . /// /// The DTOs to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs index b2aa43fc..bdf10078 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs @@ -40,7 +40,9 @@ public static class GenreEntityMapping /// Converts to . /// /// The repository entity to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this GenreEntity repositoryEntity) { return Genre.Create( @@ -52,7 +54,9 @@ public static class GenreEntityMapping /// Converts to a collection of . /// /// The repository entities to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs index d16b750f..6135cb4f 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs @@ -17,7 +17,9 @@ public static class TagDtoMapping /// Converts to . /// /// The DTO to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this TagDto dto) { return Tag.Create( @@ -29,7 +31,9 @@ public static class TagDtoMapping /// Converts to a collection of . /// /// The DTOs to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs index 802ef48d..50509924 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs @@ -40,7 +40,9 @@ public static class TagEntityMapping /// Converts to . /// /// The repository entity to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this TagEntity repositoryEntity) { return Tag.Create( @@ -52,7 +54,9 @@ public static class TagEntityMapping /// Converts to a collection of . /// /// The repository entities to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs index 5810f204..dac6ace3 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs @@ -18,7 +18,8 @@ public static class CancelLibraryScanRequestMapping public static CancelLibraryScanCommand ToCommand(this CancelLibraryScanRequest request) { return new CancelLibraryScanCommand( - request.Id + request.LibraryId, + request.ScanId ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 05f49fd9..92c979af 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; 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 System.Collections.Generic; using System.Linq; #endregion @@ -42,12 +44,14 @@ public static class LibraryEntityMapping /// Converts to . /// /// The repository entity to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this LibraryEntity repositoryEntity) { return Library.Create( LibraryId.Create(repositoryEntity.Id), - repositoryEntity.UserId, + UserId.Create(repositoryEntity.UserId), repositoryEntity.Title, repositoryEntity.LibraryType, repositoryEntity.ContentLocations.Select(contentLocation => contentLocation.Path), @@ -55,7 +59,8 @@ public static class LibraryEntityMapping repositoryEntity.IsEnabled, repositoryEntity.IsLocked, repositoryEntity.DownloadMedatadaFromWeb, - repositoryEntity.SaveMetadataInMediaDirectories + repositoryEntity.SaveMetadataInMediaDirectories, + repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList() ); } @@ -63,7 +68,9 @@ public static class LibraryEntityMapping /// Converts to a collection of . /// /// The repository entities to be converted. - /// The converted responses. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(library => library.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs index 427dc42b..75f59244 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -31,6 +31,18 @@ public static class LibraryMapping IsLocked = domainEntity.IsLocked, DownloadMedatadaFromWeb = domainEntity.DownloadMedatadaFromWeb, SaveMetadataInMediaDirectories = domainEntity.SaveMetadataInMediaDirectories, + LibraryScans = domainEntity.ScanIds.Select(scanId => new LibraryScanEntity() + { + Id = scanId.Value, + LibraryId = domainEntity.Id.Value, + UserId = domainEntity.UserId.Value, // rest of properties will be populated by EF Core + Status = default, + User = null!, + Library = null!, + 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/LibraryScanEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs new file mode 100644 index 00000000..85bee581 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanEntityMapping.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class LibraryScanEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static ErrorOr ToDomainEntity(this LibraryScanEntity repositoryEntity) + { + return LibraryScan.Create( + ScanId.Create(repositoryEntity.Id), + LibraryId.Create(repositoryEntity.LibraryId), + UserId.Create(repositoryEntity.UserId), + repositoryEntity.Status, + [] + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs new file mode 100644 index 00000000..6d4eb0d0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class LibraryScanMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static LibraryScanEntity ToRepositoryEntity(this LibraryScan domainEntity) + { + return new LibraryScanEntity + { + Id = domainEntity.Id.Value, + UserId = domainEntity.UserId.Value, + LibraryId = domainEntity.LibraryId.Value, + Status = domainEntity.Status, + User = null!, + Library = null!, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, + UpdatedBy = Guid.Empty + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index 5e915398..e5631a4a 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -137,7 +137,7 @@ public static class BookEntityMapping /// The repository entities to be converted. /// The converted domain entities. /// - /// An colection of containing either successfuly converted , or error messages. + /// An colection of containing either a collection of converted , or error messages. /// public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs index 16616979..4f72a943 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs @@ -19,7 +19,9 @@ public static class BookRatingDtoMapping /// Converts to . /// /// The DTO to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this BookRatingDto dto) { return BookRating.Create( @@ -34,7 +36,9 @@ public static class BookRatingDtoMapping /// Converts to a collection of . /// /// The DTOs to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs index da176890..c27d6f59 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs @@ -45,7 +45,9 @@ public static class BookRatingEntityMapping /// Converts to . /// /// The repository entity to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this BookRatingEntity repositoryEntity) { return BookRating.Create( @@ -60,7 +62,9 @@ public static class BookRatingEntityMapping /// Converts to a collection of . /// /// The repository entities to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs index ec4a3f66..1a8c485f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs @@ -33,7 +33,9 @@ public static class IsbnDtoMapping /// Converts to a collection of . /// /// The DTOs to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable dtos) { return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs index f889d41a..cadb3970 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs @@ -41,7 +41,9 @@ public static class IsbnEntityMapping /// Converts to . /// /// The repository entity to be converted. - /// The converted domain entity. + /// + /// An containing either a successfuly converted , or an error message. + /// public static ErrorOr ToDomainEntity(this IsbnEntity repositoryEntity) { return Isbn.Create( @@ -54,7 +56,9 @@ public static class IsbnEntityMapping /// Converts to a collection of . /// /// The repository entities to be converted. - /// The converted domain entities. + /// + /// An containing either a collection of converted , or an error message. + /// public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) { return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs index 8773d8c1..9cccdad1 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs @@ -10,7 +10,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; /// /// Command for deleting an authorization role. /// -/// The Id of the role. +/// The unique identifier of the role. [DebuggerDisplay("RoleId: {RoleId}")] public record DeleteRoleCommand( Guid RoleId diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs index 33c8daa8..df10ee28 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs @@ -45,9 +45,7 @@ public class DeleteRoleCommandHandler : IRequestHandler /// The request to be handled. /// Cancellation token that can be used to stop the execution. - /// - /// An containing either a successfuly deleted , or an error message. - /// + /// An representing either a successful operation, or an error. public async ValueTask> Handle(DeleteRoleCommand request, CancellationToken cancellationToken) { // only admins can delete authorization roles diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs index a8245a5d..98ce2684 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs @@ -12,7 +12,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; /// /// Command for updating an authorization role. /// -/// The Id of the role. +/// The unique identifier of the role. /// The name of the role. /// The collection of Ids of the permissions of the role. [DebuggerDisplay("RoleName: {RoleName}")] diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs index 5413a926..6050dc46 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs @@ -11,7 +11,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi /// /// Query for getting the authorization permissions of a role identified by . /// -/// The Id of the authorization role for which to get the list of permissions. +/// The unique identifier of the authorization role for which to get the list of permissions. [DebuggerDisplay("RoleId: {RoleId}")] public record GetRolePermissionsQuery( Guid RoleId diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index 3ca602e9..6e09a631 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -89,7 +89,8 @@ public class SetupApplicationCommandHandler : IRequestHandler createLibraryResult = Library.Create( - _currentUserService.UserId!.Value, + UserId.Create(_currentUserService.UserId!.Value), request.Title!, Enum.Parse(request.LibraryType!), request.ContentLocations!, @@ -98,7 +99,8 @@ public class AddLibraryCommandHandler : IRequestHandler getLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsError) - return getLibraryResult.Errors; - if (getLibraryResult.Value is null) - return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; - - // queue any domain events - foreach (IDomainEvent domainEvent in createLibraryResult.Value.PopDomainEvents()) - _domainEventsQueue.Enqueue(domainEvent); - - // retrieve the updated media library from the persistence medium and return it ErrorOr getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsError) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; + + // mark the media library as saved + createLibraryResult.Value.Save(); + + // queue any domain events + foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + return getCreatedLibraryResult.Value.ToResponse(); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs index 9a5da911..1502b0dd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs @@ -6,6 +6,6 @@ using Mediator; namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; /// -/// Command for cancelling the previously started scan of all media libraries. +/// Command for canceling the previously started scan of all media libraries. /// public record CancelLibrariesScanCommand : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index d5452457..93c46a87 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -1,8 +1,18 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +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; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Mediator; +using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -10,33 +20,88 @@ using System.Threading.Tasks; namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; /// -/// Handler for the command for cancelling the scan of all media libraries. +/// Handler for the command for canceling the scan of all media libraries. /// public class CancelLibrariesScanCommandHandler : IRequestHandler> { private readonly ICurrentUserService _currentUserService; - private readonly IMediaLibrariesScanTracker _librariesScanTracker; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IUnitOfWork _unitOfWork; /// /// Initializes a new instance of the class. /// /// Injected service to retrieve the current user information. - /// Injected service for scanning media libraries. - public CancelLibrariesScanCommandHandler(ICurrentUserService currentUserService, IMediaLibrariesScanTracker librariesScanTracker) + /// Injected service for authorization related functionality. + /// Injected service for the queue of domain events. + /// Injected unit of work for interacting with the data access layer repositories. + public CancelLibrariesScanCommandHandler( + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IDomainEventsQueue domainEventsQueue, + IUnitOfWork unitOfWork) { _currentUserService = currentUserService; - _librariesScanTracker = librariesScanTracker; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _unitOfWork = unitOfWork; } /// - /// Handles the command for cancelling the scan of all media libraries. + /// Handles the command for canceling the scan of all media libraries. /// /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async ValueTask> Handle(CancelLibrariesScanCommand request, CancellationToken cancellationToken) { - _librariesScanTracker.CancelUserScans(_currentUserService.UserId!.Value); + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // get the running library scans of the current user from the repository + ErrorOr> getRunningLibraryScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); + if (getRunningLibraryScansResult.IsError) + return getRunningLibraryScansResult.Errors; + + // filter the library scans to process + List authorizedLibraryScans = []; + // admins can see all library scans + if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) + authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value); + else // for regular users, only take the library scans that belong to them + authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == _currentUserService.UserId)); + + // convert persistence library scans to domain entities + IEnumerable> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities(); + + List domainEvents = []; + + // for each library scan, perform the cancellation + foreach (ErrorOr libraryScanDomainResult in libraryScansDomainResult) + { + if (libraryScanDomainResult.IsError) + return libraryScanDomainResult.Errors; + + // cancel the media library scan + ErrorOr cancelScanResult = libraryScanDomainResult.Value.CancelScan(); + if (cancelScanResult.IsError) + return cancelScanResult.Errors; + + // update the status of the library scan in the repository + ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsError) + return updateLibraryScanResult.Errors; + + // collect all the domain events created during this library scan start + domainEvents.AddRange(libraryScanDomainResult.Value.GetDomainEvents()); + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // queue any domain events + foreach (IDomainEvent domainEvent in domainEvents) + _domainEventsQueue.Enqueue(domainEvent); + return await ValueTask.FromResult(Result.Success); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs index 7510cc8b..5171a9cb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs @@ -8,10 +8,12 @@ using System.Diagnostics; namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; /// -/// Command for cancelling the scan of a media library by its Id. +/// Command for canceling the scan of a media library. /// -/// The Id of the media library whose scan is cancelled. -[DebuggerDisplay("Id: {Id}")] +/// The unique identifier of the media library whose scan is cancelled. +/// The unique identifier of the scan to cancel. +[DebuggerDisplay("LibraryId: {LibraryId}; ScanId: {ScanId}")] public record CancelLibraryScanCommand( - Guid Id + Guid LibraryId, + Guid ScanId ) : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs index eeea9cdd..56f4ef7f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs @@ -3,48 +3,93 @@ using ErrorOr; 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; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Mediator; -using System; -using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; /// -/// Handler for the command for cancelling the scan of a media library. +/// Handler for the command for canceling the scan of a media library. /// public class CancelLibraryScanCommandHandler : IRequestHandler> { - private readonly IMediaLibraryScanningService _mediaLibraryScanningService; + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; /// /// Initializes a new instance of the class. /// - /// Injected service for scanning media libraries. - public CancelLibraryScanCommandHandler(IMediaLibraryScanningService mediaLibraryScanningService) + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected unit of work for interacting with the data access layer repositories. + public CancelLibraryScanCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IUnitOfWork unitOfWork) { - _mediaLibraryScanningService = mediaLibraryScanningService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _unitOfWork = unitOfWork; } /// - /// Handles the command for cancelling the scan of a media library. + /// Handles the command for canceling the scan of a media library. /// /// The request to be handled. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async ValueTask> Handle(CancelLibraryScanCommand request, CancellationToken cancellationToken) { - _mediaLibraryScanningService.CancelScan(request.Id); + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // get the library scan from the repository + ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(request.ScanId, cancellationToken).ConfigureAwait(false); + if (getLibraryScansResult.IsError) + return getLibraryScansResult.Errors; + if (getLibraryScansResult.Value is null) + return DomainErrors.LibraryScanning.LibraryScanNotFound; + + // if the user that wants to scan the library is not an Admin or is not the owner of the library, they do not have the right to scan it + if (getLibraryScansResult.Value.UserId != _currentUserService.UserId || + !await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // convert the repository scan to a domain object + ErrorOr libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsError) + return libraryScanDomainResult.Errors; + + // cancel the media library scan + ErrorOr cancelScanResult = libraryScanDomainResult.Value.CancelScan(); + if (cancelScanResult.IsError) + return cancelScanResult.Errors; + + // update the status of the library scan in the repository + ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsError) + return updateLibraryScanResult.Errors; + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // queue any domain events + foreach (IDomainEvent domainEvent in libraryScanDomainResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + return await ValueTask.FromResult(Result.Success); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs index 72990614..a2fcc2f9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs @@ -16,8 +16,11 @@ public class CancelLibraryScanCommandValidator : AbstractValidator public CancelLibraryScanCommandValidator() { - RuleFor(x => x.Id) + RuleFor(x => x.LibraryId) .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + RuleFor(x => x.ScanId) + .NotEmpty().WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs index af7d609f..0f1932eb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommand.cs @@ -10,7 +10,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary /// /// Command for deleting a media library by its Id. /// -/// The Id of the media library to delete. +/// The unique identifier of the media library to delete. [DebuggerDisplay("Id: {Id}")] public record DeleteLibraryCommand( Guid Id diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index 462787c8..64cc22a8 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -7,7 +7,6 @@ using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Mediator; @@ -53,9 +52,7 @@ public class DeleteLibraryCommandHandler : IRequestHandler /// The request to be handled. /// Cancellation token that can be used to stop the execution. - /// - /// An containing either a successfuly created , or an error message. - /// + /// An representing either a successful operation, or an error. public async ValueTask> Handle(DeleteLibraryCommand request, CancellationToken cancellationToken) { // get the library with the specified id from the repository @@ -82,7 +79,7 @@ public class DeleteLibraryCommandHandler : IRequestHandler /// Initializes a new instance of the class. /// /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. - /// Injected service for scanning media libraries. + /// Injected service for the queue of domain events. /// Injected unit of work for interacting with the data access layer repositories. public ScanLibrariesCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, - IMediaLibraryScanningService libraryScanningService, + IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork) { _authorizationService = authorizationService; _currentUserService = currentUserService; - _libraryScanningService = libraryScanningService; + _domainEventsQueue = domainEventsQueue; _unitOfWork = unitOfWork; } @@ -56,8 +59,10 @@ public class ScanLibrariesCommandHandler : IRequestHandlerAn representing either a successful operation, or an error. public async ValueTask>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken) { - // get all media libraries that are enabled and unlocked from the persistence medium ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // get all media libraries that are enabled and unlocked from the persistence medium ErrorOr> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); if (getLibrariesResult.IsError) return getLibrariesResult.Errors; @@ -70,14 +75,58 @@ public class ScanLibrariesCommandHandler : IRequestHandler libraryResult.Value.UserId.Value == _currentUserService.UserId!.Value); List responses = []; + List domainEvents = []; + // for each library, start the scan foreach (ErrorOr domainLibraryResult in domainEntitiesResult) { if (domainLibraryResult.IsError) return domainLibraryResult.Errors; - Guid scanId = await _libraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false); - responses.Add(new ScanLibraryResponse(scanId, domainLibraryResult.Value.Id.Value)); + + // get the past month's scans for this library + ErrorOr> pastLibraryScansResult = + await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + if (pastLibraryScansResult.IsError) + return pastLibraryScansResult.Errors; + + // convert the repository scans history to domain objects + IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); + foreach (ErrorOr pastLibraryScanDomainResult in pastLibraryScansDomainResult) + if (pastLibraryScanDomainResult.IsError) + return pastLibraryScanDomainResult.Errors; + + // start the media library scan + ErrorOr libraryScanResult = LibraryScan.Create( + LibraryId.Create(domainLibraryResult.Value.Id.Value), + UserId.Create(_currentUserService.UserId!.Value), + [.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)] + ); + if (libraryScanResult.IsError) + return libraryScanResult.Errors; + + ErrorOr startScanResult = libraryScanResult.Value.QueueScan(); + // when the user demands a "scan all libraries" action, it would be annoying to receive an error if a library is already being scanned. + // instead, just don't start the scan on such a library, and start it on the others that can be started + if (startScanResult.IsError) + continue; + + // add the library scan to the persistence medium + ErrorOr insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertLibraryScanResult.IsError) + return insertLibraryScanResult.Errors; + + // collect all the domain events created during this library scan start + domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents()); + + responses.Add(new ScanLibraryResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value)); } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // queue any domain events + foreach (IDomainEvent domainEvent in domainEvents) + _domainEventsQueue.Enqueue(domainEvent); + return responses; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs index c31948a9..07781126 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs @@ -10,7 +10,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; /// /// Command for initiating the scan of a media library. /// -/// The Id of the library to scan. +/// The unique identifier of the library to scan. public record ScanLibraryCommand( Guid Id ) : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs index 30fb6df9..58b4b9cd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -3,14 +3,20 @@ using ErrorOr; 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; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.MediaLibrary.Management; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Mediator; -using System; +using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -26,25 +32,25 @@ public class ScanLibraryCommandHandler : IRequestHandler /// Initializes a new instance of the class. /// /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. - /// Injected service for scanning media libraries. + /// Injected service for the queue of domain events. /// Injected unit of work for interacting with the data access layer repositories. public ScanLibraryCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, - IMediaLibraryScanningService mediaLibraryScanningService, + IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork) { _authorizationService = authorizationService; _currentUserService = currentUserService; - _mediaLibraryScanningService = mediaLibraryScanningService; + _domainEventsQueue = domainEventsQueue; _unitOfWork = unitOfWork; } @@ -56,8 +62,10 @@ public class ScanLibraryCommandHandler : IRequestHandlerAn representing either a successful operation, or an error. public async ValueTask> Handle(ScanLibraryCommand request, CancellationToken cancellationToken) { - // get the media library from the persistence medium ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // get the media library from the persistence medium ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError) return getLibraryResult.Errors; @@ -65,7 +73,7 @@ public class ScanLibraryCommandHandler : IRequestHandler domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); - if (domainLibraryResult.IsError) return domainLibraryResult.Errors; - // start the media library scan - Guid scanId = await _mediaLibraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false); - return new ScanLibraryResponse(scanId, domainLibraryResult.Value.Id.Value); + // get the past month's scans for this library + ErrorOr> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + if (pastLibraryScansResult.IsError) + return pastLibraryScansResult.Errors; + + // convert the repository scans history to domain objects + IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); + foreach (ErrorOr pastLibraryScanDomainResult in pastLibraryScansDomainResult) + if (pastLibraryScanDomainResult.IsError) + return pastLibraryScanDomainResult.Errors; + + // queue the media library scan + ErrorOr libraryScanResult = LibraryScan.Create( + LibraryId.Create(request.Id), + UserId.Create(_currentUserService.UserId!.Value), + [.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)] + ); + if (libraryScanResult.IsError) + return libraryScanResult.Errors; + + ErrorOr queueScanResult = libraryScanResult.Value.QueueScan(); + if (queueScanResult.IsError) + return queueScanResult.Errors; + + // add the library scan to the persistence medium + ErrorOr insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertLibraryScanResult.IsError) + return insertLibraryScanResult.Errors; + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // queue any domain events + foreach (IDomainEvent domainEvent in libraryScanResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return new ScanLibraryResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs index a4a4ce69..a6ea88f6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs @@ -11,8 +11,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// /// Command for updating a media library. /// -/// The Id of the media library. -/// The Id of the user owning the media library. +/// The unique identifier of the media library. +/// The unique identifier of the user owning the media library. /// The title of the media library. /// The type of the media library. /// The file system paths of the directories where the media library elements are located. 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 6f04b336..2f023a52 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -16,8 +16,11 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File 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 Mediator; using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -83,13 +86,14 @@ public class UpdateLibraryCommandHandler : IRequestHandler(); ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsError) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; + // if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it if (getLibraryResult.Value.UserId != _currentUserService.UserId || (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) && @@ -99,7 +103,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler createLibraryResult = Library.Create( LibraryId.Create(request.Id), - request.OwnerId, + UserId.Create(request.OwnerId), request.Title!, Enum.Parse(request.LibraryType!), request.ContentLocations!, @@ -107,7 +111,8 @@ public class UpdateLibraryCommandHandler : IRequestHandler ScanId.Create(libraryScan.Id)).ToList() ); if (createLibraryResult.IsError) return createLibraryResult.Errors; @@ -120,16 +125,20 @@ public class UpdateLibraryCommandHandler : IRequestHandler getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsError) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; + + // mark the media library as saved + createLibraryResult.Value.Save(); + + // queue any domain events + foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + return getCreatedLibraryResult.Value.ToResponse(); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index 5159bb3e..7028f53c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -111,7 +111,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler /// Saves the cover image of a media library to the internal media directory. /// - /// The Id of the library for which to save the cover image. + /// The unique identifier of the library for which to save the cover image. /// The file path of the image file that will be copied to the media directory. /// Cancellation token that can be used to stop the execution. /// @@ -200,14 +200,10 @@ public class LibrarySavedDomainEventHandler : INotificationHandler - /// Saves the cover image of a media library to the internal media directory. + /// Deletes the cover image from the media directory. /// - /// The Id of the library for which to save the cover image. - /// The file path of the image file that will be copied to the media directory. - /// Cancellation token that can be used to stop the execution. - /// - /// An containing either the location of the new cover image, or an error message. - /// + /// The path where the library content is located. + /// An representing either a successful operation, or an error. private ErrorOr DeleteCoverImageFromMediaDirectory(string libraryPath) { diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs new file mode 100644 index 00000000..3614631d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +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.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the event raised when a media library scan is cancelled. +/// +public class LibraryScanCancelledDomainEventHandler : INotificationHandler +{ + private readonly IMediaLibraryScanningService _mediaLibraryScanningService; + private readonly ILibraryScanRepository _libraryScanRepository; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for scanning media libraries. + /// Injected unit of work for interacting with the data access layer repositories. + public LibraryScanCancelledDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IUnitOfWork unitOfWork) + { + _mediaLibraryScanningService = mediaLibraryScanningService; + _libraryScanRepository = unitOfWork.GetRepository(); + } + + /// + /// Handles the event raised when a media library scan is cancelled. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask Handle(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken) + { + // get the library scan from the repository + ErrorOr getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryScansResult.IsError) + throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); + if (getLibraryScansResult.Value is null) + throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); + + // convert the repository scan to a domain object + ErrorOr libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsError) + throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); + + // cancel the media library scan + ErrorOr cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value); + if (cancelScanResult.IsError) + throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs new file mode 100644 index 00000000..5c727c7d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +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.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the event raised when a media library scan has failed. +/// +public class LibraryScanFailedDomainEventHandler : INotificationHandler +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public LibraryScanFailedDomainEventHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the event raised when a media library scan has failed. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask Handle(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken) + { + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // get the library scan from the repository + ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryScansResult.IsError) + throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); + if (getLibraryScansResult.Value is null) + throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); + + // convert the repository scan to a domain object + ErrorOr libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsError) + throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); + + // mark the media library scan as failed + ErrorOr failScanResult = libraryScanDomainResult.Value.FailScan(); + // we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs might trigger this domain event, + // trying to set as failed a scan that has already been marked as failed by a concurrent job + if (!failScanResult.IsError) + { + // update the status of the library scan in the repository + ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsError) + throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs new file mode 100644 index 00000000..7846699e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the event raised when a media library's scan progress changes. +/// +public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler +{ + /// + /// Handles the event raised when a media library's scan progress changes. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) + { + await Task.CompletedTask; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs new file mode 100644 index 00000000..4926a4bb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +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; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the event raised when a media library scan is queued. +/// +public class LibraryScanQueuedDomainEventHandler : INotificationHandler +{ + private readonly IMediaLibraryScanningService _mediaLibraryScanningService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for scanning media libraries. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the queue of domain events. + /// Injected unit of work for interacting with the data access layer repositories. + public LibraryScanQueuedDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork) + { + _mediaLibraryScanningService = mediaLibraryScanningService; + _domainEventsQueue = domainEventsQueue; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the event raised when a media library scan is queued. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask Handle(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken) + { + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // get the library scan that was queued, from the repository + ErrorOr getLibraryScanResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryScanResult.IsError || getLibraryScanResult.Value is null) + throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); + + // convert the repository entity to a domain entity + ErrorOr libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); + if (libraryScanDomainResult.IsError) + throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); + + // start the media library scan + ErrorOr startScanResult = await _mediaLibraryScanningService.StartScanAsync( + libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMedatadaFromWeb, cancellationToken).ConfigureAwait(false); + if (startScanResult.IsError) + throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors); + + // queue any domain events + foreach (IDomainEvent queuedDomainEvent in libraryScanDomainResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(queuedDomainEvent); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs new file mode 100644 index 00000000..b6fcfa91 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the event raised when a media library scan is started. +/// +public class LibraryScanStartedDomainEventHandler : INotificationHandler +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public LibraryScanStartedDomainEventHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the event raised when a media library scan is started. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask Handle(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken) + { + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + + // update the status of the library scan in the repository + ErrorOr updateLibraryScanResult = await libraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateLibraryScanResult.IsError) + throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs index fb365a19..3775b7c7 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQuery.cs @@ -11,7 +11,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; /// /// Query for getting a media library by its Id. /// -/// The Id of the media library to get. +/// The unique identifier of the media library to get. [DebuggerDisplay("Id: {Id}")] public record GetLibraryQuery( Guid Id diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/MediaLibrariesScanTracker.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs similarity index 75% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/MediaLibrariesScanTracker.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs index cac7e9b4..3a07f698 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/MediaLibrariesScanTracker.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs @@ -1,16 +1,17 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Models.Scanning; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using System; using System.Collections.Concurrent; using System.Threading; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Cancellation; /// -/// Tracker used for in-progress media library scans. +/// Tracker used for canceling in-memory media library scans. /// -internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposable +internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancellationTracker, IDisposable { private readonly ConcurrentDictionary _runningScans = new(); private bool _disposed; @@ -18,8 +19,8 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab /// /// Registers a new scan operation for tracking. /// - /// The Id of the scan operation to track. - /// The Id of the user who initiated the scan to track. + /// The unique identifier of the scan operation to track. + /// The unique identifier of the user who initiated the scan to track. public void RegisterScan(Guid scanId, Guid userId) { _runningScans.TryAdd(new MediaScanTrackerModel(scanId, userId), new CancellationTokenSource()); @@ -28,8 +29,8 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab /// /// Gets the cancellation token for a scan identified by and . /// - /// The Id of the scan to get the cancellation token for<./param> - /// The Id of the user who initiated the scan for which to get the cancellation token. + /// The unique identifier of the scan to get the cancellation token for<./param> + /// The unique identifier of the user who initiated the scan for which to get the cancellation token. /// A cancellation token for the specified scan. public CancellationToken GetTokenForScan(Guid scanId, Guid userId) { @@ -41,8 +42,8 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab /// /// Cancels a scan identified by and . /// - /// The Id of the scan operation to cancel. - /// The Id of the user requesting the cancellation. + /// The unique identifier of the scan operation to cancel. + /// The unique identifier of the user requesting the cancellation. public void CancelScan(Guid scanId, Guid userId) { foreach (MediaScanTrackerModel key in _runningScans.Keys) @@ -63,7 +64,7 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab /// /// Cancels all active scan operations for a user identified by . /// - /// The Id of the user whose scans should be cancelled. + /// The unique identifier of the user whose scans should be canceled. public void CancelUserScans(Guid userId) { foreach (MediaScanTrackerModel key in _runningScans.Keys) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaLibraryScanningService.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaLibraryScanningService.cs deleted file mode 100644 index f0ff4ba1..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaLibraryScanningService.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using System; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; - -/// -/// Interface for the service used to scan a media library. -/// -public interface IMediaLibraryScanningService -{ - /// - /// Starts the scan of . - /// - /// The media library to scan. - /// Cancellation token that can be used to stop the execution. - /// The Id of the media library scan. - Task StartScanAsync(Library library, CancellationToken cancellationToken); - - /// - /// Cancels the scan identified by . - /// - /// The Id of the scan to cancel. - void CancelScan(Guid scanId); -} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs index 57853c67..ac6665a1 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs @@ -1,5 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +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.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Payloads; using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Enums.MediaLibrary; @@ -7,6 +12,12 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Mediator; +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Threading; @@ -18,20 +29,26 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for discovering file system items. /// -internal class FileSystemDiscoveryJob : MediaLibraryScanJob +internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob { private readonly IDirectoryService _directoryService; private readonly IFileService _fileService; + private readonly IServiceScopeFactory _serviceScopeFactory; /// /// Initializes a new instance of the class. /// /// Injected service for handling directories. /// Injected service for handling files. - public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService) + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details. + /// + public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService, IServiceScopeFactory serviceScopeFactory) { _directoryService = directoryService; _fileService = fileService; + _serviceScopeFactory = serviceScopeFactory; } /// @@ -44,9 +61,45 @@ internal class FileSystemDiscoveryJob : MediaLibraryScanJob if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) { Status = LibraryScanJobStatus.Running; + + Console.WriteLine("started file discovering"); + // see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService(); + IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); + ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + + // get the library from the repository + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError || getLibraryResult.Value is null) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // convert it to a domain object + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + // set the initial progress of the scan job + ErrorOr scanJobProgressResult = ScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + + _jobProgress = scanJobProgressResult.Value; + await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + Console.WriteLine($"Reporting job progress in file discovery. Total: {_jobProgress.TotalItems}; Completed: {_jobProgress.CompletedItems}; Current: {_jobProgress.CurrentOperation}"); // recursively get the file system tree for each of the media library content locations List contentLocationTrees = []; - foreach (FileSystemPathId contentLocation in Library.ContentLocations) + foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) { cancellationToken.ThrowIfCancellationRequested(); ErrorOr treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken); @@ -57,16 +110,27 @@ internal class FileSystemDiscoveryJob : MediaLibraryScanJob } else contentLocationTrees.Add(treeResult.Value); + + // increment the number of processed elements progress + scanJobProgressResult = ScanJobProgress.Create( + scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles"); + if (scanJobProgressResult.IsError) + { + await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + return; + } + await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); } + Console.WriteLine("ended file discovering"); Status = LibraryScanJobStatus.Completed; // call each linked child with the obtained payload - foreach (MediaLibraryScanJob children in Children) + foreach (IMediaLibraryScanJob children in Children) await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { - Status = LibraryScanJobStatus.Cancelled; + Status = LibraryScanJobStatus.Canceled; throw; } } @@ -77,7 +141,7 @@ internal class FileSystemDiscoveryJob : MediaLibraryScanJob /// The identifier of the root path from which to build the tree. /// Specifies whether hidden files and directories should be included in the tree. /// An containing either a , or an error. - public ErrorOr BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default) + private ErrorOr BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default) { // validate the path and get the root directory node ErrorOr rootDirectoryResult = Directory.Create(path, path.Path, Optional.None(), Optional.None()); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs index eaad25ec..124b05b0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using System; using System.Collections.Generic; using System.Threading; @@ -11,7 +12,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for comparing hashes. /// -internal class HashComparerJob : MediaLibraryScanJob +internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob { /// public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) @@ -23,16 +24,24 @@ internal class HashComparerJob : MediaLibraryScanJob if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) { Status = LibraryScanJobStatus.Running; + Console.WriteLine("started file hashing"); List ints = [1, 2, 3]; + while (!cancellationToken.IsCancellationRequested) + { + await Task.Delay(1111, cancellationToken).ConfigureAwait(false); + Console.WriteLine("ticking"); + cancellationToken.ThrowIfCancellationRequested(); + } Status = LibraryScanJobStatus.Completed; + Console.WriteLine("ended file hashing"); // call each linked child with the obtained payload - foreach (MediaLibraryScanJob children in Children) + foreach (IMediaLibraryScanJob children in Children) await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { - Status = LibraryScanJobStatus.Cancelled; + Status = LibraryScanJobStatus.Canceled; throw; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs index 944fb537..50161cd6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using System; using System.Collections.Generic; using System.Threading; @@ -11,7 +12,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for retrieving persistence data from any eventual previous scans. /// -internal class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob +internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob { /// public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) @@ -23,16 +24,18 @@ internal class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) { Status = LibraryScanJobStatus.Running; + Console.WriteLine("started repo discovering"); List ints = [1, 2, 3]; Status = LibraryScanJobStatus.Completed; + Console.WriteLine("ended repo discovering"); // call each linked child with the obtained payload - foreach (MediaLibraryScanJob children in Children) + foreach (IMediaLibraryScanJob children in Children) await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { - Status = LibraryScanJobStatus.Cancelled; + Status = LibraryScanJobStatus.Canceled; throw; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs index 3b67ac13..9329ca06 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using System; using System.Collections.Generic; using System.Threading; @@ -12,7 +13,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for retrieving written content metadata from GoodReads. /// -internal class GoodReadsMetadataScrapJob : MediaLibraryScanJob +internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob { /// public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) @@ -24,16 +25,18 @@ internal class GoodReadsMetadataScrapJob : MediaLibraryScanJob if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count) { Status = LibraryScanJobStatus.Running; + Console.WriteLine("started goodreads metadata"); List ints = [1, 2, 3]; Status = LibraryScanJobStatus.Completed; + Console.WriteLine("ended goodreads metadata"); // call each linked child with the obtained payload - foreach (MediaLibraryScanJob children in Children) + foreach (IMediaLibraryScanJob children in Children) await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { - Status = LibraryScanJobStatus.Cancelled; + Status = LibraryScanJobStatus.Canceled; throw; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaLibraryScanningService.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaLibraryScanningService.cs deleted file mode 100644 index fe43dc86..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaLibraryScanningService.cs +++ /dev/null @@ -1,84 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; - -/// -/// Service used to scan a media library. -/// -internal class MediaLibraryScanningService : IMediaLibraryScanningService -{ - private readonly IMediaLibrariesScanQueue _mediaScanQueue; - private readonly IMediaLibraryScannerFactory _libraryScannerFactory; - private readonly ICurrentUserService _currentUserService; - private readonly IMediaLibrariesScanTracker _librariesScanTracker; - - /// - /// Initializes a new instance of the class. - /// - /// Injected queue used for processing media libraries scan jobs. - /// Injected factory for creating media library scanners. - public MediaLibraryScanningService( - IMediaLibrariesScanQueue mediaScanQueue, - IMediaLibraryScannerFactory libraryScannerFactory, - IMediaLibrariesScanTracker librariesScanTracker, - ICurrentUserService currentUserService) - { - _mediaScanQueue = mediaScanQueue; - _libraryScannerFactory = libraryScannerFactory; - _currentUserService = currentUserService; - _librariesScanTracker = librariesScanTracker; - } - - /// - /// Starts the scan of . - /// - /// The media library to scan. - /// Cancellation token that can be used to stop the execution. - /// The Id of the media library scan. - public async Task StartScanAsync(Library library, CancellationToken cancellationToken) - { - Guid scanId = Guid.NewGuid(); - _librariesScanTracker.RegisterScan(scanId, _currentUserService.UserId!.Value); - - try - { - // link the user's cancellation token with the scan's token - CancellationTokenSource linkedSource = CancellationTokenSource - .CreateLinkedTokenSource(cancellationToken, _librariesScanTracker.GetTokenForScan(scanId, _currentUserService.UserId!.Value)); - - // get a media library scanner for the provided media library type - IMediaTypeScanner scanner = _libraryScannerFactory.CreateLibraryScanner(library.LibraryType); - // get the list of scan jobs for the retrieved scanner - IEnumerable jobs = scanner.CreateScanJobsForLibrary(library); - // enqueue the jobs on the channel from where they will be processed - foreach (MediaLibraryScanJob job in jobs) - { - job.ScanId = scanId; - job.UserId = _currentUserService.UserId!.Value; - await _mediaScanQueue.Writer.WriteAsync(job, linkedSource.Token).ConfigureAwait(false); - } - } - catch (NotImplementedException) { } - return scanId; - } - - /// - /// Cancels the scan identified by . - /// - /// The Id of the scan to cancel. - public void CancelScan(Guid scanId) - { - _librariesScanTracker.CancelScan(scanId, _currentUserService.UserId!.Value); - } -} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/IMediaLibrariesScanQueue.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/IMediaLibrariesScanQueue.cs deleted file mode 100644 index c9ceb29c..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/IMediaLibrariesScanQueue.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; -using System.Threading.Channels; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; - -/// -/// Interface for the message queue for handling instances. -/// -internal interface IMediaLibrariesScanQueue -{ - /// - /// Gets the writer for the queue, allowing producers to enqueue instances. - /// - public ChannelWriter Writer { get; } - - /// - /// Gets the reader for the queue, allowing consumers to dequeue instances. - /// - public ChannelReader Reader { get; } -} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs index 180bdd52..3d7400dc 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs @@ -1,30 +1,30 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; using System.Threading.Channels; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; /// -/// Provides an in-memory message queue for handling instances. +/// Provides an in-memory message queue for handling instances. /// internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue { - private readonly Channel _channel = Channel.CreateUnbounded(); + private readonly Channel _channel = Channel.CreateUnbounded(new UnboundedChannelOptions + { + SingleWriter = false, + SingleReader = false, + AllowSynchronousContinuations = true + }); /// - /// Gets the writer for the queue, allowing producers to enqueue instances. + /// Gets the writer for the queue, allowing producers to enqueue instances. /// - public ChannelWriter Writer - { - get { return _channel.Writer; } - } + public ChannelWriter Writer => _channel.Writer; /// - /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// Gets the reader for the queue, allowing consumers to dequeue instances. /// - public ChannelReader Reader - { - get { return _channel.Reader; } - } + public ChannelReader Reader => _channel.Reader; } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs index acd83cb5..8253701a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs @@ -1,7 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Utilities; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +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.Queue; using Microsoft.Extensions.Hosting; using System; using System.Threading; @@ -16,16 +17,17 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queu internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService { private readonly IMediaLibrariesScanQueue _mediaScanQueue; - private readonly IMediaLibrariesScanTracker _librariesScanTracker; + private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; /// /// Initializes a new instance of the class. /// /// Injected queue used for processing media libraries scan jobs. - public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanTracker librariesScanTracker) + /// Injected service for scanning media libraries. + public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker) { _mediaScanQueue = mediaScanQueue; - _librariesScanTracker = librariesScanTracker; + _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; } /// @@ -38,10 +40,10 @@ internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService // remark: since only top level scan jobs are placed on the bus, but they themselves trigger the execution of their children jobs, and so on, // their completion should not be awaited here due to some of them being long running tasks; therefor they are just fired synchronously // without being awaited, while still properly handling any exceptions they might throw in their asynchronous execution - await foreach (MediaLibraryScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + await foreach (IMediaLibraryScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) { // get the cancellation token that was associated with this library scan - CancellationToken scanToken = _librariesScanTracker.GetTokenForScan(mediaScanJob.ScanId, mediaScanJob.UserId); + CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(mediaScanJob.ScanId.Value, mediaScanJob.UserId.Value); // create linked token to handle both scan cancellation and service shutdown CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, scanToken); mediaScanJob.ExecuteAsync(Guid.NewGuid(), new { }, linkedSource.Token).FireAndForgetSafeAsync(() => linkedSource.Dispose()); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs deleted file mode 100644 index 18038c96..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs +++ /dev/null @@ -1,12 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent; - -/// -/// Interface defining a media library scanner for a books media library type. -/// -internal interface IBookLibraryTypeScanner : IMediaTypeScanner -{ -} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index 6829651c..88e5e6a2 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -81,7 +81,8 @@ public class RegisterUserCommandHandler : IRequestHandler /// Command for updating the authorization role and permissions of a user. /// -/// The Id of the user. -/// The Id of the role. +/// The unique identifier of the user. +/// The unique identifier of the role. /// The collection of Ids of the permissions of the user. [DebuggerDisplay("UserId: {UserId}")] public record UpdateUserRoleAndPermissionsCommand( diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs index a745c4b1..95c9f139 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs @@ -125,7 +125,8 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler permission.Id == permissionId), User = userToUpdate - }).ToList() + }).ToList(), + LibraryScans = userToUpdate.LibraryScans }; // save changes and return result diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs index e58d7810..24d34c3f 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQuery.cs @@ -11,7 +11,7 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho /// /// Query for retrieving the authorization roles and permissions of an account. /// -/// The Id of the user for whom to get the authorization. +/// The unique identifier of the user for whom to get the authorization. [DebuggerDisplay("UserId: {UserId}")] public record GetAuthorizationQuery( Guid? UserId diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs index f645e3c6..5838f920 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs @@ -12,7 +12,7 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP /// /// Query for retrieving the authorization permissions of a user identified by . /// -/// The Id of the user for whom to get the authorization permissions. +/// The unique identifier of the user for whom to get the authorization permissions. [DebuggerDisplay("UserId: {UserId}")] public record GetUserPermissionsQuery( Guid? UserId diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs index ded01e30..ab3a32fd 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs @@ -11,7 +11,7 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR /// /// Query for retrieving the authorization role of a user identified by . /// -/// The Id of the user for whom to get the authorization role. +/// The unique identifier of the user for whom to get the authorization role. [DebuggerDisplay("UserId: {UserId}")] public record GetUserRoleQuery( Guid? UserId diff --git a/src/Lumina.Contracts/DTO/Authentication/PermissionDto.cs b/src/Lumina.Contracts/DTO/Authentication/PermissionDto.cs index c3d69af8..11eda2ed 100644 --- a/src/Lumina.Contracts/DTO/Authentication/PermissionDto.cs +++ b/src/Lumina.Contracts/DTO/Authentication/PermissionDto.cs @@ -9,7 +9,7 @@ namespace Lumina.Contracts.DTO.Authentication; /// /// Data transfer object for an authorization permission. /// -/// The Id of the permission. +/// The unique identifier of the permission. /// The name of the permission. [DebuggerDisplay("Id: {Id}, PermissionName: {PermissionName}")] public record PermissionDto( diff --git a/src/Lumina.Contracts/DTO/Authentication/RoleDto.cs b/src/Lumina.Contracts/DTO/Authentication/RoleDto.cs index e59df0fa..7ecd46ce 100644 --- a/src/Lumina.Contracts/DTO/Authentication/RoleDto.cs +++ b/src/Lumina.Contracts/DTO/Authentication/RoleDto.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.DTO.Authentication; /// /// Data transfer object for an authorization role. /// -/// The Id of the role. +/// The unique identifier of the role. /// The name of the role. [DebuggerDisplay("Id: {Id}, RoleName: {RoleName}")] public record RoleDto( diff --git a/src/Lumina.Contracts/Requests/Authorization/DeleteRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/DeleteRoleRequest.cs index 83b4bb7f..653ebb32 100644 --- a/src/Lumina.Contracts/Requests/Authorization/DeleteRoleRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/DeleteRoleRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// Represents a request for deleting an authorization role. /// -/// The Id of the role. Required. +/// The unique identifier of the role. Required. [DebuggerDisplay("RoleId: {RoleId}")] public record DeleteRoleRequest( Guid? RoleId diff --git a/src/Lumina.Contracts/Requests/Authorization/GetAuthorizationRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetAuthorizationRequest.cs index b41ee6d2..ff9bb716 100644 --- a/src/Lumina.Contracts/Requests/Authorization/GetAuthorizationRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/GetAuthorizationRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// Represents the request model for retrieving account authorization information. /// -/// The Id of the user for whom to get the authorization. Required. +/// The unique identifier of the user for whom to get the authorization. Required. public record GetAuthorizationRequest( Guid? UserId ); diff --git a/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs index 4820525c..c7fa452b 100644 --- a/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// Represents the request model for retrieving the authorization permissions of a user identified by . /// -/// The Id of the user for whom to get the authorization permissions. Required. +/// The unique identifier of the user for whom to get the authorization permissions. Required. public record GetUserPermissionsRequest( Guid? UserId ); diff --git a/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs index c6000303..fbb2faf2 100644 --- a/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// Represents the request model for retrieving the authorization role of a user identified by . /// -/// The Id of the user for whom to get the authorization role. Required. +/// The unique identifier of the user for whom to get the authorization role. Required. public record GetUserRoleRequest( Guid? UserId ); diff --git a/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs index febad4d3..c54916c9 100644 --- a/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs @@ -9,7 +9,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// Represents a request for updating an existing authorization role. /// -/// The Id of the role. Required. +/// The unique identifier of the role. Required. /// The name of the role. Required. /// The collection of Ids of the permissions of the role. Required. [DebuggerDisplay("RoleName: {RoleName}")] diff --git a/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs b/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs index 7a1ac023..cc414168 100644 --- a/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs @@ -9,8 +9,8 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// Represents a request for updating the authorization role and permissions of a user. /// -/// The Id of the user. Required. -/// The Id of the role. Optional. +/// The unique identifier of the user. Required. +/// The unique identifier of the role. Optional. /// The collection of Ids of the permissions of the role. Optional. [DebuggerDisplay("UserId: {UserId}")] public record UpdateUserRoleAndPermissionsRequest( diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs index 354463ea..5d471873 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs @@ -6,10 +6,12 @@ using System.Diagnostics; namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// -/// Represents a request to cancel the scan of a media library by its Id. +/// Represents a request to cancel the scan of a media library. /// -/// The Id of the media library whose scan is cancelled. Required. -[DebuggerDisplay("Id: {Id}")] +/// The unique identifier of the media library whose scan is cancelled. Required. +/// The Id of scan to cancel. Required. +[DebuggerDisplay("LibraryId: {LibraryId}; ScanId: {ScanId}")] public record CancelLibraryScanRequest( - Guid Id + Guid LibraryId, + Guid ScanId ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs index a2ef737f..35b99d75 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// /// Represents a request to delete a media library by its Id. /// -/// The Id of the media library to be deleted. Required. +/// The unique identifier of the media library to be deleted. Required. [DebuggerDisplay("Id: {Id}")] public record DeleteLibraryRequest( Guid Id diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryRequest.cs index df1aaefc..5baf2cb9 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// /// Represents a request to get a media library by its Id. /// -/// The Id of the media library. Required. +/// The unique identifier of the media library. Required. [DebuggerDisplay("Id: {Id}")] public record GetLibraryRequest( Guid Id diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs index 8a487bf0..4a684dce 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// /// Represents a request to scan a media library. /// -/// The Id of the media library to be scanned. Required. +/// The unique identifier of the media library to be scanned. Required. [DebuggerDisplay("Id: {Id}")] public record ScanLibraryRequest( Guid Id diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index 35b91a28..c718ab86 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -10,8 +10,8 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// /// Represents a request to update a media library. /// -/// The Id of the media library. Required. -/// The Id of the user owning the media library. Required. +/// The unique identifier of the media library. Required. +/// The unique identifier of the user owning the media library. Required. /// The title of the media library. Required. /// The type of the media library. Required. /// The file system paths of the directories where the media library elements are located. Required. diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs index 4e02a50b..3503cd03 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to get a book by the specified Id. /// -/// The Id of the book to retrieve. +/// The unique identifier of the book to retrieve. [DebuggerDisplay("Id: {Id}")] public record GetBookRequest( string? Id diff --git a/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs b/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs index 8fe6eef2..3169bf36 100644 --- a/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs +++ b/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Responses.Authentication; /// /// Represents the response model for user authentication. /// -/// The Id of the user to authenticate. +/// The unique identifier of the user to authenticate. /// The username of the user to authenticate. /// The authentication token used for subsequent requests. /// Whether the user uses 2FA authentication, or not. diff --git a/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs b/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs index 46f1b394..37d6ee5d 100644 --- a/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs +++ b/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Responses.Authentication; /// /// Represents the response model for user registration. /// -/// The Id of the user. +/// The unique identifier of the user. /// The username of the user. /// The TOTP (Time-Based One-Time Password) secret used for two-factor authentication. [DebuggerDisplay("Username: {Username}")] diff --git a/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs b/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs index 4f474ab4..4205f796 100644 --- a/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs +++ b/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs @@ -10,7 +10,7 @@ namespace Lumina.Contracts.Responses.Authorization; /// /// Represents the response model for an account authorization request. /// -/// The Id of the user for whom the authorization is retrieved. +/// The unique identifier of the user for whom the authorization is retrieved. /// The collection of roles associated to the user. /// The collection of permissions associated to the user. [DebuggerDisplay("UserId: {UserId}")] diff --git a/src/Lumina.Contracts/Responses/Authorization/PermissionResponse.cs b/src/Lumina.Contracts/Responses/Authorization/PermissionResponse.cs index 87eb2a11..c98d5e2b 100644 --- a/src/Lumina.Contracts/Responses/Authorization/PermissionResponse.cs +++ b/src/Lumina.Contracts/Responses/Authorization/PermissionResponse.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Responses.Authorization; /// /// Represents the response model for a request for an of authorization permission. /// -/// The Id of the requested authorization permission. +/// The unique identifier of the requested authorization permission. /// The requested authorization permission. public record PermissionResponse( Guid Id, diff --git a/src/Lumina.Contracts/Responses/Authorization/RoleResponse.cs b/src/Lumina.Contracts/Responses/Authorization/RoleResponse.cs index 012986d8..2a6c6b0b 100644 --- a/src/Lumina.Contracts/Responses/Authorization/RoleResponse.cs +++ b/src/Lumina.Contracts/Responses/Authorization/RoleResponse.cs @@ -7,7 +7,7 @@ namespace Lumina.Contracts.Responses.Authorization; /// /// Represents the response model for a request for an authorization role. /// -/// The Id of the requested authorization role. +/// The unique identifier of the requested authorization role. /// The requested authorization role. public record RoleResponse( Guid Id, diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs index 8ce380d8..98bd578f 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -10,8 +10,8 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// /// Represents a media library response. /// -/// The Id of the media library. -/// The Id of the user owning the media library. +/// The unique identifier of the media library. +/// The unique identifier of the user owning the media library. /// The title of the media library. /// The type of the media library. /// The file system paths of the directories where the media library elements are located. diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs index 8a3dffc0..179bf7ae 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs @@ -8,8 +8,8 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// /// Represents a media library scan response. /// -/// The Id of the media library scan. -/// The Id of the scanned media library. +/// The unique identifier of the media library scan. +/// The unique identifier of the scanned media library. [DebuggerDisplay("ScanId: {ScanId} LibraryId: {LibraryId}")] public record ScanLibraryResponse( Guid ScanId, diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index e3b3e0fe..ce210241 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -202,6 +202,23 @@ public class BookConfiguration : IEntityTypeConfiguration .HasMaxLength(6) .IsRequired(); }); + + // audit + builder.Property(permission => permission.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(32); + + builder.Property(permission => permission.CreatedBy) + .IsRequired() + .HasColumnOrder(33); + + builder.Property(permission => permission.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(34); + + builder.Property(permission => permission.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(35); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index 8f5a8cd4..cef4effc 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -59,6 +59,12 @@ public class LibraryConfiguration : IEntityTypeConfiguration .HasForeignKey(library => library.UserId) .IsRequired(); + // one library with many scans + builder.HasMany(library => library.LibraryScans) + .WithOne(libraryScan => libraryScan.Library) + .HasForeignKey(libraryScan => libraryScan.LibraryId) + .OnDelete(DeleteBehavior.Cascade); // deleting a library deletes library scans + // using OwnsMany because paths are domain Value Objects, thus they have no independent identity, and their lifecycle is bound to the Library builder.OwnsMany(library => library.ContentLocations, contentLocationBuilder => { @@ -75,5 +81,22 @@ public class LibraryConfiguration : IEntityTypeConfiguration .HasMaxLength(260) .IsRequired(); }); + + // audit + builder.Property(permission => permission.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(8); + + builder.Property(permission => permission.CreatedBy) + .IsRequired() + .HasColumnOrder(9); + + builder.Property(permission => permission.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(10); + + builder.Property(permission => permission.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(11); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs new file mode 100644 index 00000000..2c078806 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class LibraryScanConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("LibraryScans"); + builder.HasKey(library => library.Id); + builder.Property(library => library.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + + // one user with many library scans + builder.HasOne(libraryScan => libraryScan.User) + .WithMany(user => user.LibraryScans) + .HasForeignKey(libraryScan => libraryScan.UserId) + .IsRequired(); + + // one library with many library scans + builder.HasOne(libraryScan => libraryScan.Library) + .WithMany(library => library.LibraryScans) + .HasForeignKey(libraryScan => libraryScan.LibraryId) + .IsRequired(); + + builder.Property(libraryScan => libraryScan.Status) + .IsRequired() + .HasConversion() + .HasColumnOrder(1); + + // audit + builder.Property(permission => permission.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(2); + + builder.Property(permission => permission.CreatedBy) + .IsRequired() + .HasColumnOrder(3); + + builder.Property(permission => permission.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(4); + + builder.Property(permission => permission.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(5); + } +} diff --git a/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs b/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs index be086ab6..66f8f464 100644 --- a/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs +++ b/src/Lumina.DataAccess/Common/Interceptors/UpdateAuditableEntitiesInterceptor.cs @@ -82,7 +82,7 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor /// Sets the creation audit properties for a newly added entity. /// /// The entity being created. - /// The Id of the user creating the entity. + /// The unique identifier of the user creating the entity. /// The current UTC timestamp. private static void SetCreationProperties(IAuditableEntity entity, Guid? userId, DateTime utcNow) { @@ -96,7 +96,7 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor /// Sets the modification audit properties for an updated entity while protecting creation properties. /// /// The entity entry being modified. - /// The Id of the user modifying the entity. + /// The unique identifier of the user modifying the entity. /// The current UTC timestamp. private static void SetModificationProperties(EntityEntry entry, Guid? userId, DateTime utcNow) { diff --git a/src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.Designer.cs new file mode 100644 index 00000000..6468ffa2 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.Designer.cs @@ -0,0 +1,808 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20250215190409_AddsMediaLibraryScanTable")] + partial class AddsMediaLibraryScanTable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("LibraryId"); + + b.HasIndex("UserId"); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.cs b/src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.cs new file mode 100644 index 00000000..7d0f94f3 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250215190409_AddsMediaLibraryScanTable.cs @@ -0,0 +1,217 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddsMediaLibraryScanTable : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Books", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 34) + .OldAnnotation("Relational:ColumnOrder", 31); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Books", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 35); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Books", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 32) + .OldAnnotation("Relational:ColumnOrder", 30); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Books", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 33); + + migrationBuilder.CreateTable( + name: "LibraryScans", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Status = table.Column(type: "TEXT", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true), + LibraryId = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LibraryScans", x => x.Id); + table.ForeignKey( + name: "FK_LibraryScans_Libraries_LibraryId", + column: x => x.LibraryId, + principalTable: "Libraries", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_LibraryScans_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_LibraryScans_LibraryId", + table: "LibraryScans", + column: "LibraryId"); + + migrationBuilder.CreateIndex( + name: "IX_LibraryScans_UserId", + table: "LibraryScans", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "LibraryScans"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Books", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 31) + .OldAnnotation("Relational:ColumnOrder", 34); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Books", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .OldAnnotation("Relational:ColumnOrder", 35); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Books", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 30) + .OldAnnotation("Relational:ColumnOrder", 32); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Books", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .OldAnnotation("Relational:ColumnOrder", 33); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index de7dff2d..b538a4e5 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -251,10 +251,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnOrder(3); b.Property("CreatedBy") - .HasColumnType("TEXT"); + .HasColumnType("TEXT") + .HasColumnOrder(9); b.Property("CreatedOnUtc") - .HasColumnType("TEXT"); + .HasColumnType("TEXT") + .HasColumnOrder(8); b.Property("DownloadMedatadaFromWeb") .ValueGeneratedOnAdd() @@ -288,10 +290,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnOrder(1); b.Property("UpdatedBy") - .HasColumnType("TEXT"); + .HasColumnType("TEXT") + .HasColumnOrder(11); b.Property("UpdatedOnUtc") - .HasColumnType("TEXT"); + .HasColumnType("TEXT") + .HasColumnOrder(10); b.Property("UserId") .HasColumnType("TEXT"); @@ -303,6 +307,48 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Libraries", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("LibraryId"); + + b.HasIndex("UserId"); + + b.ToTable("LibraryScans", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => { b.Property("Id") @@ -324,11 +370,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnOrder(28); b.Property("CreatedBy") - .HasColumnType("TEXT"); + .HasColumnType("TEXT") + .HasColumnOrder(33); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(30); + .HasColumnOrder(32); b.Property("Description") .HasMaxLength(2000) @@ -440,11 +487,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnOrder(1); b.Property("UpdatedBy") - .HasColumnType("TEXT"); + .HasColumnType("TEXT") + .HasColumnOrder(35); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(31); + .HasColumnOrder(34); b.Property("VolumeNumber") .HasColumnType("INTEGER") @@ -633,6 +681,25 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("User"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => { b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => @@ -717,10 +784,17 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("UserRoles"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => { b.Navigation("Libraries"); + b.Navigation("LibraryScans"); + b.Navigation("UserPermissions"); b.Navigation("UserRole"); diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs new file mode 100644 index 00000000..3bcfbe86 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Errors; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Libraries; + +/// +/// Repository for media library scans. +/// +internal sealed class LibraryScanRepository : ILibraryScanRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public LibraryScanRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new library scan. + /// + /// The library scan to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(LibraryScanEntity libraryScan, CancellationToken cancellationToken) + { + bool libraryScanExists = await _luminaDbContext.LibraryScans.AnyAsync( + repositoryScanLibrary => repositoryScanLibrary.Id == libraryScan.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (libraryScanExists) + return Errors.LibraryScanning.LibraryScanAlreadyExists; + + _luminaDbContext.LibraryScans.Add(libraryScan); + return Result.Created; + } + + /// + /// Gets a identified by from the storage medium. + /// + /// The id of the library scan to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryScans + .Include(libraryScan => libraryScan.Library) + .Include(libraryScan => libraryScan.User) + .FirstOrDefaultAsync(libraryScan => libraryScan.Id == id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the media library scans that belong to a media library identified by , for the previous month, from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetPastMonthScansByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryScans + .Include(library => library.Library) + .Where(library => library.LibraryId == libraryId && library.CreatedOnUtc >= DateTime.UtcNow.AddMonths(-1)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the media library scans that have a status, from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetRunningScansAsync(CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryScans + .Include(library => library.Library) + .Where(library => library.Status == LibraryScanJobStatus.Running) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Updates a media library scan. + /// + /// The media library scan to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(LibraryScanEntity data, CancellationToken cancellationToken) + { + LibraryScanEntity? foundLibraryScan = await _luminaDbContext.LibraryScans + .Include(libraryScan => libraryScan.Library) + .FirstOrDefaultAsync(libraryScan => libraryScan.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (foundLibraryScan is null) + return Errors.LibraryScanning.LibraryScanNotFound; + // update scalar properties + _luminaDbContext.Entry(foundLibraryScan).CurrentValues.SetValues(data); + return Result.Updated; + } +} diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index 2b0c1cff..12dc66cb 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -39,7 +39,7 @@ public class DataSeedService : IDataSeedService /// /// Sets up default authorization permissions in the system. /// - /// The Id of the admin admin user who will own these permissions. + /// The unique identifier of the admin admin user who will own these permissions. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken) @@ -66,7 +66,7 @@ public class DataSeedService : IDataSeedService /// /// Sets up default authorization roles in the system. /// - /// The Id of the admin user for whom roles will be set. + /// The unique identifier of the admin user for whom roles will be set. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken) @@ -91,7 +91,7 @@ public class DataSeedService : IDataSeedService /// /// Assigns admin role permissions to the admin user. /// - /// The Id of the admin user to receive admin role permissions. + /// The unique identifier of the admin user to receive admin role permissions. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) @@ -136,7 +136,7 @@ public class DataSeedService : IDataSeedService /// /// Assigns admin role to the admin user. /// - /// The Id of the admin user to receive the admin role. + /// The unique identifier of the admin user to receive the admin role. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken) diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index e856a08b..3e6bce8e 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -18,6 +18,7 @@ public class LuminaDbContext : DbContext public virtual DbSet Books { get; set; } = null!; public virtual DbSet Users { get; set; } = null!; public virtual DbSet Libraries { get; set; } = null!; + public virtual DbSet LibraryScans { get; set; } = null!; public virtual DbSet Roles { get; set; } = null!; public virtual DbSet UserRoles { get; set; } = null!; public virtual DbSet Permissions { get; set; } = null!; diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index b96b2ced..526bdf09 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -3,6 +3,10 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; using System.IO.Abstractions; @@ -41,6 +45,10 @@ public static class DomainLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddSingleton(); return services; } diff --git a/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs index 0a162970..154b909f 100644 --- a/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs +++ b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs @@ -21,9 +21,9 @@ public enum LibraryScanJobStatus Completed, /// - /// Job has been cancelled. + /// Job has been canceled. /// - Cancelled, + Canceled, /// /// Job has failed. diff --git a/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs new file mode 100644 index 00000000..10d2522a --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.LibraryScanning.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Media Library Scan error types. +/// +public static partial class Errors +{ + public static class LibraryScanning + { + public static Error CanOnlyStartPendingScans => Error.Forbidden(description: nameof(CanOnlyStartPendingScans)); + public static Error CanOnlyCancelRunningScans => Error.Forbidden(description: nameof(CanOnlyCancelRunningScans)); + public static Error CanOnlyFailRunningScans => Error.Forbidden(description: nameof(CanOnlyFailRunningScans)); + public static Error ScanIdCannotBeEmpty => Error.Validation(description: nameof(ScanIdCannotBeEmpty)); + public static Error LibraryScanAlreadyExists => Error.Conflict(description: nameof(LibraryScanAlreadyExists)); + public static Error LibraryAlreadyBeingScanned => Error.Forbidden(description: nameof(LibraryAlreadyBeingScanned)); + public static Error LibraryScanNotFound => Error.NotFound(description: nameof(LibraryScanNotFound)); + public static Error TotalScanJobItemsCountMustBePositive => Error.Validation(description: nameof(TotalScanJobItemsCountMustBePositive)); + public static Error CompletedScanJobItemsCountMustBePositive => Error.Validation(description: nameof(CompletedScanJobItemsCountMustBePositive)); + public static Error CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount => Error.Validation(description: nameof(CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount)); + public static Error ScanJobCurrentOperationCannotBeEmpty => Error.Validation(description: nameof(ScanJobCurrentOperationCannotBeEmpty)); + } +} diff --git a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs index 76822219..53c0c9a5 100644 --- a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs +++ b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs @@ -22,19 +22,11 @@ public abstract class AggregateRoot : Entity where TId : notnull Id = id; } - /// - /// Initializes a new instance of the class. - /// - protected AggregateRoot() // only needed during reflection - { - - } - /// /// Retrieves and clears all domain events associated with this aggregate root. /// /// A list of all domain events that were raised by this aggregate root. - public List PopDomainEvents() + public List GetDomainEvents() { List domainEventsCopy = [.. _domainEvents]; _domainEvents.Clear(); diff --git a/src/Lumina.Domain/Common/Models/Core/Entity.cs b/src/Lumina.Domain/Common/Models/Core/Entity.cs index 06699926..e100c991 100644 --- a/src/Lumina.Domain/Common/Models/Core/Entity.cs +++ b/src/Lumina.Domain/Common/Models/Core/Entity.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using System; #endregion @@ -34,16 +34,6 @@ public abstract class Entity : IEquatable> where TId : notnull Id = id; } -#pragma warning disable CS8618 - /// - /// Initializes a new instance of the class. - /// - protected Entity() // only needed during reflection - { - - } -#pragma warning restore CS8618 - /// /// Indicates whether the current object is equal to another object of the same type. /// @@ -94,4 +84,4 @@ public abstract class Entity : IEquatable> where TId : notnull { return Id.GetHashCode(); } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEvent.cs index 32b1c7b9..c9dcb692 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEvent.cs @@ -9,7 +9,7 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// /// Domain event raised when a libary is deleted. /// -/// The Id of the domain event. +/// The unique identifier of the domain event. /// The library that was deleted. /// The date and time when the domain event occurred. [DebuggerDisplay("Id: {Library.Id} Title: {Library.Title}")] diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs index 50a034c1..25d88500 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs @@ -9,7 +9,7 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// /// Domain event raised when a libary is created or updated. /// -/// The Id of the domain event. +/// The unique identifier of the domain event. /// The library that was created or updated. /// The date and time when the domain event occurred. [DebuggerDisplay("Id: {Library.Id} Title: {Library.Title}")] diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index c4765c11..7fbfb7c5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -5,6 +5,8 @@ using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System; using System.Collections.Generic; @@ -17,13 +19,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// /// Aggregate root for a media library. /// -[DebuggerDisplay("Id: {Id} Title: {Title}")] +[DebuggerDisplay("Id: {Id}; Title: {Title}")] public class Library : AggregateRoot { private readonly List _contentLocations; + private readonly List _scanIds; /// - /// Gets the id of the user owning this media library. + /// Gets the object representing the unique identifier of the user owning this media library. /// public UserId UserId { get; private set; } @@ -68,23 +71,29 @@ public class Library : AggregateRoot public bool SaveMetadataInMediaDirectories { get; private set; } /// - /// Gets the list of file system paths that make up the media library. + /// Gets the list of objects representing the file system paths that make up the media library. /// public IReadOnlyCollection ContentLocations => _contentLocations.AsReadOnly(); + /// + /// Gets the list of objects representing the unique identifiers for the library scans that were performed on this media library. + /// + public IReadOnlyCollection ScanIds => _scanIds.AsReadOnly(); + /// /// Initializes a new instance of the class. /// - /// The unique identifier of the media library. - /// The unique identifier of the user owning the media library. + /// The object representing the unique identifier of the media library. + /// The object representing the unique identifier of the user owning the media library. /// The title of the media library. /// The type of the media library (e.g., Book, TvShow). - /// The list of file system paths that make up the media library. + /// The list of objects representing the file system paths that make up the media library. /// 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 copy the downloaded metadata into the media library content locations, or not. + /// The list of objects representing the unique identifier of scans of the media library. private Library( LibraryId id, UserId userId, @@ -95,7 +104,8 @@ public class Library : AggregateRoot bool isEnabled, bool isLocked, bool downloadMedatadaFromWeb, - bool saveMetadataInMediaDirectories) : base(id) + bool saveMetadataInMediaDirectories, + List scanIds) : base(id) { UserId = userId; Title = title; @@ -106,13 +116,13 @@ public class Library : AggregateRoot IsLocked = isLocked; DownloadMedatadaFromWeb = downloadMedatadaFromWeb; SaveMetadataInMediaDirectories = saveMetadataInMediaDirectories; - _domainEvents.Add(new LibrarySavedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow)); + _scanIds = scanIds; } /// /// Creates a new instance of the class. /// - /// The unique identifier of the user owning the media library. + /// The object representing the unique identifier of the user owning the media library. /// The title of the media library. /// The type of the media library (e.g., Book, TvShow). /// The list of file system paths that make up the media library. @@ -121,11 +131,12 @@ public class Library : AggregateRoot /// 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 copy the downloaded metadata into the media library content locations, or not. + /// The list of objects representing the unique identifier of scans of the media library. /// /// An containing either a successfuly created , or an error message. /// public static ErrorOr Create( - Guid userId, + UserId userId, string title, LibraryType libraryType, IEnumerable contentLocations, @@ -133,7 +144,8 @@ public class Library : AggregateRoot bool isEnabled, bool isLocked, bool downloadMedatadaFromWeb, - bool saveMetadataInMediaDirectories) + bool saveMetadataInMediaDirectories, + List scanIds) { List tempContentLocations = []; // go through all the file system paths that make up the media library and create domain objects from them @@ -146,7 +158,7 @@ public class Library : AggregateRoot } return new Library( LibraryId.CreateUnique(), - UserId.Create(userId), + userId, title, libraryType, tempContentLocations, @@ -154,15 +166,16 @@ public class Library : AggregateRoot isEnabled, isLocked, downloadMedatadaFromWeb, - saveMetadataInMediaDirectories + saveMetadataInMediaDirectories, + scanIds ); } /// /// Creates a new instance of the , with a pre-existing . /// - /// The object representing the id of the media library. - /// The object representing the id of the user owning the media library. + /// The object representing the unique identifier of the media library. + /// The object representing the unique identifier of the user owning the media library. /// The title of the media library. /// The type of the media library (e.g., Book, TvShow). /// The list of file system paths that make up the media library. @@ -171,12 +184,13 @@ public class Library : AggregateRoot /// 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 copy the downloaded metadata into the media library content locations, or not. + /// The list of objects representing the unique identifier of scans of the media library. /// /// An containing either a successfuly created , or an error message. /// public static ErrorOr Create( LibraryId id, - Guid userId, + UserId userId, string title, LibraryType libraryType, IEnumerable contentLocations, @@ -184,7 +198,8 @@ public class Library : AggregateRoot bool isEnabled, bool isLocked, bool downloadMedatadaFromWeb, - bool saveMetadataInMediaDirectories) + bool saveMetadataInMediaDirectories, + List scanIds) { List tempContentLocations = []; // go through all the file system paths that make up the media library and create domain objects from them @@ -197,7 +212,7 @@ public class Library : AggregateRoot } return new Library( id, - UserId.Create(userId), + userId, title, libraryType, tempContentLocations, @@ -205,10 +220,19 @@ public class Library : AggregateRoot isEnabled, isLocked, downloadMedatadaFromWeb, - saveMetadataInMediaDirectories + saveMetadataInMediaDirectories, + scanIds ); } + /// + /// Initiates the saving of the current library. + /// + public void Save() + { + _domainEvents.Add(new LibrarySavedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow)); + } + /// /// Sets the file system path where the cover image was copied to from where it was located when the user selected it, to the internal library. /// @@ -221,13 +245,14 @@ public class Library : AggregateRoot /// /// Marks the current library as deleted. /// + /// An representing either a successful operation, or an error. public ErrorOr Delete() { // clear all existing events since they become irrelevant when the entity is deleted, and they dont need to be processed _domainEvents.Clear(); // only add the delete event if it hasn't been added already - if (!_domainEvents.Any(e => e is LibraryDeletedDomainEvent)) + if (!_domainEvents.Any(domainEvent => domainEvent is LibraryDeletedDomainEvent)) _domainEvents.Add(new LibraryDeletedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow)); // TODO: perhaps trigger events for removing contents related to the removed library (media metadata, etc)? diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEvent.cs new file mode 100644 index 00000000..89894a52 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEvent.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a libary scan is canceled. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the cancelled media library scan. +/// The unique identifier of the library whose scan was canceled. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Id}")] +public record LibraryScanCancelledDomainEvent( + Guid Id, + ScanId ScanId, + LibraryId LibraryId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCompletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCompletedDomainEvent.cs new file mode 100644 index 00000000..574a2f74 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCompletedDomainEvent.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a libary scan is completed. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the library whose scan was completed. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Id}")] +public record LibraryScanCompletedDomainEvent( + Guid Id, + LibraryId LibraryId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs new file mode 100644 index 00000000..78fddd40 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a libary scan has failed. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the failed media library scan. +/// The unique identifier of the library whose scan has failed. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Id}")] +public record LibraryScanFailedDomainEvent( + Guid Id, + ScanId ScanId, + LibraryId LibraryId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs new file mode 100644 index 00000000..5ce1f801 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a libary's scan progress changes. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the failed media library scan. +/// The unique identifier of the library whose scan progress changes. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Id}")] +public record LibraryScanProgressChangedDomainEvent( + Guid Id, + ScanId ScanId, + LibraryId LibraryId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.cs new file mode 100644 index 00000000..57c1ffce --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEvent.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a libary scan is queued. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the queued media library scan. +/// The unique identifier of the library whose scan was queued. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Id}")] +public record LibraryScanQueuedDomainEvent( + Guid Id, + ScanId ScanId, + LibraryId LibraryId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEvent.cs new file mode 100644 index 00000000..5a822e37 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEvent.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Domain event raised when a libary scan is started. +/// +/// The unique identifier of the domain event. +/// The library scan that was started. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {LibraryScan.Id}")] +public record LibraryScanStartedDomainEvent( + Guid Id, + LibraryScan LibraryScan, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs new file mode 100644 index 00000000..3d747370 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScan.cs @@ -0,0 +1,151 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; + +/// +/// Aggregate root for a media library scan. +/// +[DebuggerDisplay("Id: {Id}")] +public class LibraryScan : AggregateRoot +{ + private readonly List _pastScans = []; + + /// + /// Gets the object representing the unique identifier of the media library that is scanned. + /// + public LibraryId LibraryId { get; private set; } + + /// + /// Gets the object representing the unique identifier of the user initiating this media library scan. + /// + public UserId UserId { get; private set; } + + /// + /// Gets or sets the status of the current media library scan job. + /// + public LibraryScanJobStatus Status { get; internal set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the media library scan. + /// The object representing the unique identifier of the media library to be scanned. + /// The object representing the unique identifier of the user initiating the media library scan. + /// The status of the media library scan. + /// The list of past media library scans the library identified by had. + private LibraryScan(ScanId id, LibraryId libraryId, UserId userId, LibraryScanJobStatus status, List pastScans) : base(id) + { + LibraryId = libraryId; + UserId = userId; + Status = status; + _pastScans = pastScans; + } + + /// + /// Creates a new instance of the class. + /// + /// The object representing the unique identifier of the media library to be scanned. + /// The object representing the unique identifier of the user initiating the media library scan. + /// The list of past media library scans the library identified by had. + /// + /// An containing either a successfuly created , or an error message. + /// + public static ErrorOr Create(LibraryId libraryId, UserId userId, List pastScans) + { + return new LibraryScan(ScanId.CreateUnique(), libraryId, userId, LibraryScanJobStatus.Pending, pastScans); + } + + /// + /// Creates a new instance of the , with a pre-existing . + /// + /// The object representing the unique identifier of the media library scan. + /// The object representing the unique identifier of the media library to be scanned. + /// The object representing the unique identifier of the user initiating the media library scan. + /// The status of the media library scan. + /// The list of past media library scans the library identified by had. + /// + /// An containing either a successfuly created , or an error message. + /// + public static ErrorOr Create(ScanId id, LibraryId libraryId, UserId userId, LibraryScanJobStatus status, List pastScans) + { + return new LibraryScan(id, libraryId, userId, status, pastScans); + } + + /// + /// Queues a media library scan. + /// + /// An representing either a successful operation, or an error. + public ErrorOr QueueScan() + { + // there must be no active scan for this library in the past 30 days + if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending)) + return Errors.LibraryScanning.LibraryAlreadyBeingScanned; + + _domainEvents.Add(new LibraryScanQueuedDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow)); + + return Result.Success; + } + + /// + /// Starts the media library scan. + /// + /// An representing either a successful operation, or an error. + public ErrorOr StartScan() + { + if (Status == LibraryScanJobStatus.Pending) + Status = LibraryScanJobStatus.Running; + else + return Errors.LibraryScanning.CanOnlyStartPendingScans; + + // there must be no active scan for this library in the past 30 days + if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending)) + return Errors.LibraryScanning.LibraryAlreadyBeingScanned; + + _domainEvents.Add(new LibraryScanStartedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow)); + + return Result.Success; + } + + /// + /// Cancels the media library scan. + /// + /// An representing either a successful operation, or an error. + public ErrorOr CancelScan() + { + if (Status == LibraryScanJobStatus.Running) + Status = LibraryScanJobStatus.Canceled; + else + return Errors.LibraryScanning.CanOnlyCancelRunningScans; + + _domainEvents.Add(new LibraryScanCancelledDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow)); + + return Result.Success; + } + + /// + /// Marks the media library scan as failed. + /// + /// An representing either a successful operation, or an error. + public ErrorOr FailScan() + { + if (Status == LibraryScanJobStatus.Running) + Status = LibraryScanJobStatus.Failed; + else + return Errors.LibraryScanning.CanOnlyFailRunningScans; + + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs similarity index 51% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs index d580b9c7..7484ad69 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Cancellation/IMediaLibrariesScanCancellationTracker.cs @@ -3,38 +3,38 @@ using System; using System.Threading; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; /// -/// Interface for the tracker used for in-progress media library scans. +/// Interface for the tracker used for canceling in-memory media library scans. /// -public interface IMediaLibrariesScanTracker +public interface IMediaLibrariesScanCancellationTracker { /// /// Gets the cancellation token for a scan identified by and . /// - /// The Id of the scan to get the cancellation token for<./param> - /// The Id of the user who initiated the scan for which to get the cancellation token. + /// The unique identifier of the scan to get the cancellation token for. + /// The unique identifier of the user who initiated the scan for which to get the cancellation token. /// A cancellation token for the specified scan. CancellationToken GetTokenForScan(Guid scanId, Guid userId); /// /// Registers a new scan operation for tracking. /// - /// The Id of the scan operation to track. - /// The Id of the user who initiated the scan to track. + /// The unique identifier of the scan operation to track. + /// The unique identifier of the user who initiated the scan to track. void RegisterScan(Guid scanId, Guid userId); /// /// Cancels a scan identified by and . /// - /// The Id of the scan operation to cancel. - /// The Id of the user requesting the cancellation. + /// The unique identifier of the scan operation to cancel. + /// The unique identifier of the user requesting the cancellation. void CancelScan(Guid scanId, Guid userId); /// /// Cancels all active scan operations for a user identified by . /// - /// The Id of the user whose scans should be cancelled. + /// The unique identifier of the user whose scans should be canceled. void CancelUserScans(Guid userId); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs new file mode 100644 index 00000000..734d8b01 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; + +/// +/// Interface for the service used to scan a media library. +/// +public interface IMediaLibraryScanningService +{ + /// + /// Starts . + /// + /// 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 downloadMedatadaFromWeb, CancellationToken cancellationToken); + + /// + /// Cancels . + /// + /// The scan to cancel. + /// An representing either a successful operation, or an error. + ErrorOr CancelScan(LibraryScan scan); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs new file mode 100644 index 00000000..a0cc2b9c --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for discovering file system items. +/// +public interface IFileSystemDiscoveryJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs new file mode 100644 index 00000000..43c11e1b --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for comparing hashes. +/// +public interface IHashComparerJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanJob.cs new file mode 100644 index 00000000..c5831aae --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanJob.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.MediaLibrary; +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 System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the abstract base class defining a media library scan job. +/// +public interface IMediaLibraryScanJob +{ + /// + /// Gets or sets the Id of the media library scan that this job is part of. + /// + ScanId ScanId { get; set; } + + /// + /// Gets or sets the Id of the user that initiated the media library scan that this job is part of. + /// + UserId UserId { get; set; } + + /// + /// Gets or sets the unique identifier of the media library upon which the scan is performed. + /// + LibraryId LibraryId { get; set; } + + /// + /// Gets or sets the list of child media scan jobs that will be triggered when this job's payload completes execution. + /// + List Children { get; } + + /// + /// Gets or sets the list of parent media scan jobs that will trigger this job when their payload will complete execution. + /// + List Parents { get; } + + /// + /// Gets or sets the status of the current media library scan job. + /// + LibraryScanJobStatus Status { get; } + + /// + /// Adds a media library scan job to the list of child media library scan jobs that will be triggered when this job's payload completes execution. + /// + /// The child media library scan job to be added. + void AddChild(IMediaLibraryScanJob job); + + /// + /// Adds a media library scan job to the list of parent media library scan jobs that will trigger this job when their payload will complete execution. + /// + /// The child media library scan job to be added. + void AddParent(IMediaLibraryScanJob job); + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The id of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaLibraryScanJobFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanJobFactory.cs similarity index 70% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaLibraryScanJobFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanJobFactory.cs index 8a88cfdd..7d5b4fbd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaLibraryScanJobFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanJobFactory.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using System; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; /// /// Interface for the media library scan jobs factory. @@ -13,8 +13,9 @@ internal interface IMediaLibraryScanJobFactory /// /// Creates a new media library scan job of type . /// + /// The unique identifier of the media library upon which the scan is performed. /// The type of media library scan job to create. /// A media library scan job of type . /// Thrown when the type of the requested media library scan job has not been registered. - TJob CreateJob(Library library) where TJob : MediaLibraryScanJob; + TJob CreateJob(LibraryId libraryId) where TJob : IMediaLibraryScanJob; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs new file mode 100644 index 00000000..e07b0c3c --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs @@ -0,0 +1,9 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for retrieving persistence data from any eventual previous scans. +/// +public interface IRepositoryMetadataDiscoveryJob : IMediaLibraryScanJob +{ + +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJob.cs similarity index 70% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJob.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJob.cs index c57baed0..29dd78f3 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJob.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJob.cs @@ -1,45 +1,48 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Enums.MediaLibrary; -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 System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; /// /// Abstract class defining a media library scan job. /// -internal abstract class MediaLibraryScanJob +public abstract class MediaLibraryScanJob : IMediaLibraryScanJob { - internal int parentsPayloadsExecuted; - + protected int parentsPayloadsExecuted; + protected ScanJobProgress? _jobProgress; + /// /// Gets or sets the Id of the media library scan that this job is part of. /// - public Guid ScanId { get; set; } + public required ScanId ScanId { get; set; } /// /// Gets or sets the Id of the user that initiated the media library scan that this job is part of. /// - public Guid UserId { get; set; } + public required UserId UserId { get; set; } + + /// + /// Gets or sets the unique identifier of the media library upon which the scan is performed. + /// + public required LibraryId LibraryId { get; set; } /// /// Gets or sets the list of child media scan jobs that will be triggered when this job's payload completes execution. /// - public List Children { get; protected set; } = []; + public List Children { get; protected set; } = []; /// /// Gets or sets the list of parent media scan jobs that will trigger this job when their payload will complete execution. /// - public List Parents { get; protected set; } = []; - - /// - /// Gets or sets the media library upon which the scan is performed. - /// - public required Library Library { get; set; } + public List Parents { get; protected set; } = []; /// /// Gets or sets the status of the current media library scan job. @@ -50,7 +53,7 @@ internal abstract class MediaLibraryScanJob /// Adds a media library scan job to the list of child media library scan jobs that will be triggered when this job's payload completes execution. /// /// The child media library scan job to be added. - public void AddChild(MediaLibraryScanJob job) + public void AddChild(IMediaLibraryScanJob job) { if (!Children.Contains(job) && !Parents.Contains(job)) Children.Add(job); @@ -60,7 +63,7 @@ internal abstract class MediaLibraryScanJob /// Adds a media library scan job to the list of parent media library scan jobs that will trigger this job when their payload will complete execution. /// /// The child media library scan job to be added. - public void AddParent(MediaLibraryScanJob job) + public void AddParent(IMediaLibraryScanJob job) { if (!Parents.Contains(job) && !Children.Contains(job)) Parents.Add(job); @@ -70,7 +73,7 @@ internal abstract class MediaLibraryScanJob /// Executes the payload of the media library scan job. /// /// The type of the input parameter representing the data to be processed by this payload. - /// The id of the media library scan job. + /// The unique identifier of the media library scan job. /// The input data to be processed by this payload. /// Cancellation token that can be used to stop the execution. public abstract Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJobFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobFactory.cs similarity index 75% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJobFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobFactory.cs index 860c0dfd..bf7135bb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJobFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobFactory.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Microsoft.Extensions.DependencyInjection; using System; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; /// /// Concrete implementation for the media library scan jobs factory. @@ -25,14 +25,15 @@ internal class MediaLibraryScanJobFactory : IMediaLibraryScanJobFactory /// /// Creates a new media library scan job of type . /// + /// The unique identifier of the media library upon which the scan is performed. /// The type of media library scan job to create. /// A media library scan job of type . /// Thrown when the type of the requested media library scan job has not been registered. - public TJob CreateJob(Library library) where TJob : MediaLibraryScanJob + public TJob CreateJob(LibraryId libraryId) where TJob : IMediaLibraryScanJob { // resolve the job from DI - TJob job = _serviceProvider.GetRequiredService() ?? throw new ArgumentException(); - job.Library = library; + TJob job = _serviceProvider.GetRequiredService() ?? throw new ArgumentException("Job type not registered in the DI system."); + job.LibraryId = libraryId; return job; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs new file mode 100644 index 00000000..17e32bc2 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.MediaLibrary; +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.Queue; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; + +/// +/// Service used to scan a media library. +/// +internal class MediaLibraryScanningService : IMediaLibraryScanningService +{ + private readonly IMediaLibrariesScanQueue _mediaScanQueue; + private readonly IMediaLibraryScannerFactory _libraryScannerFactory; + private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; + + /// + /// Initializes a new instance of the class. + /// + /// Injected queue used for processing media libraries scan jobs. + /// Injected factory for creating media library scanners. + public MediaLibraryScanningService( + IMediaLibrariesScanQueue mediaScanQueue, + IMediaLibraryScannerFactory libraryScannerFactory, + IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker) + { + _mediaScanQueue = mediaScanQueue; + _libraryScannerFactory = libraryScannerFactory; + _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; + } + + /// + /// Starts . + /// + /// 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 downloadMedatadaFromWeb, CancellationToken cancellationToken) + { + // mark the scan itself as started + ErrorOr startScanResult = scan.StartScan(); + if (startScanResult.IsError) + return startScanResult.Errors; + // register the scan in the tracker for cancellation tokens + _mediaLibrariesScanCancellationTracker.RegisterScan(scan.Id.Value, scan.UserId!.Value); + + try + { + // link the user's cancellation token with the scan's token + CancellationTokenSource linkedSource = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken, _mediaLibrariesScanCancellationTracker.GetTokenForScan(scan.Id.Value, scan.UserId!.Value)); + + // get a media library scanner for the provided media library type + IMediaTypeScanner scanner = _libraryScannerFactory.CreateLibraryScanner(libraryType); + // get the list of scan jobs for the retrieved scanner + List jobs = scanner.CreateScanJobsForLibrary(scan.LibraryId, downloadMedatadaFromWeb).ToList(); + // enqueue the jobs on the channel from where they will be processed + foreach (IMediaLibraryScanJob job in jobs) + { + job.ScanId = scan.Id; + job.UserId = scan.UserId; + await _mediaScanQueue.Writer.WriteAsync(job, linkedSource.Token).ConfigureAwait(false); + } + } + catch (NotImplementedException) { } + return Result.Success; + } + + /// + /// Cancels . + /// + /// The media library scan to cancel. + /// An representing either a successful operation, or an error. + public ErrorOr CancelScan(LibraryScan scan) + { + // trigger the process that cancels the jobs of the scan + _mediaLibrariesScanCancellationTracker.CancelScan(scan.Id.Value, scan.UserId!.Value); + return Result.Success; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs new file mode 100644 index 00000000..cb679ffe --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Queue/IMediaLibrariesScanQueue.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using System.Threading.Channels; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; + +/// +/// Interface for the message queue for handling instances. +/// +public interface IMediaLibrariesScanQueue +{ + /// + /// Gets the writer for the queue, allowing producers to enqueue instances. + /// + public ChannelWriter Writer { get; } + + /// + /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// + public ChannelReader Reader { get; } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaLibraryScannerFactory.cs similarity index 86% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaLibraryScannerFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaLibraryScannerFactory.cs index 3c4a3c85..5468b54f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaLibraryScannerFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaLibraryScannerFactory.cs @@ -2,7 +2,7 @@ using Lumina.Domain.Common.Enums.MediaLibrary; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; /// /// Interface defining a factory for creating media library scanners. diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaTypeScanner.cs similarity index 53% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaTypeScanner.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaTypeScanner.cs index f28140ee..5a1a988d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/IMediaTypeScanner.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using System.Collections.Generic; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; /// /// Interface defining a media library scanner for a specific media library type. /// -internal interface IMediaTypeScanner +public interface IMediaTypeScanner { /// /// The media library type that this media library scanner supports. @@ -20,7 +20,8 @@ internal interface IMediaTypeScanner /// /// Creates the media library scan jobs for the provided media library. /// - /// The media library for which to create the media library scan jobs. + /// 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(Library library); + IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMedatadaFromWeb); } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/MediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/MediaLibraryScannerFactory.cs similarity index 95% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/MediaLibraryScannerFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/MediaLibraryScannerFactory.cs index c5ff3b39..abc9797d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/MediaLibraryScannerFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/Common/MediaLibraryScannerFactory.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent; using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Microsoft.Extensions.DependencyInjection; using System; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; /// /// Defines a factory for creating media library scanners. diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanId.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanId.cs new file mode 100644 index 00000000..d0e5e670 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanId.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Value Object for the Id of a media library scan. +/// +[DebuggerDisplay("Value: {Value}")] +public sealed class ScanId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private ScanId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static ScanId CreateUnique() + { + return new ScanId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static ScanId Create(Guid value) + { + return new ScanId(value); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanJobProgress.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanJobProgress.cs new file mode 100644 index 00000000..bcf57cf7 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanJobProgress.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Value Object representing a progress snapshot of a media library scan job. +/// +[DebuggerDisplay("CompletedItems: {CompletedItems}; TotalItems: {TotalItems}; CurrentOperation: {CurrentOperation}")] +public sealed class ScanJobProgress : ValueObject +{ + /// + /// Gets the number of completed items of the media library scan job. + /// + public int CompletedItems { get; } + + /// + /// Gets the total number of items of the media library scan job. + /// + public int TotalItems { get; } + + /// + /// Gets the current operation being performed by the media library scan job. + /// + public string CurrentOperation { get; } = string.Empty; + + /// + /// Gets the ratio between the total number and the completed number of items, as a percentage. + /// + public decimal ProgressPercentage => CompletedItems * 100.0m / TotalItems; + + /// + /// Initializes a new instance of the class. + /// + /// The number of completed items of the media library scan job. + /// The total number of items of the media library scan job. + /// The current operation being performed by the media library scan job. + private ScanJobProgress(int completedItems, int totalItems, string currentOperation) + { + CompletedItems = completedItems; + TotalItems = totalItems; + CurrentOperation = currentOperation; + } + + /// + /// Creates a new instance of the class. + /// + /// The number of completed items of the media library scan job. + /// The total number of items of the media library scan job. + /// The current operation being performed by the media library scan job. + /// + /// An containing either a successfuly created , or an error message. + /// + public static ErrorOr Create(int completedItems, int totalItems, string currentOperation) + { + if (totalItems <= 0) + return Errors.LibraryScanning.TotalScanJobItemsCountMustBePositive; + if (completedItems < 0) + return Errors.LibraryScanning.CompletedScanJobItemsCountMustBePositive; + if (completedItems > totalItems) + return Errors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount; + if (string.IsNullOrWhiteSpace(currentOperation)) + return Errors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty; + return new ScanJobProgress(completedItems, totalItems, currentOperation); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return CompletedItems; + yield return TotalItems; + yield return CurrentOperation; + } + + /// + /// Customized ToString() method. + /// + /// Custom string value showing relevant data for current class. + public override string ToString() + { + return $"CompletedItems: {CompletedItems}; TotalItems: {TotalItems}; CurrentOperation: {CurrentOperation}"; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs index b02d15ac..52252ab0 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs @@ -54,7 +54,7 @@ public class MediaContributor : AggregateRoot MediaContributorName name, MediaContributorRole role, Optional dateOfBirth, - Optional dateOfDeath) + Optional dateOfDeath) : base(id) { Id = id; Name = name; diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs index 837df0b3..f6cf0476 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs @@ -21,11 +21,9 @@ public sealed class User : AggregateRoot /// /// Initializes a new instance of the class. /// - /// The unique identifier of the user. + /// The object representing the unique identifier of the user. /// The username of the user. - private User( - UserId id, - string username) : base(id) + private User(UserId id, string username) : base(id) { Username = username; } @@ -37,28 +35,21 @@ public sealed class User : AggregateRoot /// /// An containing either a successfuly created , or an error message. /// - public static ErrorOr Create( - string username) + public static ErrorOr Create(string username) { - return new User( - UserId.CreateUnique(), - username); + return new User(UserId.CreateUnique(), username); } /// /// Creates a new instance of the , with a pre-existing . /// - /// The object representing the id of the user. + /// The object representing the unique identifier of the user. /// The username of the user. /// /// An containing either a successfuly created , or an error message. /// - public static ErrorOr Create( - UserId id, - string username) + public static ErrorOr Create(UserId id, string username) { - return new User( - id, - username); + return new User(id, username); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs index 784f7d9c..e7d163e2 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs @@ -49,16 +49,6 @@ public sealed class Movie : Entity _ratings = ratings; } -#pragma warning disable CS8618 - /// - /// Initializes a new instance of the class. - /// - private Movie() // only needed during reflection - { - - } -#pragma warning restore CS8618 - /// /// Creates a new instance of the class. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Episode.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Episode.cs index 21682dff..fa923684 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Episode.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Episode.cs @@ -12,5 +12,7 @@ namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLi [DebuggerDisplay("{Id}: {Title}")] public sealed class Episode : Entity { - + public Episode(EpisodeId id) : base(id) + { + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Season.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Season.cs index b8e838fe..54073a8f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Season.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Season.cs @@ -12,5 +12,7 @@ namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLi [DebuggerDisplay("{Id}: {Title}")] public sealed class Season : Entity { - -} \ No newline at end of file + public Season(SeasonId id) : base(id) + { + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShow.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShow.cs index a186f6f7..9c089648 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShow.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShow.cs @@ -12,5 +12,7 @@ namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLi [DebuggerDisplay("{Id}: {Title}")] public sealed class TvShow : Entity { - + public TvShow(TvShowId id) : base(id) + { + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index e706d27a..63e8c5b8 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs @@ -99,7 +99,7 @@ public sealed class Book : AggregateRoot public IReadOnlyCollection ISBNs => _isbns.AsReadOnly(); /// - /// Gets the list of media contributors (actors, directors, etc) starring in this book. + /// Gets the list of objects representing the unique identifiers of the media contributors (actors, directors, etc) starring in this book. /// public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); @@ -111,7 +111,7 @@ public sealed class Book : AggregateRoot /// /// Initializes a new instance of the class. /// - /// The unique identifier of the book. + /// The object representing the unique identifier of the book. /// The metadata of the book. /// The optional format of the book (e.g., Hardcover, Paperback). /// The optional edition of the book. @@ -129,7 +129,7 @@ public sealed class Book : AggregateRoot /// The date and time when the entity was created. /// The date and time when the entity was last updated. /// The list of ISBNs of the book. - /// The list of media contributors of the book. + /// The list of objects representing the unique identifiers of the media contributors of the book. /// The list of ratings for the book. private Book( BookId id, @@ -175,16 +175,6 @@ public sealed class Book : AggregateRoot _ratings = ratings; } -#pragma warning disable CS8618 - /// - /// Initializes a new instance of the class. - /// - private Book() // only needed during reflection - { - - } -#pragma warning restore CS8618 - /// /// Creates a new instance of the class. /// @@ -203,7 +193,7 @@ public sealed class Book : AggregateRoot /// The optional Barnes & Noble ID of the book. /// The optional Apple Books ID of the book. /// The list of ISBNs of the book. - /// The list of media contributors of the book. + /// The list of objects representing the unique identifiers of the media contributors of the book. /// The list of ratings for the book. /// /// An containing either a successfuly created , or an error message. @@ -255,7 +245,7 @@ public sealed class Book : AggregateRoot /// /// Creates a new instance of the , with a pre-existing . /// - /// The object representing the id of the book. + /// The object representing the unique identifier of the book. /// The metadata of the book. /// The optional format of the book (e.g., Hardcover, Paperback). /// The optional edition of the book. @@ -273,7 +263,7 @@ public sealed class Book : AggregateRoot /// The date and time when the entity was created. /// The date and time when the entity was last updated. /// The list of ISBNs of the book. - /// The list of media contributors of the book. + /// The list of objects representing the unique identifiers of the media contributors of the book. /// The list of ratings for the book. /// /// An containing either a successfuly created , or an error message. diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs index 2cea20bf..c80765ce 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs @@ -35,7 +35,7 @@ public sealed class BookSeries : Entity /// /// Initializes a new instance of the class. /// - /// The identifier of the book series. + /// The object representing the unique identifier of the book series. /// The metadata of the book series. /// The current status of the book series. /// The books of the book series. @@ -51,7 +51,7 @@ public sealed class BookSeries : Entity /// /// Creates a new instance of the class. /// - /// The identifier of the book series. + /// The object representing the unique identifier of the book series. /// The metadata of the book series. /// The current status of the book series. /// The books of the book series. diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IGoodReadsMetadataScrapJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IGoodReadsMetadataScrapJob.cs new file mode 100644 index 00000000..9dc7196e --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IGoodReadsMetadataScrapJob.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for retrieving written content metadata from GoodReads. +/// +public interface IGoodReadsMetadataScrapJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs similarity index 59% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/BookLibraryTypeScanner.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index b1470ff3..6efd6742 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; -using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books; using Lumina.Domain.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using System.Collections.Generic; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; /// /// Media library scanner for a books media library type. @@ -19,7 +19,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner public LibraryType SupportedType { get; } = LibraryType.Book; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected factory for creating media library scan jobs. public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory) @@ -28,13 +28,13 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner } /// - public IEnumerable CreateScanJobsForLibrary(Library library) + public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMedatadaFromWeb) { // declare the list of jobs that this scanner requires - FileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(library); - RepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob(library); - HashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob(library); - GoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(library); + IFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); + IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); + IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob(libraryId); + IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(libraryId); // establish the hierarchical relationships between jobs fileSystemDiscoveryJob.AddChild(hashComparerJob); @@ -43,7 +43,7 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner hashComparerJob.AddParent(fileSystemDiscoveryJob); hashComparerJob.AddParent(repositoryMetadataDiscoveryJob); - if (library.DownloadMedatadaFromWeb) + if (downloadMedatadaFromWeb) { hashComparerJob.AddChild(goodReadsMetadataScrapJob); goodReadsMetadataScrapJob.AddParent(hashComparerJob); diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs new file mode 100644 index 00000000..aac900f9 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/IBookLibraryTypeScanner.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; + +/// +/// Interface defining a media library scanner for a books media library type. +/// +public interface IBookLibraryTypeScanner : IMediaTypeScanner +{ +} diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index 8ad251e1..feef8631 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -22,4 +22,8 @@ + + + + diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index bdad2fa5..162e6885 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -40,7 +40,7 @@ public class AuthorizationService : IAuthorizationService /// /// Determines whether the specified user has a specific permission. /// - /// The Id of the user for whom to check the permission. + /// The unique identifier of the user for whom to check the permission. /// The permission to check. /// Cancellation token that can be used to stop the execution. /// if the user has the specified permission, otherwise. @@ -62,7 +62,7 @@ public class AuthorizationService : IAuthorizationService /// /// Determines whether the specified user belongs to a specific role. /// - /// The Id of the user for whom to check the role. + /// The unique identifier of the user for whom to check the role. /// The role to check. /// Cancellation token that can be used to stop the execution. /// if the user is in the specified role, otherwise. @@ -78,7 +78,7 @@ public class AuthorizationService : IAuthorizationService /// Evaluates whether the specified user meets the conditions defined in the specified authorization policy. /// /// The type of authorization policy to evaluate. - /// The Id of the user for whom to evaluate the policy. + /// The unique identifier of the user for whom to evaluate the policy. /// Cancellation token that can be used to stop the execution. /// if the user satisfies the policy, otherwise. public async Task EvaluatePolicyAsync(Guid userId, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs index 760e1396..4a1a6008 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs @@ -34,7 +34,7 @@ public class Over18Policy : IOver18Policy /// /// Evaluates the policy for the user identified by . /// - /// The Id of the user for which to evaluate the policy. + /// The unique identifier of the user for which to evaluate the policy. /// Cancellation token that can be used to stop the execution. /// if the policy evaluation succeeds, otherwise. public async Task EvaluateAsync(Guid userId, CancellationToken cancellationToken) diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index 5f8c6fe2..e6294167 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -16,9 +16,10 @@ public static partial class ApiRoutes public const string ADD_LIBRARY = "/libraries"; public const string UPDATE_LIBRARY = "/libraries/{id}"; public const string DELETE_LIBRARY = "/libraries/{id}"; - public const string SCAN_LIBRARIES = "/libraries/scan"; - public const string SCAN_LIBRARY = "/libraries/{id}/scan"; - public const string CANCEL_LIBRARIES_SCAN = "/libraries/cancel-scan"; - public const string CANCEL_LIBRARY_SCAN = "/libraries/{id}/cancel-scan"; + public const string SCAN_LIBRARIES = "/libraries/scans"; + public const string SCAN_LIBRARY = "/libraries/{id}/scans"; + public const string LIBRARY_SCAN_PROGRESS = "/libraries/{libraryId}/scans/{scanId}/progress"; + public const string CANCEL_LIBRARIES_SCAN = "/libraries/scans/cancel"; + public const string CANCEL_LIBRARY_SCAN = "/libraries/{libraryId}/scans/{scanId}/cancel"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs index 55780e92..44668f34 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs @@ -28,7 +28,7 @@ public class DeleteRoleEndpointSummary : Summary r.RoleId, "The Id of the role. Required."); + RequestParam(r => r.RoleId, "The unique identifier of the role. Required."); Response(204, "The authorization role was successfuly deleted."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs index f2594f48..e6c1b78d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs @@ -34,7 +34,7 @@ public class UpdateRoleEndpointSummary : Summary r.RoleId, "The Id of the role. Required."); + RequestParam(r => r.RoleId, "The unique identifier of the role. Required."); RequestParam(r => r.RoleName, "The name of the role. Required."); RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Required."); 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 426d33ad..72cc4a77 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 @@ -48,7 +48,7 @@ public class AddLibraryEndpointSummary : Summary r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); ResponseParam(r => r.Id, "The unique identifier of the entity."); - ResponseParam(r => r.UserId, "The Id of the user owning the media library."); + ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); ResponseParam(r => r.Title, "The title of the media library."); ResponseParam(r => r.LibraryType, "The type of the media library."); ResponseParam(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs index df9c5a71..1290f045 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrariesScan; /// -/// API endpoint for the /libraries/cancel-scan route. +/// API endpoint for the /libraries/scans/cancel route. /// public class CancelLibrariesScanEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs index c99c5d18..5c6bc552 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs @@ -21,7 +21,7 @@ public class CancelLibrariesScanEndpointSummary : Summary -/// API endpoint for the /libraries/{id}/cancel-scan route. +/// API endpoint for the /libraries/{libraryId}/scans/{scanId}/cancel route. /// public class CancelLibraryScanEndpoint : BaseEndpoint { @@ -46,7 +48,7 @@ public class CancelLibraryScanEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false); + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.NoContent(), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs index bead73d8..13715b50 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -10,15 +12,23 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrar /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class CancelLibraryScanEndpointSummary : Summary +public class CancelLibraryScanEndpointSummary : Summary { /// /// Initializes a new instance of the class. /// public CancelLibraryScanEndpointSummary() { - Summary = "Cancells the previously started scan of a media library."; - Description = "Cancells the scanning process of a media library of a user, if the user making the request is an Admin or the library belongs to them."; + Summary = "Cancels the previously started scan of a media library."; + Description = "Cancels the scanning process of a media library of a user, if the user making the request is an Admin or the library belongs to them."; + + ExampleRequest = new CancelLibraryScanRequest( + LibraryId: Guid.NewGuid(), + ScanId: Guid.NewGuid() + ); + + RequestParam(r => r.LibraryId, "The unique identifier of the media library whose scan is cancelled. Required."); + RequestParam(r => r.ScanId, "The Id of scan to cancel. Required."); Response(204, "The media library scan was successfully cancelled."); @@ -31,7 +41,7 @@ public class CancelLibraryScanEndpointSummary : Summary { { "General.Validation", new[] { - "LibraryIdCannotBeEmpty" + "LibraryIdCannotBeEmpty", + "ScanIdCannotBeEmpty" } } }, diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs index acccbc28..c6236839 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs @@ -28,7 +28,7 @@ public class DeleteLibraryEndpointSummary : Summary r.Id, "The Id of the media library to be deleted. Required."); + RequestParam(r => r.Id, "The unique identifier of the media library to be deleted. Required."); Response(200, "The media library was successfuly deleted."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointSummary.cs index 7d8471c3..e005100d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointSummary.cs @@ -28,10 +28,10 @@ public class GetLibraryEndpointSummary : Summary r.Id, "The Id of the media library. Required."); + RequestParam(r => r.Id, "The unique identifier of the media library. Required."); ResponseParam(r => r.Id, "The unique identifier of the entity."); - ResponseParam(r => r.UserId, "The Id of the user owning the media library."); + ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); ResponseParam(r => r.Title, "The title of the media library."); ResponseParam(r => r.LibraryType, "The type of the media library."); ResponseParam(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs index 6fa7329d..c0e8b12a 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries; /// -/// API endpoint for the /libraries/scan route. +/// API endpoint for the /libraries/scans route. /// public class ScanLibrariesEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs index 36641e04..7bd56f18 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs @@ -42,7 +42,7 @@ public class ScanLibrariesEndpointSummary : Summary -/// API endpoint for the /libraries/{id}/scan route. +/// API endpoint for the /libraries/{id}/scans route. /// public class ScanLibraryEndpoint : BaseEndpoint { private readonly ISender _sender; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected service for mediating commands and queries. public ScanLibraryEndpoint(ISender sender) diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs index c7e7c538..f482c598 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs @@ -37,7 +37,7 @@ public class ScanLibraryEndpointSummary : Summary { { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs index 90f5c304..28acbb3a 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs @@ -40,8 +40,8 @@ public class UpdateLibraryEndpointSummary : Summary r.Id, "The Id of the media library. Required."); - RequestParam(r => r.UserId, "The Id of the user owning the media library. Required."); + RequestParam(r => r.Id, "The unique identifier of the media library. Required."); + RequestParam(r => r.UserId, "The unique identifier of the user owning the media library. Required."); RequestParam(r => r.Title, "The title of the media library. Required."); RequestParam(r => r.LibraryType, "The type of the media library. Required."); RequestParam(r => r.ContentLocations, ">The file system paths of the directories where the media library elements are located. Required."); @@ -52,7 +52,7 @@ public class UpdateLibraryEndpointSummary : Summary r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); ResponseParam(r => r.Id, "The unique identifier of the entity."); - ResponseParam(r => r.UserId, "The Id of the user owning the media library."); + ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); ResponseParam(r => r.Title, "The title of the media library."); ResponseParam(r => r.LibraryType, "The type of the media library."); ResponseParam(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs index e8ee6ec9..76342905 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs @@ -28,7 +28,7 @@ public class GetAuthorizationEndpointSummary : Summary r.UserId, "The Id of the user for whom to get the authorization. Required."); + RequestParam(r => r.UserId, "The unique identifier of the user for whom to get the authorization. Required."); Response(200, "The authorization role and permissions of the account are returned.", example: new AuthorizationResponse( diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs index 9d04572f..b185a332 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs @@ -28,7 +28,7 @@ public class GetUserPermissionsEndpointSummary : Summary r.UserId, "The Id of the user for whom to get the authorization permissions. Required."); + RequestParam(r => r.UserId, "The unique identifier of the user for whom to get the authorization permissions. Required."); Response(200, "The authorization permissions of the user are returned.", example: new[] { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs index 00f441d1..3d3fe5d7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs @@ -28,7 +28,7 @@ public class GetUserRoleEndpointSummary : Summary r.UserId, "The Id of the user for whom to get the authorization role. Required."); + RequestParam(r => r.UserId, "The unique identifier of the user for whom to get the authorization role. Required."); Response(200, "The authorization role of the user is returned.", example: new RoleResponse( diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs index 96fddeed..54751b3c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs @@ -34,8 +34,8 @@ public class UpdateUserRoleAndPermissionsEndpointSummary : Summary r.UserId, "The Id of the user. Required."); - RequestParam(r => r.RoleId, "The Id of the role. Optional."); + RequestParam(r => r.UserId, "The unique identifier of the user. Required."); + RequestParam(r => r.RoleId, "The unique identifier of the role. Optional."); RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Optional."); ResponseParam(r => r.UserId, "The id of the user whose role and permissions were updated."); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs index e1b743e0..4436f3a9 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs @@ -9,7 +9,7 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; /// /// Represents the response model for an account authorization request. /// -/// The Id of the user for whom the authorization is retrieved. +/// The unique identifier of the user for whom the authorization is retrieved. /// The role associated to the user. /// The collection of permissions associated to the user. [DebuggerDisplay("UserId: {UserId}")] diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs index 14de666f..7ace0b3d 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; /// /// Represents a model for an authorization permission. /// -/// The Id of the authorization permission. +/// The unique identifier of the authorization permission. /// The authorization permission. public record PermissionModel( Guid Id, diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs index aa41a538..bc1a3ac4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; /// /// Represents a model for an authorization role. /// -/// The Id of the authorization role. +/// The unique identifier of the authorization role. /// The authorization role. public record RoleModel( Guid Id, diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs index 3fa994fd..f70a2f1f 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; /// /// Represents the request model for updating an existing authorization role. /// -/// The Id of the role. +/// The unique identifier of the role. /// The name of the role. /// The collection of Ids of the permissions of the role. public record UpdateRoleRequestModel( diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs index 9342aaf8..a76ce7aa 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs @@ -8,8 +8,8 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; /// /// Represents the request model for updating the authorization role and permissions of a user. /// -/// The Id of the user. -/// The Id of the role. +/// The unique identifier of the user. +/// The unique identifier of the role. /// The collection of Ids of the permissions of the user. public record UpdateUserRoleAndPermissionsRequestModel( Guid UserId, diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs index a5662424..18989cb0 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Models.UsersManagement; /// /// Represents the response model for a user authentication. /// -/// The Id of the logged in user. +/// The unique identifier of the logged in user. /// The username of the logged in user. /// The JWT authentication token, if authentication failed or TOTP is required. /// Indicates whether the user has Two-Factor Authentication enabled, or not. diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserModel.cs index 681d041d..bee24edf 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserModel.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Models.UsersManagement; /// /// Represents a model for a user. /// -/// The Id of the user. +/// The unique identifier of the user. /// The username of the user. public record UserModel( Guid Id, diff --git a/src/Lumina.Presentation.Web/Controllers/AdminController.cs b/src/Lumina.Presentation.Web/Controllers/AdminController.cs index 9805047f..d09fc47d 100644 --- a/src/Lumina.Presentation.Web/Controllers/AdminController.cs +++ b/src/Lumina.Presentation.Web/Controllers/AdminController.cs @@ -60,7 +60,7 @@ public class AdminController : Controller /// /// Gets the authorization permissions of a role identified by . /// - /// The Id of the role for which to get the list of permissions. + /// The unique identifier of the role for which to get the list of permissions. /// Cancellation token that can be used to stop the execution. [HttpGet("api-get-permissions-by-role-id/{roleId}")] public async Task GetPermissionsByRoleId(Guid roleId, CancellationToken cancellationToken) @@ -72,7 +72,7 @@ public class AdminController : Controller /// /// Gets the authorization permissions of a user identified by . /// - /// The Id of the user for whom to get the list of permissions. + /// The unique identifier of the user for whom to get the list of permissions. /// Cancellation token that can be used to stop the execution. [HttpGet("api-get-permissions-by-user-id/{userId}")] public async Task GetPermissionsByUserId(Guid userId, CancellationToken cancellationToken) @@ -84,7 +84,7 @@ public class AdminController : Controller /// /// Gets the authorization role of a user identified by . /// - /// The Id of the user for whom to get the role. + /// The unique identifier of the user for whom to get the role. /// Cancellation token that can be used to stop the execution. [HttpGet("api-get-role-by-user-id/{userId}")] public async Task GetRoleByUserId(Guid userId, CancellationToken cancellationToken) @@ -131,7 +131,7 @@ public class AdminController : Controller /// /// Deletes an authorization role. /// - /// The Id of the role to be deleted. + /// The unique identifier of the role to be deleted. /// Cancellation token that can be used to stop the execution. [HttpDelete("api-delete-role/{roleId}")] public async Task DeleteRole(Guid roleId, CancellationToken cancellationToken) diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs index 83c38f45..8e296e91 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -121,7 +121,7 @@ public class LibraryManagementController : Controller [HttpPost("api-scan-libraries")] public async Task ScanAllLibraries(CancellationToken cancellationToken = default) { - ScanLibraryModel[] response = await _apiHttpClient.PostAsync($"libraries/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + ScanLibraryModel[] response = await _apiHttpClient.PostAsync($"libraries/scans", new EmptyModel(), cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } @@ -133,30 +133,31 @@ public class LibraryManagementController : Controller [HttpPost("api-scan-library/{id}")] public async Task ScanLibrary(Guid id, CancellationToken cancellationToken = default) { - ScanLibraryModel response = await _apiHttpClient.PostAsync($"libraries/{id}/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + ScanLibraryModel response = await _apiHttpClient.PostAsync($"libraries/{id}/scans", new EmptyModel(), cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } /// - /// Cancells the previously started scan of all media libraries. + /// Cancels the previously started scan of all media libraries. /// /// Cancellation token that can be used to stop the execution. [HttpPost("api-cancel-libraries-scan")] public async Task CancelLibrariesScan(CancellationToken cancellationToken = default) { - await _apiHttpClient.PostAsync($"libraries/cancel-scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PostAsync($"libraries/scans/cancel", new EmptyModel(), cancellationToken).ConfigureAwait(false); return Json(new { success = true }); } /// - /// Cancells the previously started scan of a media library. + /// Cancels the previously started scan of a media library. /// - /// The id of the media library whose scan is cancelled. + /// The id of the media library whose scan is cancelled. + /// The id of the scan to cancel. /// Cancellation token that can be used to stop the execution. - [HttpPost("api-cancel-library-scan/{id}")] - public async Task CancelLibraryScan(Guid id, CancellationToken cancellationToken = default) + [HttpPost("{libraryId:guid}/api-cancel-library-scan/{scanId:guid}")] + public async Task CancelLibraryScan(Guid libraryId, Guid scanId, CancellationToken cancellationToken = default) { - await _apiHttpClient.PostAsync($"libraries/{id}/cancel-scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PostAsync($"libraries/{libraryId}/scans/{scanId}/cancel", new EmptyModel(), cancellationToken).ConfigureAwait(false); return Json(new { success = true }); } } diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 816ce2a2..8d3776b1 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -549,4 +549,28 @@ Eine gesperrte Bibliothek kann nicht gescannt werden! + + Nur ausstehende Scans können gestartet werden! + + + Nur laufende Scans können abgebrochen werden! + + + Scan-ID darf nicht leer sein! + + + Die Bibliothek wird bereits gescannt! + + + Gesamtanzahl der Scan-Aufträge muss positiv sein! + + + Anzahl der abgeschlossenen Scan-Aufträge muss positiv sein! + + + Die Anzahl der abgeschlossenen Scan-Aufträge darf die Gesamtanzahl der Scan-Aufträge nicht überschreiten! + + + Aktuelle Scan-Operation darf nicht leer sein! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 83ca976f..68426de4 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -549,4 +549,28 @@ Cannot scan a locked library! + + Can only start pending scans! + + + Can only cancel running scans! + + + Scan Id cannot be empty! + + + Library is already being scanned! + + + Total scan job items count must be positive! + + + Completed scan job items count must be positive! + + + Completed scan job items count can't exceed total scan job items count! + + + Scan job current operation cannot be empty! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index bdf989a1..737b7a71 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -549,4 +549,28 @@ ¡No se puede escanear una biblioteca bloqueada! + + ¡Solo se pueden iniciar escaneos pendientes! + + + ¡Solo se pueden cancelar los escaneos en ejecución! + + + ¡El ID de escaneo no puede estar vacío! + + + ¡La biblioteca ya está siendo escaneada! + + + ¡El número total de elementos a escanear debe ser positivo! + + + ¡El número de elementos escaneados completados debe ser positivo! + + + ¡El número de elementos escaneados completados no puede exceder el número total de elementos a escanear! + + + ¡La operación actual del escaneo no puede estar vacía! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 1fabf8e4..e2d3104c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -549,4 +549,28 @@ Impossible de scanner une bibliothèque verrouillée! + + Seuls les scans en attente peuvent être démarrés ! + + + Seuls les scans en cours peuvent être annulés ! + + + L'ID de scan ne peut pas être vide ! + + + La bibliothèque est déjà en cours de scan ! + + + Le nombre total d'éléments à scanner doit être positif ! + + + Le nombre d'éléments scannés terminés doit être positif ! + + + Le nombre d'éléments scannés terminés ne peut pas dépasser le nombre total d'éléments à scanner ! + + + L'opération actuelle du scan ne peut pas être vide ! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index c773a4be..d1e01da4 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -549,4 +549,28 @@ Impossibile scansionare una libreria bloccata! + + È possibile avviare solo le scansioni in sospeso! + + + È possibile annullare solo le scansioni in esecuzione! + + + L'ID della scansione non può essere vuoto! + + + La libreria è già in fase di scansione! + + + Il numero totale degli elementi da scansionare deve essere positivo! + + + Il numero di elementi scansionati completati deve essere positivo! + + + Il numero di elementi scansionati completati non può superare il numero totale di elementi da scansionare! + + + L'operazione corrente della scansione non può essere vuota! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index d3649ed1..d7eb743a 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -549,4 +549,28 @@ ロックされたライブラリはスキャンできません! + + 保留中のスキャンのみ開始できます! + + + 実行中のスキャンのみキャンセル可能です! + + + スキャンIDを空にすることはできません! + + + ライブラリは既にスキャン中です! + + + スキャン項目の合計数は正の値でなければなりません! + + + 完了したスキャン項目数は正の値でなければなりません! + + + 完了したスキャン項目数は合計スキャン項目数を超えることはできません! + + + スキャンの現在の操作を空にすることはできません! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 27081c14..3b83eddb 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -549,4 +549,28 @@ Cannot scan a locked library! + + Can only start pending scans! + + + Can only cancel running scans! + + + Scan Id cannot be empty! + + + Library is already being scanned! + + + Total scan job items count must be positive! + + + Completed scan job items count must be positive! + + + Completed scan job items count can't exceed total scan job items count! + + + Scan job current operation cannot be empty! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index abf3a931..f6664d8c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -549,4 +549,28 @@ Nu se poate scana o bibliotecă blocată! + + Se pot porni doar scanări în așteptare! + + + Se pot anula doar scanările în curs! + + + ID-ul de scanare nu poate fi gol! + + + Biblioteca este deja în curs de scanare! + + + Numărul total de elemente de scanat trebuie să fie pozitiv! + + + Numărul de elemente scanate complet trebuie să fie pozitiv! + + + Numărul de elemente scanate complet nu poate depăși numărul total de elemente de scanat! + + + Operația curentă de scanare nu poate fi goală! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index 27e42a27..2d0db0e1 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -549,4 +549,28 @@ Невозможно сканировать заблокированную библиотеку! + + Можно запускать только ожидающие сканирования! + + + Можно отменить только запущенные сканирования! + + + Идентификатор сканирования не может быть пустым! + + + Библиотека уже сканируется! + + + Общее количество элементов для сканирования должно быть положительным! + + + Количество завершенных отсканированных элементов должно быть положительным! + + + Количество завершенных отсканированных элементов не может превышать общее количество элементов для сканирования! + + + Текущая операция сканирования не может быть пустой! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 2d31b834..6e6f4ece 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -549,4 +549,28 @@ 无法扫描已锁定的库! + + 只能启动待处理的扫描! + + + 只能取消正在运行的扫描! + + + 扫描ID不能为空! + + + 库已在扫描中! + + + 扫描任务项目总数必须为正数! + + + 已完成扫描项目数量必须为正数! + + + 已完成扫描项目数量不能超过扫描项目总数! + + + 扫描任务当前操作不能为空! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx index f34074bd..9a5a7185 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx @@ -153,6 +153,9 @@ Sind Sie sicher, dass Sie die ausgewählte Bibliothek löschen möchten? + + Dateien werden erkannt... + Dokumentarfilm diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx index 65ae5693..ee1afbb8 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx @@ -153,6 +153,9 @@ Are you sure you want to delete the specified library? + + Discovering files... + Documentary diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx index 0a254a0a..0f73abe9 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx @@ -153,6 +153,9 @@ ¿Está seguro de que desea eliminar la biblioteca especificada? + + Descubriendo archivos... + Documental diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx index 8c73c26c..9f44d8cd 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx @@ -153,6 +153,9 @@ Êtes-vous sûr de vouloir supprimer la bibliothèque spécifiée? + + Découverte des fichiers... + Documentaire diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx index 5563d276..9d8c7b3f 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx @@ -153,6 +153,9 @@ È sicuro di voler eliminare la libreria specificata? + + Rilevamento dei file... + Documentario diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx index a8a226f3..20d143e5 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx @@ -153,6 +153,9 @@ 指定されたライブラリを削除してもよろしいですか? + + ファイルを検出中... + ドキュメンタリー diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx index 65ae5693..ee1afbb8 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx @@ -153,6 +153,9 @@ Are you sure you want to delete the specified library? + + Discovering files... + Documentary diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx index 553497a1..0a7a927f 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx @@ -153,6 +153,9 @@ Sunteți sigur că doriți să ștergeți biblioteca specificată? + + Se descoperă fișierele... + Documentar diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx index 2c1c4a76..d82f2186 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx @@ -153,6 +153,9 @@ Вы уверены, что хотите удалить указанную библиотеку? + + Обнаружение файлов... + Документальный Фильм diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx index 4e1c565c..8661d496 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx @@ -153,6 +153,9 @@ 您确定要删除指定的库吗? + + 正在发现文件... + 纪录片 diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml index f8dbdcc3..ee8383aa 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml @@ -108,7 +108,7 @@ ${library.isEnabled === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} ${library.isLocked === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} - + @_localizer[ @_localizer[ @@ -155,6 +155,7 @@ data.forEach(scan => { const row = tbody.querySelector(`tr[data-library-id="${scan.libraryId}"]`); if (row) { + row.setAttribute('data-scan-id', scan.scanId); const scanIcon = row.querySelector('img[src*="trigger.svg"]'); const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); @@ -175,6 +176,7 @@ const success = await callApiPostAsync(url.replace('/@(default(Guid))', `/${libraryId}`)); if (success) { + row.setAttribute('data-scan-id', success.scanId); const scanIcon = e.target; const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); @@ -208,9 +210,24 @@ if (e.target.matches('img[src*="stop.svg"]')) { const row = e.target.closest('tr'); - const libraryId = row.getAttribute('data-library-id'); - const url = '@_urlService.GetAbsoluteUrl("CancelLibraryScan", "LibraryManagement", new { id = default(Guid) })'; - await callApiPostAsync(url.replace('/@(default(Guid))', `/${libraryId}`)); + const url = '@_urlService.GetAbsoluteUrl("CancelLibraryScan", "LibraryManagement", new { libraryId = default(Guid), scanId = default(Guid) })'; + + // make a list of values from DOM that are needed as URL query params (they need to be in the order they appear in the URL!) + const params = [ + row.getAttribute('data-library-id'), + row.getAttribute('data-scan-id') + ]; + // split URL into segments for precise replacement + const segments = url.split('/'); + let paramIndex = 0; + // replace each default GUID sequentially with the values of the query params list, in the order they were added + const finalUrl = segments.map(segment => + segment === '00000000-0000-0000-0000-000000000000' + ? params[paramIndex++] + : segment + ).join('/'); + + await callApiPostAsync(finalUrl); const scanIcon = row.querySelector('img[src*="trigger.svg"]'); const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index ba330a2d..fd182997 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -699,7 +699,7 @@ function removeHorizontalScrolling(idOrElement) { /** * Gets the position and size of an element relative to the viewport. - * @param {string} id - The Id of the element to get the offset for. + * @param {string} id - The unique identifier of the element to get the offset for. * @returns {Object} An object with the top, left, width, and height of the element. */ function getElementOffset(id) { diff --git a/src/Lumina.sln b/src/Lumina.sln index 7bd29194..36ebae26 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -178,6 +178,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architectur ..\docs\technical\architecture\3.2 component-server-diagram.puml = ..\docs\technical\architecture\3.2 component-server-diagram.puml EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-knowledge-management", "architecture-knowledge-management", "{70B56088-6D3A-481E-9459-79AC6B16FEC1}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", "architecture-decision-log", "{788FADE4-342D-4919-8E5C-10CA8EDBE954}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0001.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decission-record-0001.md + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -285,6 +292,8 @@ Global {FC005908-27A7-4BDA-BD2A-B749A09727E0} = {2C55920F-0BCB-4C64-A1E6-56053F080806} {4DC31AC0-D305-4718-8FE1-C023AF6A7CA6} = {B045C2EC-3ACB-47D3-BE62-7AC334B023D9} {D93CA337-37D5-4A42-86B5-0A2410594A7A} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} + {70B56088-6D3A-481E-9459-79AC6B16FEC1} = {D93CA337-37D5-4A42-86B5-0A2410594A7A} + {788FADE4-342D-4919-8E5C-10CA8EDBE954} = {70B56088-6D3A-481E-9459-79AC6B16FEC1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index acdab7c7..1984732e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -196,7 +196,7 @@ public class GetDirectoriesEndpointTests : IClassFixture libraryResult = Library.Create( - Guid.NewGuid(), + UserId.CreateUnique(), "Test Library", LibraryType.Book, ["C:/Books", "D:/Media/Books"], @@ -33,7 +34,8 @@ public class LibraryMappingTests true, false, true, - false + false, + [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -54,6 +56,7 @@ public class LibraryMappingTests Assert.False(result.IsLocked); Assert.True(result.DownloadMedatadaFromWeb); Assert.False(result.SaveMetadataInMediaDirectories); + Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id)); } [Fact] @@ -61,7 +64,7 @@ public class LibraryMappingTests { // Arrange ErrorOr libraryResult = Library.Create( - Guid.NewGuid(), + UserId.CreateUnique(), "Empty Library", LibraryType.Book, [], @@ -69,7 +72,8 @@ public class LibraryMappingTests true, false, true, - false + false, + [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -91,7 +95,7 @@ public class LibraryMappingTests { // Arrange ErrorOr libraryResult = Library.Create( - Guid.NewGuid(), + UserId.CreateUnique(), "Test Library", libraryType, ["C:/Media"], @@ -99,7 +103,8 @@ public class LibraryMappingTests true, false, true, - false + false, + [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -129,7 +134,7 @@ public class LibraryMappingTests ]; ErrorOr libraryResult = Library.Create( - Guid.NewGuid(), + UserId.CreateUnique(), "Test Library", LibraryType.Book, contentLocations, @@ -137,7 +142,8 @@ public class LibraryMappingTests true, false, true, - false + false, + [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -161,7 +167,7 @@ public class LibraryMappingTests ]; ErrorOr libraryResult = Library.Create( - Guid.NewGuid(), + UserId.CreateUnique(), "Test Library", LibraryType.Book, contentLocations, @@ -169,7 +175,8 @@ public class LibraryMappingTests true, false, true, - false + false, + [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -181,4 +188,37 @@ public class LibraryMappingTests Assert.Equal(library.ContentLocations.Select(l => l.Path), result.ContentLocations.Select(l => l.Path)); Assert.Null(result.CoverImage); } + + [Fact] + public void ToRepositoryEntity_WhenMappingEmptyScanList_ShouldMapCorrectly() + { + // Arrange + List contentLocations = + [ + "C:/Media/Books", + "D:/Books" + ]; + + ErrorOr libraryResult = Library.Create( + UserId.CreateUnique(), + "Test Library", + LibraryType.Book, + contentLocations, + null, + true, + false, + true, + false, + [] + ); + Library library = libraryResult.Value; + + // Act + LibraryEntity result = library.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.NotNull(library.ScanIds); + Assert.NotNull(result.LibraryScans); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs index 72ea9c0a..802a4f2b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs @@ -4,6 +4,8 @@ using ErrorOr; using Lumina.Domain.Common.Enums.MediaLibrary; 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 System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -44,7 +46,7 @@ public class DomainLibraryFixture ]; ErrorOr library = Library.Create( - Guid.NewGuid(), + UserId.CreateUnique(), _faker.Random.String2(_faker.Random.Number(1, 50)), _faker.PickRandom(), validPaths.Take(_random.Next(1, validPaths.Count)), @@ -52,7 +54,8 @@ public class DomainLibraryFixture _faker.Random.Bool(), _faker.Random.Bool(), _faker.Random.Bool(), - _faker.Random.Bool() + _faker.Random.Bool(), + [ScanId.CreateUnique(), ScanId.CreateUnique()] ); return library.Value; @@ -68,11 +71,12 @@ public class DomainLibraryFixture bool isEnabled = true, bool isLocked = false, bool downloadMedatadaFromWeb = true, - bool saveMetadataInMediaDirectories = false) + bool saveMetadataInMediaDirectories = false, + IEnumerable? scanIds = null) { ErrorOr library = id is null ? Library.Create( - userId ?? Guid.NewGuid(), + userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? LibraryType.Book, contentLocations ?? ["C:/Media"], @@ -80,11 +84,12 @@ public class DomainLibraryFixture isEnabled, isLocked, downloadMedatadaFromWeb, - saveMetadataInMediaDirectories + saveMetadataInMediaDirectories, + scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()] ) : Library.Create( LibraryId.Create(id.Value), - userId ?? Guid.NewGuid(), + userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? LibraryType.Book, contentLocations ?? ["C:/Media"], @@ -92,7 +97,8 @@ public class DomainLibraryFixture isEnabled, isLocked, downloadMedatadaFromWeb, - saveMetadataInMediaDirectories + saveMetadataInMediaDirectories, + scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()] ); return library.Value; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs index f8f053d7..806f3337 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs @@ -57,7 +57,7 @@ public class UserEntityFixture /// Creates a valid collection of user libraries. /// /// The number of user libraries to create. - /// The Id of the user for whom to create the libraries. + /// The unique identifier of the user for whom to create the libraries. /// A collection of . private static List CreateLibraries(int count, Guid userId) {