mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 20:11:10 +00:00
Returns the unit of work save changes result
This commit is contained in:
1 parent
f3e465255e
commit
64ef3a1e22
141 files changed
+1388
-1151
No files matched your search
@@ -1,12 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Themes;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -43,6 +45,21 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IBookRepository BookRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artist repository.
|
||||
/// </summary>
|
||||
IArtistRepository ArtistRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the album repository.
|
||||
/// </summary>
|
||||
IAlbumRepository AlbumRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the track repository.
|
||||
/// </summary>
|
||||
ITrackRepository TrackRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media contributor repository.
|
||||
/// </summary>
|
||||
@@ -124,10 +141,11 @@ public interface IUnitOfWork
|
||||
IUserSettingsRepository UserSettingsRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves all changes made to the database.
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
Task SaveChangesAsync(CancellationToken cancellationToken);
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
|
||||
|
||||
+10
-6
@@ -58,18 +58,18 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins can create authorization roles
|
||||
// Only admins can create authorization roles.
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
|
||||
// create the new role, with its permissions
|
||||
// Create the new role, with its permissions.
|
||||
RoleEntity newRole = new()
|
||||
{
|
||||
RoleName = request.RoleName,
|
||||
@@ -81,12 +81,16 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
|
||||
RoleId = default
|
||||
})]
|
||||
};
|
||||
// save the new role in the repository
|
||||
// Save the new role in the repository.
|
||||
Result<Created> insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
|
||||
if (insertRoleResult.IsFailure)
|
||||
return insertRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// retrieve the newly saved authorization role from the persistence medium and return it
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Retrieve the newly saved authorization role from the persistence medium and return it.
|
||||
Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsFailure)
|
||||
return getRoleResult.Errors;
|
||||
|
||||
+13
-12
@@ -1,20 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
|
||||
@@ -56,7 +52,7 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
@@ -67,19 +63,24 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
|
||||
// check if a role with the requested Id exists
|
||||
Result<RoleEntity?> getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
// Check if a role with the requested Id exists.
|
||||
Result<RoleEntity?> getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getExistingRoleResult.IsFailure)
|
||||
return getExistingRoleResult.Errors;
|
||||
else if (getExistingRoleResult.Value is null)
|
||||
return Errors.Authorization.RoleNotFound;
|
||||
else if (getExistingRoleResult.Value.RoleName == "Admin")
|
||||
return Errors.Authorization.AdminRoleCannotBeDeleted;
|
||||
// delete the role and its permissions
|
||||
|
||||
// Delete the role and its permissions.
|
||||
Result<Deleted> deleteRoleResult = await _unitOfWork.RoleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteRoleResult.IsFailure)
|
||||
return deleteRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return deleteRoleResult.Value;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return Result.Deleted;
|
||||
}
|
||||
}
|
||||
+14
-11
@@ -1,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
@@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -58,37 +57,41 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins can update authorization roles
|
||||
// Only admins can update authorization roles.
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
|
||||
// update the role and its permissions
|
||||
// Update the role and its permissions.
|
||||
RoleEntity newRole = new()
|
||||
{
|
||||
Id = command.RoleId,
|
||||
RoleName = command.RoleName,
|
||||
RolePermissions = command.Permissions.Select(permissionId => new RolePermissionEntity()
|
||||
RolePermissions = [.. command.Permissions.Select(permissionId => new RolePermissionEntity()
|
||||
{
|
||||
PermissionId = permissionId,
|
||||
Permission = null!,
|
||||
Role = null!,
|
||||
RoleId = default
|
||||
}).ToList()
|
||||
})]
|
||||
};
|
||||
// save the updated role in the repository
|
||||
// Save the updated role in the repository.
|
||||
Result<Updated> updateRoleResult = await _unitOfWork.RoleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false);
|
||||
if (updateRoleResult.IsFailure)
|
||||
return updateRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// retrieve the updated authorization role from the persistence medium and return it
|
||||
Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Retrieve the updated authorization role from the persistence medium and return it.
|
||||
Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsFailure)
|
||||
return getRoleResult.Errors;
|
||||
if (getRoleResult.Value is null)
|
||||
|
||||
+12
-9
@@ -1,18 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
@@ -89,12 +90,12 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
|
||||
return validationResult;
|
||||
|
||||
// Check if any users already exists (admin account is only set once!).
|
||||
Result<IEnumerable<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (selectUsersResult.IsFailure)
|
||||
return selectUsersResult.Errors;
|
||||
else if (selectUsersResult.Value.Any())
|
||||
else if (selectUsersResult.Value.Data.Any())
|
||||
return Errors.Authorization.AdminAccountAlreadyCreated;
|
||||
// no users are present, register the admin one
|
||||
// No users are present, register the admin one.
|
||||
string? totpSecret = null;
|
||||
Guid id = Guid.NewGuid();
|
||||
UserEntity user = new()
|
||||
@@ -123,7 +124,9 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
|
||||
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||
if (insertUserResult.IsFailure)
|
||||
return insertUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Set the default permissions, roles, roles permissions.
|
||||
Result<Created> setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
@@ -150,15 +153,15 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
|
||||
// The default jobs were seeded with an active execution cycle, so a cycle started event is queued for each of them; the
|
||||
// queued events are published only after the setup transaction commits, because a cycle worker started inside the request
|
||||
// would try to read the scheduled jobs while the still open setup transaction locks the storage medium.
|
||||
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobsResult.IsFailure)
|
||||
return getScheduledJobsResult.Errors;
|
||||
foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value)
|
||||
foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value.Data)
|
||||
if (scheduledJob.Status == ScheduledJobStatus.Active)
|
||||
_domainEventsQueue.Enqueue(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), ScheduledJobId.Create(scheduledJob.Id), DateTime.UtcNow));
|
||||
|
||||
// TODO: insert the default admin profile preferences when they are implemented.
|
||||
// If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
|
||||
// If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed.
|
||||
return new RegistrationResponse(user.Id, user.Username, totpSecret);
|
||||
}
|
||||
}
|
||||
+16
-13
@@ -83,18 +83,18 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins or users with the permission to manage media libraries can create them
|
||||
// Only admins or users with the permission to manage media libraries can create them.
|
||||
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false) &&
|
||||
!await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false))
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// make sure the file is an actual supported image
|
||||
// Make sure the file is an actual supported image.
|
||||
if (command.CoverImage is not null)
|
||||
{
|
||||
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
|
||||
@@ -108,13 +108,13 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
||||
return DomainErrors.Library.CoverFileMustBeAnImage;
|
||||
}
|
||||
|
||||
// create a domain library object
|
||||
// Create a domain library object.
|
||||
Result<Library> createLibraryResult = Library.Create(
|
||||
UserId.Create(userId),
|
||||
command.Title!,
|
||||
Enum.Parse<LibraryType>(command.LibraryType!),
|
||||
command.ContentLocations!,
|
||||
command.CoverImage,
|
||||
Optional<string>.FromNullable(command.CoverImage),
|
||||
command.IsEnabled,
|
||||
command.IsLocked,
|
||||
command.CanDownloadMetadataFromWeb,
|
||||
@@ -126,10 +126,10 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
||||
if (createLibraryResult.IsFailure)
|
||||
return createLibraryResult.Errors;
|
||||
|
||||
// convert the domain library entity to a repository library entity
|
||||
// Convert the domain library entity to a repository library entity.
|
||||
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
|
||||
// insert the repository entity, seed the provider configurations of the new library so that it lists the plugins
|
||||
// providing metadata or artwork for its type, and save the changes
|
||||
// Insert the repository entity, seed the provider configurations of the new library so that it lists the plugins
|
||||
// providing metadata or artwork for its type, and save the changes.
|
||||
Result<Created> insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
|
||||
if (insertLibraryResult.IsFailure)
|
||||
return insertLibraryResult.Errors;
|
||||
@@ -137,19 +137,22 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
||||
createLibraryResult.Value.Id.Value, Enum.Parse<LibraryType>(command.LibraryType!), cancellationToken).ConfigureAwait(false);
|
||||
if (ensureProviderConfigurationsResult.IsFailure)
|
||||
return ensureProviderConfigurationsResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// retrieve the newly saved media library from the persistence medium and return it
|
||||
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Retrieve the newly saved media library from the persistence medium and return it.
|
||||
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getCreatedLibraryResult.IsFailure)
|
||||
return getCreatedLibraryResult.Errors;
|
||||
if (getCreatedLibraryResult.Value is null)
|
||||
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
|
||||
|
||||
// mark the media library as saved
|
||||
// Mark the media library as saved.
|
||||
createLibraryResult.Value.Save();
|
||||
|
||||
// queue any domain events
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
|
||||
+14
-12
@@ -58,53 +58,55 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get the running library scans of the current user from the repository
|
||||
// Get the running library scans of the current user from the repository.
|
||||
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getRunningLibraryScansResult.IsFailure)
|
||||
return getRunningLibraryScansResult.Errors;
|
||||
|
||||
// filter the library scans to process
|
||||
// Filter the library scans to process.
|
||||
List<LibraryScanEntity> authorizedLibraryScans = [];
|
||||
// admins can see all library scans
|
||||
// Admins can see all library scans.
|
||||
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value);
|
||||
else // for regular users, only take the library scans that belong to them
|
||||
else // For regular users, only take the library scans that belong to them.
|
||||
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId));
|
||||
|
||||
// convert persistence library scans to domain entities
|
||||
// Convert persistence library scans to domain entities.
|
||||
IEnumerable<Result<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
|
||||
|
||||
List<IDomainEvent> domainEvents = [];
|
||||
|
||||
// for each library scan, perform the cancellation
|
||||
// For each library scan, perform the cancellation.
|
||||
foreach (Result<LibraryScan> libraryScanDomainResult in libraryScansDomainResult)
|
||||
{
|
||||
if (libraryScanDomainResult.IsFailure)
|
||||
return libraryScanDomainResult.Errors;
|
||||
|
||||
// cancel the media library scan
|
||||
// Cancel the media library scan.
|
||||
Result<Success> cancelScanResult = libraryScanDomainResult.Value.CancelScan();
|
||||
if (cancelScanResult.IsFailure)
|
||||
return cancelScanResult.Errors;
|
||||
|
||||
// update the status of the library scan in the repository
|
||||
// Update the status of the library scan in the repository.
|
||||
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsFailure)
|
||||
return updateLibraryScanResult.Errors;
|
||||
|
||||
// collect all the domain events created during this library scan start
|
||||
// Collect all the domain events created during this library scan start.
|
||||
domainEvents.AddRange(libraryScanDomainResult.Value.GetDomainEvents());
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// queue any domain events
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in domainEvents)
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
|
||||
+11
-9
@@ -67,43 +67,45 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get the library scan from the repository
|
||||
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
|
||||
// Get the library scan from the repository.
|
||||
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScansResult.IsFailure)
|
||||
return getLibraryScansResult.Errors;
|
||||
if (getLibraryScansResult.Value is null)
|
||||
return DomainErrors.LibraryScanning.LibraryScanNotFound;
|
||||
|
||||
// admins can cancel any library scan; for everyone else, only the ones of the libraries they own
|
||||
// Admins can cancel any library scan; for everyone else, only the ones of the libraries they own.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(getLibraryScansResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// convert the repository scan to a domain object
|
||||
// Convert the repository scan to a domain object.
|
||||
Result<LibraryScan> libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsFailure)
|
||||
return libraryScanDomainResult.Errors;
|
||||
|
||||
// cancel the media library scan
|
||||
// Cancel the media library scan.
|
||||
Result<Success> cancelScanResult = libraryScanDomainResult.Value.CancelScan();
|
||||
if (cancelScanResult.IsFailure)
|
||||
return cancelScanResult.Errors;
|
||||
|
||||
// update the status of the library scan in the repository
|
||||
// Update the status of the library scan in the repository.
|
||||
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsFailure)
|
||||
return updateLibraryScanResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// queue any domain events
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in libraryScanDomainResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
|
||||
+13
-10
@@ -72,48 +72,51 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get the library with the specified id from the repository
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
// Get the library with the specified id from the repository.
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
else if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
|
||||
// admins can delete any library; for everyone else, only the libraries they own
|
||||
// Admins can delete any library; for everyone else, only the libraries they own.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// create a domain library object
|
||||
// Create a domain library object.
|
||||
Result<Library> createLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (createLibraryResult.IsFailure)
|
||||
return createLibraryResult.Errors;
|
||||
|
||||
// delete the domain aggregate
|
||||
// Delete the domain aggregate.
|
||||
Result<Deleted> deleteDomainLibraryResult = createLibraryResult.Value.Delete();
|
||||
if (deleteDomainLibraryResult.IsFailure)
|
||||
return deleteDomainLibraryResult.Errors;
|
||||
|
||||
// queue any domain events
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// remove the provider configurations of the library, so that they are not orphaned, and delete the library
|
||||
// Remove the provider configurations of the library, so that they are not orphaned, and delete the library.
|
||||
Result<Deleted> removeProviderConfigurationsResult = await _providerConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (removeProviderConfigurationsResult.IsFailure)
|
||||
return removeProviderConfigurationsResult.Errors;
|
||||
Result<Deleted> deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (deletePersistenceLibraryResult.IsFailure)
|
||||
return deletePersistenceLibraryResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return deletePersistenceLibraryResult;
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return Result.Deleted;
|
||||
}
|
||||
}
|
||||
+16
-14
@@ -61,46 +61,46 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get all media libraries that are enabled and unlocked from the persistence medium
|
||||
// Get all media libraries that are enabled and unlocked from the persistence medium.
|
||||
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getLibrariesResult.IsFailure)
|
||||
return getLibrariesResult.Errors;
|
||||
|
||||
// convert persistence libraries to domain entities
|
||||
// Convert persistence libraries to domain entities.
|
||||
IEnumerable<Result<Library>> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities();
|
||||
|
||||
// if the current user is not an admin, they can only scan the libraries that belong to them
|
||||
// If the current user is not an admin, they can only scan the libraries that belong to them.
|
||||
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == userId);
|
||||
|
||||
List<MediaLibraryScanResponse> responses = [];
|
||||
List<IDomainEvent> domainEvents = [];
|
||||
|
||||
// for each library, start the scan
|
||||
// For each library, start the scan.
|
||||
foreach (Result<Library> domainLibraryResult in domainEntitiesResult)
|
||||
{
|
||||
if (domainLibraryResult.IsFailure)
|
||||
return domainLibraryResult.Errors;
|
||||
|
||||
// get the past month's scans for this library
|
||||
// Get the past month's scans for this library.
|
||||
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult =
|
||||
await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (pastLibraryScansResult.IsFailure)
|
||||
return pastLibraryScansResult.Errors;
|
||||
|
||||
// convert the repository scans history to domain objects
|
||||
// Convert the repository scans history to domain objects.
|
||||
IEnumerable<Result<LibraryScan>> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities();
|
||||
foreach (Result<LibraryScan> pastLibraryScanDomainResult in pastLibraryScansDomainResult)
|
||||
if (pastLibraryScanDomainResult.IsFailure)
|
||||
return pastLibraryScanDomainResult.Errors;
|
||||
|
||||
// start the media library scan
|
||||
// Start the media library scan.
|
||||
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
|
||||
LibraryId.Create(domainLibraryResult.Value.Id.Value),
|
||||
UserId.Create(userId),
|
||||
@@ -110,25 +110,27 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
|
||||
return libraryScanResult.Errors;
|
||||
|
||||
Result<Success> 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
|
||||
// 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.IsFailure)
|
||||
continue;
|
||||
|
||||
// add the library scan to the persistence medium
|
||||
// Add the library scan to the persistence medium.
|
||||
Result<Created> insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertLibraryScanResult.IsFailure)
|
||||
return insertLibraryScanResult.Errors;
|
||||
|
||||
// collect all the domain events created during this library scan start
|
||||
// Collect all the domain events created during this library scan start.
|
||||
domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents());
|
||||
|
||||
responses.Add(new MediaLibraryScanResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value));
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// queue any domain events
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in domainEvents)
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
|
||||
+14
-12
@@ -73,50 +73,50 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get the media library from the persistence medium
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
// Get the media library from the persistence medium.
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
|
||||
// admins can scan any library; for everyone else, only the libraries they own
|
||||
// Admins can scan any library; for everyone else, only the libraries they own.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// check if the library is enabled and unlocked, before scanning it
|
||||
// Check if the library is enabled and unlocked, before scanning it.
|
||||
if (!getLibraryResult.Value.IsEnabled)
|
||||
return DomainErrors.Library.CannotScanDisabledLibrary;
|
||||
|
||||
if (getLibraryResult.Value.IsLocked)
|
||||
return DomainErrors.Library.CannotScanLockedLibrary;
|
||||
|
||||
// convert the persistence library to a domain entity
|
||||
// Convert the persistence library to a domain entity.
|
||||
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsFailure)
|
||||
return domainLibraryResult.Errors;
|
||||
|
||||
// get the past month's scans for this library
|
||||
// Get the past month's scans for this library.
|
||||
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (pastLibraryScansResult.IsFailure)
|
||||
return pastLibraryScansResult.Errors;
|
||||
|
||||
// convert the repository scans history to domain objects
|
||||
// Convert the repository scans history to domain objects.
|
||||
IEnumerable<Result<LibraryScan>> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities();
|
||||
foreach (Result<LibraryScan> pastLibraryScanDomainResult in pastLibraryScansDomainResult)
|
||||
if (pastLibraryScanDomainResult.IsFailure)
|
||||
return pastLibraryScanDomainResult.Errors;
|
||||
|
||||
// queue the media library scan
|
||||
// Queue the media library scan.
|
||||
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
|
||||
LibraryId.Create(command.Id),
|
||||
UserId.Create(userId),
|
||||
@@ -129,14 +129,16 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
|
||||
if (queueScanResult.IsFailure)
|
||||
return queueScanResult.Errors;
|
||||
|
||||
// add the library scan to the persistence medium
|
||||
// Add the library scan to the persistence medium.
|
||||
Result<Created> insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertLibraryScanResult.IsFailure)
|
||||
return insertLibraryScanResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// queue any domain events
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in libraryScanResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
|
||||
+18
-16
@@ -87,21 +87,21 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get a library repository and retrieve the library to update
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||
// Get a library repository and retrieve the library to update.
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
else if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
|
||||
// make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is
|
||||
// relative to the application base directory and is already validated, so it must not block saving unrelated changes
|
||||
// Make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is
|
||||
// relative to the application base directory and is already validated, so it must not block saving unrelated changes.
|
||||
if (command.CoverImage is not null && command.CoverImage != getLibraryResult.Value.CoverImage)
|
||||
{
|
||||
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
|
||||
@@ -115,14 +115,14 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
return DomainErrors.Library.CoverFileMustBeAnImage;
|
||||
}
|
||||
|
||||
// admins or users with the permission to manage media libraries can update any library; other users can only update the libraries they own
|
||||
// Admins or users with the permission to manage media libraries can update any library; other users can only update the libraries they own.
|
||||
bool hasManagePermission = await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false);
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
|
||||
if (!hasManagePermission && !canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// create a domain library object
|
||||
// Create a domain library object.
|
||||
LibraryType newLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
|
||||
Result<Library> createLibraryResult = Library.Create(
|
||||
LibraryId.Create(command.Id),
|
||||
@@ -130,7 +130,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
command.Title!,
|
||||
newLibraryType,
|
||||
command.ContentLocations!,
|
||||
command.CoverImage,
|
||||
Optional<string>.FromNullable(command.CoverImage),
|
||||
command.IsEnabled,
|
||||
command.IsLocked,
|
||||
command.CanDownloadMetadataFromWeb,
|
||||
@@ -140,11 +140,11 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
);
|
||||
if (createLibraryResult.IsFailure)
|
||||
return createLibraryResult.Errors;
|
||||
// convert the domain library entity to a repository library entity
|
||||
// Convert the domain library entity to a repository library entity.
|
||||
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
|
||||
|
||||
// update the repository entity, and when the library type changed, reconcile the provider configurations so that
|
||||
// they match the plugins supporting the new type, and save the changes
|
||||
// Update the repository entity, and when the library type changed, reconcile the provider configurations so that
|
||||
// they match the plugins supporting the new type, and save the changes.
|
||||
Result<Updated> updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryResult.IsFailure)
|
||||
return updateLibraryResult.Errors;
|
||||
@@ -154,19 +154,21 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
if (reconcileResult.IsFailure)
|
||||
return reconcileResult.Errors;
|
||||
}
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// retrieve the updated media library from the persistence medium and return it
|
||||
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
// Retrieve the updated media library from the persistence medium and return it.
|
||||
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getCreatedLibraryResult.IsFailure)
|
||||
return getCreatedLibraryResult.Errors;
|
||||
if (getCreatedLibraryResult.Value is null)
|
||||
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
|
||||
|
||||
// mark the media library as saved
|
||||
// Mark the media library as saved.
|
||||
createLibraryResult.Value.Save();
|
||||
|
||||
// queue any domain events
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
|
||||
+8
-6
@@ -48,7 +48,7 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<Lib
|
||||
{
|
||||
Guid libraryId = domainEvent.LibraryId.Value;
|
||||
|
||||
// load the book stored at the deleted path, which might have been already removed
|
||||
// Load the book stored at the deleted path, which might have been already removed.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
throw new EventualConsistencyException(getBookResult.FirstError, getBookResult.Errors);
|
||||
@@ -56,8 +56,8 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<Lib
|
||||
if (book is null)
|
||||
return;
|
||||
|
||||
// delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
|
||||
// Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new EventualConsistencyException(getLibraryResult.FirstError, getLibraryResult.Errors);
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
@@ -71,11 +71,13 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<Lib
|
||||
if (deleteArtworkResult.IsFailure)
|
||||
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
|
||||
|
||||
// delete the book, whose stored artwork and participations are removed by the database cascade
|
||||
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteAsync(book.Id, cancellationToken).ConfigureAwait(false);
|
||||
// Delete the book, whose stored artwork and participations are removed by the database cascade.
|
||||
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteBookResult.IsFailure)
|
||||
throw new EventualConsistencyException(deleteBookResult.FirstError, deleteBookResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
}
|
||||
}
|
||||
+24
-22
@@ -58,21 +58,23 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask HandleAsync(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
if (domainEvent.Library.CoverImage is not null)
|
||||
if (domainEvent.Library.CoverImage.HasValue)
|
||||
{
|
||||
// attempt to copy the image from the original location provided by the user to the internal location for media library files
|
||||
Result<string> saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage, cancellationToken).ConfigureAwait(false);
|
||||
// Attempt to copy the image from the original location provided by the user to the internal location for media library files.
|
||||
Result<string> saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (saveCoverImageResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors);
|
||||
domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value);
|
||||
// update the media library with the new cover location
|
||||
// Update the media library with the new cover location.
|
||||
Result<Updated> updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
}
|
||||
else // no cover image is provided, delete any cover image that might exist in the internal location for media library files
|
||||
else // No cover image is provided, delete any cover image that might exist in the internal location for media library files.
|
||||
{
|
||||
Result<string> libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value);
|
||||
if (libraryPathResult.IsFailure)
|
||||
@@ -90,17 +92,17 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
/// </returns>
|
||||
private Result<string> GetLibraryPath(Guid libraryId)
|
||||
{
|
||||
// root directory for media
|
||||
// Root directory for media.
|
||||
Result<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory);
|
||||
if (rootPathResult.IsFailure)
|
||||
return rootPathResult.Errors;
|
||||
|
||||
// libraries directory
|
||||
// Libraries directory.
|
||||
Result<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory);
|
||||
if (librariesPathResult.IsFailure)
|
||||
return librariesPathResult.Errors;
|
||||
|
||||
// this new particular library' directory
|
||||
// This new particular library's directory.
|
||||
Result<string> libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString());
|
||||
if (libraryPathResult.IsFailure)
|
||||
return libraryPathResult.Errors;
|
||||
@@ -142,8 +144,8 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
if (fileExistsResult.IsFailure)
|
||||
return fileExistsResult.Errors;
|
||||
|
||||
// when the library is saved without changing its cover, the stored cover image path is already the internal media directory
|
||||
// path, relative to the application base directory; resolve it against the base directory and keep it when the file is found
|
||||
// When the library is saved without changing its cover, the stored cover image path is already the internal media directory
|
||||
// path, relative to the application base directory; resolve it against the base directory and keep it when the file is found.
|
||||
if (!fileExistsResult.Value)
|
||||
{
|
||||
Result<FileSystemPathId> internalImagePathIdResult = ResolveInternalMediaPathId(imagePath);
|
||||
@@ -157,19 +159,19 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
}
|
||||
|
||||
// make sure the file is an actual supported image
|
||||
// Make sure the file is an actual supported image.
|
||||
Result<ImageType> imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (imageCheckResult.IsFailure)
|
||||
return imageCheckResult.Errors;
|
||||
if (imageCheckResult.Value == ImageType.None)
|
||||
return Errors.Library.CoverFileMustBeAnImage;
|
||||
|
||||
// the provided cover image path exists and is a valid image, store it in the media directory
|
||||
Result<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // root directory for media
|
||||
// The provided cover image path exists and is a valid image, store it in the media directory.
|
||||
Result<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // Root directory for media.
|
||||
if (rootPathResult.IsFailure)
|
||||
return rootPathResult.Errors;
|
||||
|
||||
Result<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // libraries directory
|
||||
Result<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // Libraries directory.
|
||||
if (librariesPathResult.IsFailure)
|
||||
return librariesPathResult.Errors;
|
||||
|
||||
@@ -181,7 +183,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
if (librariesPathIdResult.IsFailure)
|
||||
return librariesPathIdResult.Errors;
|
||||
|
||||
// create the path of the new library
|
||||
// Create the path of the new library.
|
||||
Result<string> libraryPathResult = GetLibraryPath(libraryId);
|
||||
if (libraryPathResult.IsFailure)
|
||||
return libraryPathResult.Errors;
|
||||
@@ -190,7 +192,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
if (newLibraryPathIdResult.IsFailure)
|
||||
return newLibraryPathIdResult.Errors;
|
||||
|
||||
// check if it doesn't already exist, and if so, create it
|
||||
// Check if it doesn't already exist, and if so, create it.
|
||||
Result<bool> directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(newLibraryPathIdResult.Value);
|
||||
if (directoryExistsResult.IsFailure)
|
||||
return directoryExistsResult.Errors;
|
||||
@@ -203,24 +205,24 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
}
|
||||
else
|
||||
{
|
||||
// delete previous library covers that might exist
|
||||
// Delete previous library covers that might exist.
|
||||
DeleteCoverImageFromMediaDirectory(libraryPathResult.Value);
|
||||
|
||||
Result<Deleted> deleteExistingCoverImageResult = DeleteCoverImageFromMediaDirectory(libraryPathResult.Value);
|
||||
if (deleteExistingCoverImageResult.IsFailure)
|
||||
return deleteExistingCoverImageResult.Errors;
|
||||
}
|
||||
// copy the new cover file from the location provided by the user
|
||||
// Copy the new cover file from the location provided by the user.
|
||||
Result<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(fileSystemPathIdResult.Value, newLibraryPathIdResult.Value, true);
|
||||
if (copyFileResult.IsFailure)
|
||||
return copyFileResult.Errors;
|
||||
|
||||
// rename the new cover file to the standard naming
|
||||
// Rename the new cover file to the standard naming.
|
||||
Result<FileSystemPathId> renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageCheckResult.Value.ToString().ToLower()}");
|
||||
if (renameFileResult.IsFailure)
|
||||
return renameFileResult.Errors;
|
||||
|
||||
// get the internal relative path for the copied file
|
||||
// Get the internal relative path for the copied file.
|
||||
string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..];
|
||||
if (!relativePath.StartsWith(_pathService.PathSeparator))
|
||||
relativePath = $"{_pathService.PathSeparator}{relativePath}";
|
||||
@@ -239,7 +241,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
if (newLibraryPathIdResult.IsFailure)
|
||||
return newLibraryPathIdResult.Errors;
|
||||
|
||||
// get existing files of this media library's directory, and delete previous cover files, if they are found
|
||||
// Get existing files of this media library's directory, and delete previous cover files, if they are found.
|
||||
Result<IEnumerable<FileSystemPathId>> getExistingLibraryFilesResult = _environmentContext.FileProviderService.GetFilePaths(newLibraryPathIdResult.Value, true);
|
||||
if (getExistingLibraryFilesResult.IsFailure)
|
||||
return getExistingLibraryFilesResult.Errors;
|
||||
|
||||
+12
-10
@@ -54,41 +54,43 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibrarySc
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// get the library scan from the repository
|
||||
// Get the library scan from the repository.
|
||||
Result<LibraryScanEntity?> getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(
|
||||
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors);
|
||||
if (getLibraryScanResult.Value is null)
|
||||
throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound);
|
||||
|
||||
// convert the repository scan to a domain object
|
||||
// Convert the repository scan to a domain object.
|
||||
Result<LibraryScan> libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsFailure)
|
||||
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
|
||||
|
||||
// mark the media library scan as failed
|
||||
// Mark the media library scan as failed.
|
||||
Result<Success> failScanResult = libraryScanDomainResult.Value.FailScan();
|
||||
// we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event,
|
||||
// trying to set as failed a scan that has already been marked as failed by a concurrent job
|
||||
// We're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan 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.IsFailure)
|
||||
{
|
||||
// update the status of the library scan in the repository
|
||||
// Update the status of the library scan in the repository.
|
||||
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
}
|
||||
|
||||
// release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job
|
||||
// Release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job.
|
||||
_mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId);
|
||||
_mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId);
|
||||
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (clearStagingResult.IsFailure)
|
||||
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
|
||||
|
||||
// notify SignalR clients that the library scan failed
|
||||
// Notify SignalR clients that the library scan failed.
|
||||
await _debouncedLibraryScanProgressNotifier.SendLibraryScanFailedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+11
-9
@@ -54,36 +54,38 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler<Library
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// get the library scan from the repository
|
||||
// Get the library scan from the repository.
|
||||
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(
|
||||
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScansResult.IsFailure)
|
||||
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
|
||||
// Convert the repository scan to a domain object.
|
||||
Result<LibraryScan> libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsFailure)
|
||||
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
|
||||
|
||||
// mark the media library scan as finished
|
||||
// Mark the media library scan as finished.
|
||||
Result<Success> finishScanResult = libraryScanDomainResult.Value.FinishScan();
|
||||
if (finishScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors);
|
||||
|
||||
// update the library scan in the repository
|
||||
// Update the library scan in the repository.
|
||||
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
|
||||
// mark the scan progress as finished
|
||||
// Mark the scan progress as finished.
|
||||
_mediaLibrariesScanProgressTracker.UpdateScanProgress(libraryScanDomainResult.Value.LibraryId, domainEvent.MediaLibraryScanCompositeId);
|
||||
// notify SignalR clients that the library scan finished
|
||||
// Notify SignalR clients that the library scan finished.
|
||||
await _debouncedLibraryScanProgressNotifier.SendLibraryScanFinishedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
||||
// only when everything is done, this needs to be called in order to dispose cancellation token sources, etc
|
||||
// Only when everything is done, this needs to be called in order to dispose cancellation token sources, etc.
|
||||
_mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -35,11 +35,13 @@ public class LibraryScanStartedDomainEventHandler : IDomainEventHandler<LibraryS
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// update the status of the library scan in the repository
|
||||
// Update the status of the library scan in the repository.
|
||||
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -57,23 +57,26 @@ public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler<Reor
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// admins can reorder the artwork providers of any library; for everyone else, only their own libraries
|
||||
// Admins can reorder the artwork providers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// Load the artwork provider configurations that are currently registered for the library, so that only providers it actually has are reordered.
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
|
||||
// Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list.
|
||||
Dictionary<Guid, LibraryArtworkProviderConfigurationEntity> configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId);
|
||||
// Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice.
|
||||
for (int rank = 0; rank < command.PluginIds.Count; rank++)
|
||||
{
|
||||
Guid pluginId = command.PluginIds[rank];
|
||||
@@ -86,7 +89,10 @@ public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler<Reor
|
||||
}
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Persist all the rank changes in a single save, so that the reorder is applied atomically.
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -56,23 +56,26 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<Reo
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// admins can reorder the metadata providers of any library; for everyone else, only their own libraries
|
||||
// Admins can reorder the metadata providers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// Load the metadata provider configurations that are currently registered for the library, so that only providers it actually has are reordered.
|
||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
|
||||
// Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list.
|
||||
Dictionary<Guid, LibraryMetadataProviderConfigurationEntity> configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId);
|
||||
// Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice.
|
||||
for (int rank = 0; rank < command.PluginIds.Count; rank++)
|
||||
{
|
||||
Guid pluginId = command.PluginIds[rank];
|
||||
@@ -85,7 +88,10 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<Reo
|
||||
}
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Persist all the rank changes in a single save, so that the reorder is applied atomically.
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -56,18 +56,19 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler<Se
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// admins can configure the artwork providers of any library; for everyone else, only their own libraries
|
||||
// Admins can configure the artwork providers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated.
|
||||
Result<LibraryArtworkProviderConfigurationEntity?> getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationResult.IsFailure)
|
||||
return getConfigurationResult.Errors;
|
||||
@@ -75,12 +76,13 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler<Se
|
||||
LibraryArtworkProviderConfigurationEntity configuration;
|
||||
if (getConfigurationResult.Value is not null)
|
||||
{
|
||||
// The provider is already configured for the library, so only its enabled state changes, keeping its existing rank in the display order.
|
||||
configuration = getConfigurationResult.Value;
|
||||
configuration.IsEnabled = command.IsEnabled;
|
||||
}
|
||||
else
|
||||
{
|
||||
// compute the rank to assign to the new configuration, appending it after the existing ones
|
||||
// Compute the rank to assign to the new configuration, appending it after the existing ones.
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
@@ -98,10 +100,14 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler<Se
|
||||
};
|
||||
}
|
||||
|
||||
// Insert the new configuration, or update the existing one, and persist the change.
|
||||
Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -56,18 +56,19 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// admins can configure the metadata providers of any library; for everyone else, only their own libraries
|
||||
// Admins can configure the metadata providers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated.
|
||||
Result<LibraryMetadataProviderConfigurationEntity?> getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationResult.IsFailure)
|
||||
return getConfigurationResult.Errors;
|
||||
@@ -75,12 +76,13 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
|
||||
LibraryMetadataProviderConfigurationEntity configuration;
|
||||
if (getConfigurationResult.Value is not null)
|
||||
{
|
||||
// The provider is already configured for the library, so only its enabled state changes, keeping its existing rank in the display order.
|
||||
configuration = getConfigurationResult.Value;
|
||||
configuration.IsEnabled = command.IsEnabled;
|
||||
}
|
||||
else
|
||||
{
|
||||
// compute the rank to assign to the new configuration, appending it after the existing ones
|
||||
// Compute the rank to assign to the new configuration, appending it after the existing ones.
|
||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
@@ -98,10 +100,14 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
|
||||
};
|
||||
}
|
||||
|
||||
// Insert the new configuration, or update the existing one, and persist the change.
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -49,7 +49,11 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandler<UpdatePluginSe
|
||||
Result<Updated> updateResult = await _unitOfWork.PluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -118,7 +118,10 @@ public class AddScheduledJobCommandHandler : ICommandHandler<AddScheduledJobComm
|
||||
Result<Created> insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(persistenceScheduledJob, cancellationToken).ConfigureAwait(false);
|
||||
if (insertScheduledJobResult.IsFailure)
|
||||
return insertScheduledJobResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in createScheduledJobResult.Value.GetDomainEvents())
|
||||
|
||||
+5
-2
@@ -83,7 +83,7 @@ public class RemoveScheduledJobCommandHandler : ICommandHandler<RemoveScheduledJ
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// Get the scheduled job from the storage medium.
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure)
|
||||
return getScheduledJobResult.Errors;
|
||||
if (getScheduledJobResult.Value is null)
|
||||
@@ -102,7 +102,10 @@ public class RemoveScheduledJobCommandHandler : ICommandHandler<RemoveScheduledJ
|
||||
Result<Deleted> deleteScheduledJobResult = await _unitOfWork.ScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteScheduledJobResult.IsFailure)
|
||||
return deleteScheduledJobResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Queue any domain events.
|
||||
scheduledJobDomainResult.Value.Remove();
|
||||
|
||||
+5
-2
@@ -80,7 +80,7 @@ public class StartScheduledJobCommandHandler : ICommandHandler<StartScheduledJob
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// Get the scheduled job from the storage medium.
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure)
|
||||
return getScheduledJobResult.Errors;
|
||||
if (getScheduledJobResult.Value is null)
|
||||
@@ -98,7 +98,10 @@ public class StartScheduledJobCommandHandler : ICommandHandler<StartScheduledJob
|
||||
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateScheduledJobResult.IsFailure)
|
||||
return updateScheduledJobResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Queue any domain events.
|
||||
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
|
||||
|
||||
+5
-2
@@ -84,7 +84,7 @@ public class StopScheduledJobCommandHandler : ICommandHandler<StopScheduledJobCo
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// Get the scheduled job from the storage medium.
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure)
|
||||
return getScheduledJobResult.Errors;
|
||||
if (getScheduledJobResult.Value is null)
|
||||
@@ -102,7 +102,10 @@ public class StopScheduledJobCommandHandler : ICommandHandler<StopScheduledJobCo
|
||||
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateScheduledJobResult.IsFailure)
|
||||
return updateScheduledJobResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Stop the execution cycle in the scheduler service.
|
||||
await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+5
-1
@@ -80,7 +80,11 @@ public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler<U
|
||||
Result<Updated> upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
+11
-62
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.Scheduling;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
@@ -10,7 +12,6 @@ using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -46,7 +47,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHand
|
||||
public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// Get the scheduled job from the repository.
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure)
|
||||
throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
|
||||
if (getScheduledJobResult.Value is null)
|
||||
@@ -55,94 +56,42 @@ public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHand
|
||||
|
||||
// A cycle run returns the scheduled job to its active status, a one time execution completes it.
|
||||
ScheduledJobStatus status = domainEvent.IsCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed;
|
||||
ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc);
|
||||
ScheduledJobEntity updatedScheduledJob = scheduledJob.ToUpdatedRepositoryEntity(status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc);
|
||||
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
|
||||
if (updateScheduledJobResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
|
||||
|
||||
// Mark the execution of the task of the scheduled job as completed.
|
||||
Result<ScheduledJobExecutionEntity?> getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobExecutionEntity?> getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getExecutionResult.IsFailure)
|
||||
throw new EventualConsistencyException(getExecutionResult.FirstError, getExecutionResult.Errors);
|
||||
if (getExecutionResult.Value is null)
|
||||
throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobExecutionNotFound);
|
||||
ScheduledJobExecutionEntity execution = getExecutionResult.Value;
|
||||
ScheduledJobExecutionEntity updatedExecution = CreateUpdatedExecution(execution, domainEvent.CompletedOnUtc);
|
||||
ScheduledJobExecutionEntity updatedExecution = execution.ToUpdatedRepositoryEntity(domainEvent.CompletedOnUtc);
|
||||
Result<Updated> updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
|
||||
if (updateExecutionResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
|
||||
// Notify the SignalR clients about the current scheduled jobs and the completed execution.
|
||||
await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
|
||||
await _scheduledJobNotifier.SendScheduledJobExecutionCompletedAsync(updatedExecution.ToResponse(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJob">The scheduled job to copy.</param>
|
||||
/// <param name="status">The status of the copy.</param>
|
||||
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
|
||||
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
|
||||
/// <returns>The copy of the scheduled job.</returns>
|
||||
private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
|
||||
{
|
||||
return new ScheduledJobEntity
|
||||
{
|
||||
Id = scheduledJob.Id,
|
||||
Name = scheduledJob.Name,
|
||||
TaskType = scheduledJob.TaskType,
|
||||
ScheduleType = scheduledJob.ScheduleType,
|
||||
IntervalMinutes = scheduledJob.IntervalMinutes,
|
||||
Hour = scheduledJob.Hour,
|
||||
Minute = scheduledJob.Minute,
|
||||
Status = status,
|
||||
OwnerUserId = scheduledJob.OwnerUserId,
|
||||
LastStartedOnUtc = lastStartedOnUtc,
|
||||
LastCompletedOnUtc = lastCompletedOnUtc,
|
||||
CreatedOnUtc = scheduledJob.CreatedOnUtc,
|
||||
CreatedBy = scheduledJob.CreatedBy,
|
||||
UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
|
||||
UpdatedBy = scheduledJob.UpdatedBy
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a copy of <paramref name="execution"/> with the provided completion time.
|
||||
/// </summary>
|
||||
/// <param name="execution">The execution to copy.</param>
|
||||
/// <param name="completedOnUtc">The completion time of the copy.</param>
|
||||
/// <returns>The copy of the execution.</returns>
|
||||
private static ScheduledJobExecutionEntity CreateUpdatedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc)
|
||||
{
|
||||
return new ScheduledJobExecutionEntity
|
||||
{
|
||||
Id = execution.Id,
|
||||
ScheduledJobId = execution.ScheduledJobId,
|
||||
TaskType = execution.TaskType,
|
||||
IsCycleRun = execution.IsCycleRun,
|
||||
WasCycleActive = execution.WasCycleActive,
|
||||
StartedOnUtc = execution.StartedOnUtc,
|
||||
CompletedOnUtc = completedOnUtc,
|
||||
CreatedOnUtc = execution.CreatedOnUtc,
|
||||
CreatedBy = execution.CreatedBy,
|
||||
UpdatedOnUtc = execution.UpdatedOnUtc,
|
||||
UpdatedBy = execution.UpdatedBy
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notifies the SignalR clients about the current list of scheduled jobs.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobsResult.IsFailure)
|
||||
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())];
|
||||
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+9
-36
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.Scheduling;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
@@ -10,7 +12,6 @@ using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -46,7 +47,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle
|
||||
public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// Get the scheduled job from the repository.
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure)
|
||||
throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
|
||||
if (getScheduledJobResult.Value is null)
|
||||
@@ -57,7 +58,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle
|
||||
bool wasCycleActive = scheduledJob.Status == ScheduledJobStatus.Active;
|
||||
|
||||
// Update the scheduled job with its running status and the start time of the execution.
|
||||
ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc);
|
||||
ScheduledJobEntity updatedScheduledJob = scheduledJob.ToUpdatedRepositoryEntity(ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc);
|
||||
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
|
||||
if (updateScheduledJobResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
|
||||
@@ -81,53 +82,25 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle
|
||||
if (insertExecutionResult.IsFailure)
|
||||
throw new EventualConsistencyException(insertExecutionResult.FirstError, insertExecutionResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
|
||||
// Notify the SignalR clients about the current scheduled jobs and the started execution.
|
||||
await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
|
||||
await _scheduledJobNotifier.SendScheduledJobExecutionStartedAsync(execution.ToResponse(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJob">The scheduled job to copy.</param>
|
||||
/// <param name="status">The status of the copy.</param>
|
||||
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
|
||||
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
|
||||
/// <returns>The copy of the scheduled job.</returns>
|
||||
private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
|
||||
{
|
||||
return new ScheduledJobEntity
|
||||
{
|
||||
Id = scheduledJob.Id,
|
||||
Name = scheduledJob.Name,
|
||||
TaskType = scheduledJob.TaskType,
|
||||
ScheduleType = scheduledJob.ScheduleType,
|
||||
IntervalMinutes = scheduledJob.IntervalMinutes,
|
||||
Hour = scheduledJob.Hour,
|
||||
Minute = scheduledJob.Minute,
|
||||
Status = status,
|
||||
OwnerUserId = scheduledJob.OwnerUserId,
|
||||
LastStartedOnUtc = lastStartedOnUtc,
|
||||
LastCompletedOnUtc = lastCompletedOnUtc,
|
||||
CreatedOnUtc = scheduledJob.CreatedOnUtc,
|
||||
CreatedBy = scheduledJob.CreatedBy,
|
||||
UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
|
||||
UpdatedBy = scheduledJob.UpdatedBy
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notifies the SignalR clients about the current list of scheduled jobs.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobsResult.IsFailure)
|
||||
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())];
|
||||
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+8
-17
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.Scheduling;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
@@ -50,31 +52,20 @@ public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandle
|
||||
if (getOpenExecutionResult.Value is not null)
|
||||
{
|
||||
ScheduledJobExecutionEntity execution = getOpenExecutionResult.Value;
|
||||
ScheduledJobExecutionEntity updatedExecution = new()
|
||||
{
|
||||
Id = execution.Id,
|
||||
ScheduledJobId = execution.ScheduledJobId,
|
||||
TaskType = execution.TaskType,
|
||||
IsCycleRun = execution.IsCycleRun,
|
||||
WasCycleActive = execution.WasCycleActive,
|
||||
StartedOnUtc = execution.StartedOnUtc,
|
||||
CompletedOnUtc = domainEvent.OccurredOnUtc,
|
||||
CreatedOnUtc = execution.CreatedOnUtc,
|
||||
CreatedBy = execution.CreatedBy,
|
||||
UpdatedOnUtc = execution.UpdatedOnUtc,
|
||||
UpdatedBy = execution.UpdatedBy
|
||||
};
|
||||
ScheduledJobExecutionEntity updatedExecution = execution.ToUpdatedRepositoryEntity(domainEvent.OccurredOnUtc);
|
||||
Result<Updated> updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
|
||||
if (updateExecutionResult.IsFailure)
|
||||
throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
|
||||
}
|
||||
|
||||
// Notify the SignalR clients about the current list of scheduled jobs.
|
||||
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobsResult.IsFailure)
|
||||
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())];
|
||||
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+12
-8
@@ -2,6 +2,8 @@
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Themes;
|
||||
@@ -71,7 +73,7 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins can delete themes
|
||||
// Only admins can delete themes.
|
||||
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
@@ -83,13 +85,13 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
|
||||
if (theme is null || theme.IsDeleted)
|
||||
return DomainErrors.Themes.ThemeNotFound;
|
||||
|
||||
Result<IEnumerable<ThemeEntity>> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<ThemeEntity>> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getAllResult.IsFailure)
|
||||
return getAllResult.Errors;
|
||||
|
||||
List<ThemeEntity> availableThemes = getAllResult.Value.Where(availableTheme => !availableTheme.IsDeleted).ToList();
|
||||
List<ThemeEntity> availableThemes = getAllResult.Value.Data.Where(availableTheme => !availableTheme.IsDeleted).ToList();
|
||||
|
||||
// at least one bundled theme must always remain available, so the application never ends up without any theme
|
||||
// At least one bundled theme must always remain available, so the application never ends up without any theme.
|
||||
if (theme.InstallSource == ThemeInstallSource.Bundled)
|
||||
{
|
||||
int availableBundledThemes = availableThemes.Count(availableTheme => availableTheme.InstallSource == ThemeInstallSource.Bundled);
|
||||
@@ -97,7 +99,7 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
|
||||
return DomainErrors.Themes.LastBundledThemeCannotBeDeleted;
|
||||
}
|
||||
|
||||
// if the deleted theme was the active one, switch to another available theme, preferring the configured default
|
||||
// If the deleted theme was the active one, switch to another available theme, preferring the configured default.
|
||||
if (theme.IsCurrent == true)
|
||||
{
|
||||
ThemeEntity? replacementTheme = availableThemes
|
||||
@@ -114,7 +116,7 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
|
||||
|
||||
if (theme.InstallSource == ThemeInstallSource.Bundled)
|
||||
{
|
||||
// bundled themes are soft deleted, so they can be restored automatically later, as long as the user did not delete them
|
||||
// Bundled themes are soft deleted, so they can be restored automatically later, as long as the user did not delete them.
|
||||
theme.IsDeleted = true;
|
||||
theme.IsCurrent = null;
|
||||
theme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
@@ -123,13 +125,15 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
|
||||
}
|
||||
else
|
||||
{
|
||||
// user themes are removed entirely, because their files are not shipped with the application and could never be restored
|
||||
// User themes are removed entirely, because their files are not shipped with the application and could never be restored.
|
||||
Result<Deleted> deleteResult = await _unitOfWork.ThemeRepository.DeleteByIdAsync(theme.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteResult.IsFailure)
|
||||
return deleteResult.Errors;
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
Result<Success> deleteFilesResult = await _themeService.DeleteAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteFilesResult.IsFailure)
|
||||
|
||||
+7
-5
@@ -74,11 +74,11 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins can install themes
|
||||
// Only admins can install themes.
|
||||
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// store the theme pack files on the server, replacing the files of an existing theme with the same manifest id
|
||||
// Store the theme pack files on the server, replacing the files of an existing theme with the same manifest id.
|
||||
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false);
|
||||
if (installResult.IsFailure)
|
||||
return installResult.Errors;
|
||||
@@ -103,7 +103,7 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
|
||||
PreviewPath = manifest.Preview,
|
||||
InstallSource = existingTheme.InstallSource,
|
||||
IsCurrent = existingTheme.IsCurrent,
|
||||
// reinstalling a theme must bring it back even if it was soft deleted before, so the uploaded pack becomes visible again
|
||||
// Reinstalling a theme must bring it back even if it was soft deleted before, so the uploaded pack becomes visible again.
|
||||
IsDeleted = false,
|
||||
InstalledAtUtc = DateTime.UtcNow,
|
||||
CreatedOnUtc = existingTheme.CreatedOnUtc,
|
||||
@@ -137,13 +137,15 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
|
||||
Result<Created> insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
{
|
||||
// roll back the stored files so a failed install leaves no orphaned theme pack behind
|
||||
// Roll back the stored files so a failed install leaves no orphaned theme pack behind.
|
||||
await _themeService.DeleteAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
return insertResult.Errors;
|
||||
}
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return themeEntity.ToResponse();
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -70,7 +70,7 @@ public class RestoreThemeCommandHandler : ICommandHandler<RestoreThemeCommand, R
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins can restore themes
|
||||
// Only admins can restore themes.
|
||||
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
@@ -82,11 +82,11 @@ public class RestoreThemeCommandHandler : ICommandHandler<RestoreThemeCommand, R
|
||||
if (theme is null)
|
||||
return DomainErrors.Themes.ThemeNotFound;
|
||||
|
||||
// only bundled themes are soft deleted, so only a soft deleted bundled theme can be restored
|
||||
// Only bundled themes are soft deleted, so only a soft deleted bundled theme can be restored.
|
||||
if (!theme.IsDeleted || theme.InstallSource != ThemeInstallSource.Bundled)
|
||||
return DomainErrors.Themes.ThemeCannotBeRestored;
|
||||
|
||||
// restore the pack files from the shipped archive before reactivating the theme
|
||||
// Restore the pack files from the shipped archive before reactivating the theme.
|
||||
Result<Success> restoreFilesResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
|
||||
if (restoreFilesResult.IsFailure)
|
||||
return restoreFilesResult.Errors;
|
||||
@@ -99,7 +99,9 @@ public class RestoreThemeCommandHandler : ICommandHandler<RestoreThemeCommand, R
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
+8
-2
@@ -66,7 +66,7 @@ public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeComm
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins can change the active theme
|
||||
// Only admins can change the active theme.
|
||||
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
@@ -78,9 +78,11 @@ public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeComm
|
||||
if (theme is null || theme.IsDeleted)
|
||||
return DomainErrors.Themes.ThemeNotFound;
|
||||
|
||||
// The theme is already active, so no change is needed.
|
||||
if (theme.IsCurrent == true)
|
||||
return theme.ToResponse();
|
||||
|
||||
// Only one theme can be active at a time, so the currently active theme must be deactivated before the requested one is activated.
|
||||
Result<ThemeEntity?> getCurrentResult = await _unitOfWork.ThemeRepository.GetCurrentAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getCurrentResult.IsFailure)
|
||||
return getCurrentResult.Errors;
|
||||
@@ -92,12 +94,16 @@ public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeComm
|
||||
await _unitOfWork.ThemeRepository.UpdateAsync(currentTheme, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Activate the requested theme and persist its update.
|
||||
theme.IsCurrent = true;
|
||||
theme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
theme.UpdatedBy = userId;
|
||||
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return theme.ToResponse();
|
||||
}
|
||||
}
|
||||
+10
-5
@@ -58,6 +58,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// Load the requested theme, so that a missing or soft deleted theme is reported before its template is read.
|
||||
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false);
|
||||
if (getThemeResult.IsFailure)
|
||||
return getThemeResult.Errors;
|
||||
@@ -69,10 +70,10 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
|
||||
Result<string> templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false);
|
||||
if (templateResult.IsFailure)
|
||||
{
|
||||
// the stored files of a bundled theme removed externally are restored, and if the broken theme was the
|
||||
// The stored files of a bundled theme removed externally are restored, and if the broken theme was the
|
||||
// active one, the configured default theme is activated, so clients always have a renderable theme; a
|
||||
// theme that simply does not provide a template for the page is not broken, so it is not restored and the
|
||||
// caller falls back to the application's default unstyled Razor view instead
|
||||
// caller falls back to the application's default unstyled Razor view instead.
|
||||
if (templateResult.FirstError != DomainErrors.Themes.ThemeTemplateNotFound
|
||||
&& theme.InstallSource == ThemeInstallSource.Bundled
|
||||
&& await TryRestoreBundledThemeAsync(theme, cancellationToken).ConfigureAwait(false))
|
||||
@@ -99,6 +100,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
|
||||
if (restoreResult.IsFailure)
|
||||
return false;
|
||||
|
||||
// When the restored theme was the active one, switch to the configured default theme, so clients always have a working theme for the next render.
|
||||
if (theme.IsCurrent == true)
|
||||
{
|
||||
Result<ThemeEntity?> getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false);
|
||||
@@ -114,7 +116,10 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
|
||||
defaultTheme.IsCurrent = true;
|
||||
await _unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Persist both activation changes together, so the theme switch is applied atomically.
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,8 +131,8 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// the restore is best effort: an unexpected failure must not fail the request, so the caller falls back to
|
||||
// the application view instead of returning an error to the browser
|
||||
// The restore is best effort: an unexpected failure must not fail the request, so the caller falls back to
|
||||
// the application view instead of returning an error to the browser.
|
||||
_logger.LogWarning(exception, "Failed to restore the files of bundled theme '{ThemeId}'.", theme.ThemeId);
|
||||
return false;
|
||||
}
|
||||
|
||||
+13
-4
@@ -55,23 +55,32 @@ public class ChangePasswordCommandHandler : ICommandHandler<ChangePasswordComman
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// Load the account by its username, so the current password can be verified before it is replaced.
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
// validate if the current password is correct
|
||||
|
||||
// Validate that the provided current password matches the stored hash, so a request with only a valid username cannot overwrite the password.
|
||||
if (!_hashService.CheckStringAgainstHash(command.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
|
||||
return Errors.Authentication.InvalidCurrentPassword;
|
||||
|
||||
// The stored hash is URI escaped, so the new hash is escaped the same way before it is stored.
|
||||
getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(command.NewPassword!));
|
||||
// if the password change was initiated via a password reset, remote the temporary password that was generated in the process
|
||||
|
||||
// If the password change was initiated via a password reset, remove the temporary password that was generated in the process.
|
||||
getUserResult.Value.TempPassword = null;
|
||||
getUserResult.Value.TempPasswordCreated = null;
|
||||
// update the user
|
||||
|
||||
// Update the user and persist the change.
|
||||
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (updateUserResult.IsFailure)
|
||||
return updateUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return new ChangePasswordResponse(true);
|
||||
}
|
||||
}
|
||||
+17
-11
@@ -64,31 +64,37 @@ public class RecoverPasswordCommandHandler : ICommandHandler<RecoverPasswordComm
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// check if any users already exists
|
||||
// Load the account by its username, so its existing recovery state and TOTP configuration can be checked.
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
else if (getUserResult.Value.TempPassword is not null) // if a temp password is present, a password request was already requested
|
||||
else if (getUserResult.Value.TempPassword is not null) // If a temporary password is present, a password reset was already requested.
|
||||
return Errors.Authentication.PasswordResetAlreadyRequested;
|
||||
// check if the user uses TOTP
|
||||
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (!usesTotp)
|
||||
|
||||
// Check if the user uses TOTP.
|
||||
bool doesUseTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (!doesUseTotp)
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
if (usesTotp && string.IsNullOrEmpty(command.TotpCode))
|
||||
if (doesUseTotp && string.IsNullOrEmpty(command.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
else if (usesTotp && !string.IsNullOrEmpty(command.TotpCode)) // and if they do, validate it
|
||||
else if (doesUseTotp && !string.IsNullOrEmpty(command.TotpCode)) // When the user uses TOTP, validate the provided code before allowing the reset.
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), command.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
// hash the new password and assign it to a temporary password that will be valid 15 minutes
|
||||
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
||||
|
||||
// Generate the hash of a temporary password and record when it was created, so that the reset flow can expire it after 15 minutes.
|
||||
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: Replace the hardcoded password with a randomly generated one.
|
||||
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||
// update the user
|
||||
|
||||
// Update the user and persist the temporary password.
|
||||
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (updateUserResult.IsFailure)
|
||||
return updateUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return new RecoverPasswordResponse(true);
|
||||
}
|
||||
}
|
||||
+17
-9
@@ -73,12 +73,14 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// check if any users already exists (admin account is only set once!)
|
||||
// Check if a user with this username already exists, since the admin account can only be created once.
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is not null)
|
||||
return Errors.Authentication.UsernameAlreadyExists;
|
||||
|
||||
// Build the account, hashing the password and URI escaping it the same way as the stored form.
|
||||
string? totpSecret = null;
|
||||
Guid id = Guid.NewGuid();
|
||||
UserEntity user = new()
|
||||
@@ -93,23 +95,29 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
CreatedBy = id,
|
||||
LibraryScans = [],
|
||||
};
|
||||
// if the user enabled two factor auth, include a QR with the totp secret
|
||||
|
||||
// If the user enabled two factor authentication, include a QR code with the TOTP secret.
|
||||
if (command.Use2fa)
|
||||
{
|
||||
// generate a TOTP secret
|
||||
// Generate a TOTP secret.
|
||||
byte[] secret = _totpTokenGenerator.GenerateSecret();
|
||||
// convert the secret into a QR code for the user to scan
|
||||
// Convert the secret into a QR code for the user to scan.
|
||||
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(command.Username!, secret);
|
||||
// store the TOTP secret in the repository, encrypted
|
||||
// Store the TOTP secret in the repository, encrypted.
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
||||
}
|
||||
// insert the user
|
||||
|
||||
// Insert the user and persist the change.
|
||||
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||
if (insertUserResult.IsFailure)
|
||||
return insertUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// TODO: insert the default admin profile preferences when they are implemented
|
||||
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// TODO: Insert the default admin profile preferences when they are implemented.
|
||||
// If 2FA was enabled, the TOTP secret needs to be delivered to the client unencrypted, so it can be displayed.
|
||||
return new RegistrationResponse(user.Id, user.Username, totpSecret);
|
||||
}
|
||||
}
|
||||
+17
-12
@@ -73,28 +73,31 @@ public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, Result<LoginR
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// check if any users already exists
|
||||
// Load the account by its username, so the password and two factor state can be verified.
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
// validate that the password is correct
|
||||
|
||||
// Validate that the password matches the stored hash.
|
||||
if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
|
||||
{
|
||||
// if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too
|
||||
// If a password reset was requested, a temporary password is in use; when the check against the regular password failed, try the temporary one too.
|
||||
if (getUserResult.Value.TempPassword is not null)
|
||||
{
|
||||
// the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
|
||||
// The temporary password is only valid for 15 minutes; when it is obsolete, remove it and return an error.
|
||||
if (getUserResult.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow)
|
||||
{
|
||||
getUserResult.Value.TempPassword = null;
|
||||
getUserResult.Value.TempPasswordCreated = null;
|
||||
await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken);
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Errors.Authentication.TempPasswordExpired;
|
||||
}
|
||||
else // temporary password is still valid, validate password against it
|
||||
else // The temporary password is still valid, so validate the password against it.
|
||||
{
|
||||
if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!)))
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
@@ -103,15 +106,17 @@ public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, Result<LoginR
|
||||
else
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
}
|
||||
// create the JWT token
|
||||
|
||||
// Create the JWT token.
|
||||
string token = _jwtTokenGenerator.GenerateToken(getUserResult.Value.Id.ToString(), getUserResult.Value.Username);
|
||||
// check if the user uses TOTP
|
||||
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (usesTotp && string.IsNullOrEmpty(query.TotpCode))
|
||||
|
||||
// Check if the user uses TOTP.
|
||||
bool doesUseTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (doesUseTotp && string.IsNullOrEmpty(query.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
else if (usesTotp && !string.IsNullOrEmpty(query.TotpCode)) // and if they do, validate it
|
||||
else if (doesUseTotp && !string.IsNullOrEmpty(query.TotpCode)) // When the user uses TOTP, validate the provided code.
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), query.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
return new LoginResponse(getUserResult.Value.Id, getUserResult.Value.Username, token, usesTotp);
|
||||
return new LoginResponse(getUserResult.Value.Id, getUserResult.Value.Username, token, doesUseTotp);
|
||||
}
|
||||
}
|
||||
+21
-14
@@ -6,6 +6,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
@@ -60,52 +62,54 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// only admins can update user authorizations
|
||||
// Only admins can update user authorizations.
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// get the user to update
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false);
|
||||
// Get the user to update.
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||
return DomainErrors.Users.UserDoesNotExist;
|
||||
|
||||
Result<RoleEntity?> getRoleResult = default;
|
||||
if (command.RoleId is not null)
|
||||
{
|
||||
// get the new role
|
||||
getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
// Get the new role.
|
||||
getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsFailure || getRoleResult.Value is null)
|
||||
return ApplicationErrors.Authorization.RoleNotFound;
|
||||
|
||||
// check if we're changing an admin's role and if this would leave us without admins
|
||||
// Check if changing the role of an admin would leave the application without any admin.
|
||||
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin")
|
||||
{
|
||||
// count how many admins we have
|
||||
Result<IEnumerable<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Count how many admins exist, so the last one is never demoted.
|
||||
Result<PaginatedResultDto<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getAllUsersResult.IsFailure)
|
||||
return getAllUsersResult.Errors;
|
||||
|
||||
int adminCount = getAllUsersResult.Value.Count(user => user.UserRole?.Role.RoleName == "Admin");
|
||||
int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == "Admin");
|
||||
if (adminCount <= 1)
|
||||
return ApplicationErrors.Authorization.CannotRemoveLastAdmin;
|
||||
}
|
||||
}
|
||||
// get the permissions to assign
|
||||
|
||||
// Get the permissions to assign.
|
||||
Result<IEnumerable<PermissionEntity>> getPermissionsResult =
|
||||
await _unitOfWork.PermissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false);
|
||||
if (getPermissionsResult.IsFailure)
|
||||
return getPermissionsResult.Errors;
|
||||
|
||||
// update the user
|
||||
// Update the user.
|
||||
UserEntity userToUpdate = getUserResult.Value;
|
||||
|
||||
// Build the role link for the requested role, leaving the current role untouched when no role was provided.
|
||||
UserRoleEntity? userRole = default!;
|
||||
if (command.RoleId is not null)
|
||||
{
|
||||
@@ -118,6 +122,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
||||
};
|
||||
}
|
||||
|
||||
// Build the updated user by copying the unchanged fields and replacing the role and permissions with the requested ones.
|
||||
UserEntity updatedUser = new()
|
||||
{
|
||||
Id = userToUpdate.Id,
|
||||
@@ -138,12 +143,14 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
||||
LibraryScans = userToUpdate.LibraryScans
|
||||
};
|
||||
|
||||
// save changes and return result
|
||||
// Save the changes and return the result.
|
||||
Result<Updated> updateResult = await _unitOfWork.UserRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return new AuthorizationResponse(
|
||||
userToUpdate.Id,
|
||||
|
||||
+4
-1
@@ -106,7 +106,10 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
return updateResult.Errors;
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -58,7 +60,9 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertPermissionResult.IsFailure)
|
||||
return insertPermissionResult.Errors;
|
||||
}
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
@@ -81,7 +85,9 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertRoleResult.IsFailure)
|
||||
return insertRoleResult.Errors;
|
||||
}
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
@@ -102,12 +108,12 @@ public class DataSeedService : IDataSeedService
|
||||
return Errors.Authorization.AdminAccountNotFound;
|
||||
|
||||
// Get all permissions.
|
||||
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPermissionsResult.IsFailure)
|
||||
return getPermissionsResult.Errors;
|
||||
|
||||
// Add each permission to the admin role.
|
||||
foreach (PermissionEntity permission in getPermissionsResult.Value)
|
||||
foreach (PermissionEntity permission in getPermissionsResult.Value.Data)
|
||||
{
|
||||
RolePermissionEntity rolePermissionEntity = new()
|
||||
{
|
||||
@@ -122,7 +128,9 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertRolePermissionResult.IsFailure)
|
||||
return insertRolePermissionResult.Errors;
|
||||
}
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
@@ -143,7 +151,7 @@ public class DataSeedService : IDataSeedService
|
||||
return Errors.Authorization.AdminRoleNotFound;
|
||||
|
||||
// Get admin user.
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure)
|
||||
return getUserResult.Errors;
|
||||
|
||||
@@ -164,7 +172,9 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertUserRoleResult.IsFailure)
|
||||
return insertUserRoleResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
@@ -196,7 +206,9 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertScheduledJobResult.IsFailure)
|
||||
return insertScheduledJobResult.Errors;
|
||||
}
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
|
||||
+37
-43
@@ -33,7 +33,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob
|
||||
{
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILogger<MediaLibraryScanArtworkEnrichmentJob> _logger;
|
||||
|
||||
@@ -62,30 +62,30 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
|
||||
// whether the providers that require access to the web are used during the enrichment
|
||||
// Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
|
||||
// whether the providers that require access to the web are used during the enrichment.
|
||||
string libraryName = string.Empty;
|
||||
bool canDownloadMetadataFromWeb = false;
|
||||
if (unitOfWork.LibraryRepository is not null)
|
||||
{
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
_logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used.");
|
||||
else
|
||||
@@ -95,8 +95,8 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
}
|
||||
}
|
||||
|
||||
// get the artwork providers configured for the media library, in their configured order, that support the media library type.
|
||||
// the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding
|
||||
// Get the artwork providers configured for the media library, in their configured order, that support the media library type.
|
||||
// The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding.
|
||||
List<IArtworkProvider> artworkProviders = [];
|
||||
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
|
||||
{
|
||||
@@ -118,7 +118,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
}
|
||||
}
|
||||
|
||||
// when no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely
|
||||
// When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely.
|
||||
if (artworkProviders.Count > 0)
|
||||
{
|
||||
IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService<IBookArtworkService>();
|
||||
@@ -129,7 +129,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
|
||||
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
|
||||
|
||||
// set the initial progress of the scan job
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
@@ -138,7 +138,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedBooksCount = 0;
|
||||
|
||||
// process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size
|
||||
// Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size.
|
||||
string? lastPath = null;
|
||||
while (true)
|
||||
{
|
||||
@@ -151,7 +151,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
if (booksPage.Count == 0)
|
||||
break;
|
||||
|
||||
// load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory
|
||||
// Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory.
|
||||
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false);
|
||||
if (getAuthorsResult.IsFailure)
|
||||
throw new InvalidOperationException(getAuthorsResult.FirstError.Description);
|
||||
@@ -162,11 +162,11 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
|
||||
await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// check if enough time has passed since last update
|
||||
// Check if enough time has passed since the last update.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
@@ -174,24 +174,24 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
}
|
||||
}
|
||||
|
||||
// persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size
|
||||
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size.
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
|
||||
lastPath = booksPage[^1].Path;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", LibraryId.Value);
|
||||
}
|
||||
|
||||
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
@@ -222,19 +222,17 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary<Guid, string?> authorsDisplayNamesByBookId, CancellationToken cancellationToken)
|
||||
{
|
||||
// when no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped
|
||||
// When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped.
|
||||
if (bookArtworkService is null || artworkProviders.Count == 0)
|
||||
return;
|
||||
|
||||
ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false);
|
||||
if (resolvedArtwork is null)
|
||||
{
|
||||
// no artwork provider returned usable artwork, mark the cover artwork of the book as failed to resolve
|
||||
BookArtworkEntity? coverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
|
||||
// No artwork provider returned usable artwork, so the cover artwork of the book is marked as failed to resolve.
|
||||
BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
|
||||
if (coverArtwork is null)
|
||||
{
|
||||
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
|
||||
}
|
||||
bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
|
||||
else
|
||||
{
|
||||
coverArtwork.Status = ArtworkStatus.Failed;
|
||||
@@ -244,9 +242,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
return;
|
||||
}
|
||||
|
||||
BookArtworkEntity? existingCoverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
|
||||
BookArtworkEntity? existingCoverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
|
||||
|
||||
// when the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one
|
||||
// When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one
|
||||
// is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it.
|
||||
ulong contentHash = 0;
|
||||
bool shouldStoreArtwork = true;
|
||||
@@ -262,11 +260,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
Result<string> saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false);
|
||||
if (saveArtworkResult.IsFailure)
|
||||
{
|
||||
// a failing artwork storage must not prevent the book from being tracked as failed to resolve
|
||||
// A failing artwork storage must not prevent the book from being tracked as failed to resolve.
|
||||
if (existingCoverArtwork is null)
|
||||
{
|
||||
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
|
||||
}
|
||||
bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
|
||||
else
|
||||
{
|
||||
existingCoverArtwork.Status = ArtworkStatus.Failed;
|
||||
@@ -276,7 +272,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
return;
|
||||
}
|
||||
|
||||
// for remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one
|
||||
// For remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one.
|
||||
if (contentHash == 0)
|
||||
{
|
||||
string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\'));
|
||||
@@ -284,9 +280,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
}
|
||||
|
||||
if (existingCoverArtwork is null)
|
||||
{
|
||||
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow));
|
||||
}
|
||||
bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow));
|
||||
else
|
||||
{
|
||||
existingCoverArtwork.FileName = saveArtworkResult.Value;
|
||||
@@ -300,7 +294,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
}
|
||||
else
|
||||
{
|
||||
// the resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched
|
||||
// The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched.
|
||||
existingCoverArtwork!.Status = ArtworkStatus.Enriched;
|
||||
existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
|
||||
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
|
||||
@@ -338,13 +332,13 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// a failing artwork provider must not prevent the other providers from being tried
|
||||
// A failing artwork provider must not prevent the other providers from being tried.
|
||||
}
|
||||
|
||||
if (artwork is null)
|
||||
continue;
|
||||
|
||||
// a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract
|
||||
// A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract.
|
||||
if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess)
|
||||
continue;
|
||||
|
||||
|
||||
+47
-42
@@ -4,7 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
@@ -17,9 +17,12 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -38,7 +41,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob
|
||||
{
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILogger<MediaLibraryScanMetadataEnrichmentJob> _logger;
|
||||
|
||||
@@ -67,36 +70,36 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment
|
||||
// Load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment.
|
||||
bool canDownloadMetadataFromWeb = false;
|
||||
if (unitOfWork.LibraryRepository is not null)
|
||||
{
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
_logger.LogWarning("Failed to read the media library, the providers requiring the web will not be used.");
|
||||
else
|
||||
canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
|
||||
}
|
||||
|
||||
// get the metadata providers configured for the media library, in their configured order, that support the media library type,
|
||||
// skipping the providers that require access to the web when the media library does not permit downloading data from the web
|
||||
// Get the metadata providers configured for the media library, in their configured order, that support the media library type,
|
||||
// skipping the providers that require access to the web when the media library does not permit downloading data from the web.
|
||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
|
||||
@@ -112,7 +115,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
providers.AddRange(configuredProviders);
|
||||
}
|
||||
|
||||
// read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing
|
||||
// Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing.
|
||||
bool shouldAggregateMetadataWhenMissing = false;
|
||||
if (unitOfWork.UserSettingsRepository is not null)
|
||||
{
|
||||
@@ -123,7 +126,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
|
||||
}
|
||||
|
||||
// when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely
|
||||
// When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely.
|
||||
if (providers.Count > 0)
|
||||
{
|
||||
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
@@ -131,7 +134,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
|
||||
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
|
||||
|
||||
// set the initial progress of the scan job
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
@@ -140,11 +143,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedBooksCount = 0;
|
||||
|
||||
// the contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
|
||||
// created once even when the same person is discovered for many books of the same page
|
||||
// The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
|
||||
// created once even when the same person is discovered for many books of the same page.
|
||||
Dictionary<string, MediaContributorEntity> contributorsByNormalizedName = [];
|
||||
|
||||
// process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
|
||||
// Process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size.
|
||||
string? lastPath = null;
|
||||
while (true)
|
||||
{
|
||||
@@ -163,11 +166,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
|
||||
await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// check if enough time has passed since last update
|
||||
// Check if enough time has passed since the last update.
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
@@ -175,8 +178,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
}
|
||||
}
|
||||
|
||||
// persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size
|
||||
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size.
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
contributorsByNormalizedName.Clear();
|
||||
|
||||
@@ -184,16 +189,14 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value);
|
||||
}
|
||||
|
||||
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
@@ -224,7 +227,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, CancellationToken cancellationToken)
|
||||
{
|
||||
// convert the book to a domain object
|
||||
// Convert the book to a domain object.
|
||||
Result<Book> getBookResult = bookEntity.ToDomainEntity();
|
||||
if (getBookResult.IsFailure)
|
||||
return;
|
||||
@@ -233,7 +236,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
BookMetadataLookupDto bookMetadataLookup = new(
|
||||
LibraryId: bookEntity.LibraryId,
|
||||
Path: bookEntity.Path,
|
||||
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results
|
||||
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: This should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results.
|
||||
OpenLibraryId: bookEntity.OpenLibraryId,
|
||||
Title: bookEntity.Title,
|
||||
Author: null,
|
||||
@@ -246,19 +249,20 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
|
||||
if (resolvedMetadata is null)
|
||||
{
|
||||
// no metadata provider returned usable metadata, mark the book as failed to enrich, keeping its previous metadata
|
||||
// No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata.
|
||||
bookEntity.MetadataStatus = MetadataStatus.Failed;
|
||||
bookEntity.UpdatedOnUtc = DateTime.UtcNow;
|
||||
bookEntity.UpdatedBy = Guid.NewGuid();
|
||||
return;
|
||||
}
|
||||
|
||||
// apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns
|
||||
// Apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns.
|
||||
book.ApplyMetadata(resolvedMetadata.Metadata);
|
||||
bookEntity.ApplyMetadataToEntity(book);
|
||||
|
||||
// link the media contributors discovered while enriching to the book, finding or creating a single contributor per person
|
||||
// Link the media contributors discovered while enriching to the book, finding or creating a single contributor per person.
|
||||
List<BookContributorEntity> linkedContributors = [];
|
||||
List<BookMediaContributor> domainContributors = [];
|
||||
foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? [])
|
||||
{
|
||||
if (contributor.Name?.DisplayName is null)
|
||||
@@ -266,25 +270,26 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
|
||||
MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
string roleName = contributor.Role?.Name ?? "Contributor";
|
||||
MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other;
|
||||
MediaContributorRole role = contributor.Role ?? MediaContributorRole.Author;
|
||||
if (linkedContributors.Any(linkedContributor => linkedContributor.MediaContributorId == contributorEntity.Id && linkedContributor.Role == role))
|
||||
continue;
|
||||
linkedContributors.Add(new BookContributorEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = bookEntity.Id,
|
||||
MediaContributorId = contributorEntity.Id,
|
||||
RoleName = roleName,
|
||||
RoleCategory = roleCategory,
|
||||
Role = role,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
});
|
||||
domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value);
|
||||
}
|
||||
bookEntity.BookContributors.Clear();
|
||||
bookEntity.BookContributors.AddRange(linkedContributors);
|
||||
book.UpdateContributors([.. linkedContributors.Select(linkedContributor => Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects.MediaContributorId.Create(linkedContributor.MediaContributorId))]);
|
||||
bookEntity.Contributors.Clear();
|
||||
bookEntity.Contributors.AddRange(linkedContributors);
|
||||
book.UpdateContributors(domainContributors);
|
||||
|
||||
// mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern
|
||||
// Mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern.
|
||||
bookEntity.MetadataStatus = MetadataStatus.Enriched;
|
||||
bookEntity.MetadataProvider = resolvedMetadata.ProviderName;
|
||||
bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
|
||||
@@ -340,7 +345,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// a failing metadata provider must not prevent the other providers from being tried
|
||||
// A failing metadata provider must not prevent the other providers from being tried.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -369,12 +374,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
|
||||
mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata);
|
||||
contributingProviders.Add(metadataProvider.Name);
|
||||
// the identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely
|
||||
// The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely.
|
||||
bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// a failing metadata provider must not prevent the other providers from being tried
|
||||
// A failing metadata provider must not prevent the other providers from being tried.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-19
@@ -53,36 +53,36 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// set the initial progress of the scan job, it's a 1 step job - invalidating the stale enrichment state
|
||||
// Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints
|
||||
// are compared against the current provider configuration to detect whether it changed since the last scan
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
// Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints
|
||||
// are compared against the current provider configuration to detect whether it changed since the last scan.
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// load the provider configurations of the media library, whose fingerprint is compared against the stored one
|
||||
// Load the provider configurations of the media library, whose fingerprint is compared against the stored one.
|
||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getMetadataConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
|
||||
@@ -91,7 +91,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
|
||||
if (getArtworkConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description);
|
||||
|
||||
// read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing
|
||||
// Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing.
|
||||
bool shouldAggregateMetadataWhenMissing = false;
|
||||
if (unitOfWork.UserSettingsRepository is not null)
|
||||
{
|
||||
@@ -102,7 +102,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
|
||||
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
|
||||
}
|
||||
|
||||
// compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
|
||||
// Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
|
||||
// changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration
|
||||
// was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored.
|
||||
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb);
|
||||
@@ -122,27 +122,29 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
|
||||
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
|
||||
// the library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository
|
||||
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed
|
||||
// Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
|
||||
// The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository
|
||||
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed.
|
||||
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||
library.UpdatedOnUtc = DateTime.UtcNow;
|
||||
library.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
|
||||
// increment the number of processed elements progress
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+19
-17
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
@@ -52,17 +52,17 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue.
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
@@ -70,27 +70,27 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium
|
||||
// Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them
|
||||
// Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them.
|
||||
Result<IReadOnlyList<string>> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getDeletedPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
|
||||
|
||||
// get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched
|
||||
// Get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched.
|
||||
Result<IReadOnlyList<string>> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getChangedPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getChangedPathsResult.FirstError.Description);
|
||||
|
||||
// apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan
|
||||
// Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan.
|
||||
Result<Updated> applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (applySnapshotSwapResult.IsFailure)
|
||||
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
||||
|
||||
// reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow
|
||||
// Reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow.
|
||||
if (getChangedPathsResult.Value.Count > 0)
|
||||
{
|
||||
Result<Updated> resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
@@ -98,14 +98,14 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
||||
throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// raise a deletion event for every media library scan snapshot item that is no longer present on disk
|
||||
// Raise a deletion event for every media library scan snapshot item that is no longer present on disk.
|
||||
foreach (string deletedPath in getDeletedPathsResult.Value)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata
|
||||
// Materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata.
|
||||
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getPathsResult.IsFailure)
|
||||
throw new InvalidOperationException(getPathsResult.FirstError.Description);
|
||||
@@ -124,19 +124,21 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
|
||||
if (insertBookResult.IsFailure)
|
||||
throw new InvalidOperationException(insertBookResult.FirstError.Description);
|
||||
}
|
||||
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
|
||||
// increment the number of processed elements progress
|
||||
// Increment the number of processed elements progress.
|
||||
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
|
||||
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
|
||||
if (Children.Count == 0)
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
// Call each linked child with the obtained payload.
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
@@ -109,12 +111,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
|
||||
// Remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status,
|
||||
// and delete the provider configurations of the removed plugins, since their configuration only makes sense while the plugin is installed.
|
||||
IMediaLibraryProviderConfigurationStore providerConfigurationStore = asyncServiceScope.ServiceProvider.GetRequiredService<IMediaLibraryProviderConfigurationStore>();
|
||||
Result<IEnumerable<PluginEntity>> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(stoppingToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<PluginEntity>> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: stoppingToken).ConfigureAwait(false);
|
||||
if (getPluginsResult.IsFailure)
|
||||
_logger.LogError("Failed to get the detected plugins while reconciling the plugin rows.");
|
||||
else
|
||||
{
|
||||
foreach (PluginEntity plugin in getPluginsResult.Value)
|
||||
foreach (PluginEntity plugin in getPluginsResult.Value.Data)
|
||||
{
|
||||
if (detectedPluginIds.Contains(plugin.Id))
|
||||
continue;
|
||||
@@ -128,12 +130,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
|
||||
}
|
||||
|
||||
// Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type.
|
||||
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(stoppingToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<LibraryEntity>> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync<BaseFilterDto>(cancellationToken: stoppingToken).ConfigureAwait(false);
|
||||
if (getLibrariesResult.IsFailure)
|
||||
_logger.LogError("Failed to get the media libraries while seeding the provider configurations.");
|
||||
else
|
||||
{
|
||||
foreach (LibraryEntity library in getLibrariesResult.Value)
|
||||
foreach (LibraryEntity library in getLibrariesResult.Value.Data)
|
||||
{
|
||||
Result<Success> ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false);
|
||||
if (ensureResult.IsFailure)
|
||||
@@ -144,7 +146,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
|
||||
}
|
||||
}
|
||||
|
||||
await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -68,7 +68,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
|
||||
{
|
||||
RunCycleWorkerAsync(scheduledJobId, runImmediately: true, cancellationToken).FireAndForgetSafeAsync();
|
||||
RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately: true, cancellationToken).FireAndForgetSafeAsync();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
@@ -174,8 +174,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
continue;
|
||||
}
|
||||
// A once at startup scheduled job fires immediately when its cycle is resumed at startup; the other scheduled jobs wait for their next scheduled execution.
|
||||
bool runImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup;
|
||||
RunCycleWorkerAsync(scheduledJobId, runImmediately, cancellationToken).FireAndForgetSafeAsync();
|
||||
bool shouldRunImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup;
|
||||
RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately, cancellationToken).FireAndForgetSafeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,9 +183,9 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
/// Runs the execution cycle worker of the scheduled job identified by <paramref name="scheduledJobId"/>.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is run.</param>
|
||||
/// <param name="runImmediately">Whether the task of the scheduled job is run immediately when the cycle starts.</param>
|
||||
/// <param name="shouldRunImmediately">Whether the task of the scheduled job is run immediately when the cycle starts.</param>
|
||||
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken)
|
||||
private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool shouldRunImmediately, CancellationToken stoppingToken)
|
||||
{
|
||||
// Each cycle owns its own cancellation token source: it is the handle the runtime registry stores, so stopping one
|
||||
// scheduled job cancels exactly this cycle and no other job's cycle, even though the cycle worker itself runs "fire and forget" on another thread.
|
||||
@@ -203,7 +203,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
CancellationToken cycleToken = linkedCancellationTokenSource.Token;
|
||||
// An immediate run is executed as a cycle run, so it completes the scheduled job back to its active state and is
|
||||
// recorded as part of the cycle; this is the path taken by an admin start, by the resume at startup and by the seed of the default jobs.
|
||||
if (runImmediately)
|
||||
if (shouldRunImmediately)
|
||||
await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false);
|
||||
|
||||
// The schedule is read from the storage medium for every cycle, so the delay until the next run is always
|
||||
@@ -320,7 +320,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
IDomainEventPublisher domainEventPublisher = services.GetRequiredService<IDomainEventPublisher>();
|
||||
|
||||
// Load the scheduled job, and mark its task as started.
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
|
||||
return;
|
||||
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
|
||||
@@ -383,8 +383,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
// A one time execution returns the scheduled job to its active state when its execution cycle is still running, so the
|
||||
// running cycle keeps scheduling executions and the job can still be stopped; the same applies to a once at startup job,
|
||||
// whose active state is what makes it fire again at the next application startup.
|
||||
bool completesTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup;
|
||||
Result<Success> completeExecutionResult = scheduledJob.MarkExecutionCompleted(completesTheCycleRun);
|
||||
bool doesCompleteTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup;
|
||||
Result<Success> completeExecutionResult = scheduledJob.MarkExecutionCompleted(doesCompleteTheCycleRun);
|
||||
if (completeExecutionResult.IsFailure)
|
||||
return;
|
||||
foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents())
|
||||
@@ -412,7 +412,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
{
|
||||
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
|
||||
return ScheduledJobStatus.Added;
|
||||
ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
|
||||
@@ -433,17 +433,19 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
ScheduledJobStatus reconciledStatus = (openExecution?.WasCycleActive ?? true) ? ScheduledJobStatus.Active : ScheduledJobStatus.Added;
|
||||
|
||||
Result<Updated> updateScheduledJobResult = await unitOfWork.ScheduledJobRepository.UpdateAsync(
|
||||
CreateUpdatedScheduledJob(scheduledJob, reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
scheduledJob.ToUpdatedRepositoryEntity(reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
if (updateScheduledJobResult.IsFailure)
|
||||
return ScheduledJobStatus.Added;
|
||||
if (openExecution is not null)
|
||||
{
|
||||
Result<Updated> updateExecutionResult = await unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(
|
||||
CreateClosedExecution(openExecution, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
openExecution.ToUpdatedRepositoryEntity(DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
if (updateExecutionResult.IsFailure)
|
||||
return ScheduledJobStatus.Added;
|
||||
}
|
||||
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
_logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name);
|
||||
return reconciledStatus;
|
||||
}
|
||||
@@ -468,7 +470,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
{
|
||||
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
|
||||
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
|
||||
return null;
|
||||
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
|
||||
@@ -488,57 +490,4 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
return schedule.GetDelayUntilNextExecution(dateTimeProvider.UtcNow, TimeZoneInfo.Local);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJob">The scheduled job to copy.</param>
|
||||
/// <param name="status">The status of the copy.</param>
|
||||
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
|
||||
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
|
||||
/// <returns>The copy of the scheduled job.</returns>
|
||||
private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
|
||||
{
|
||||
return new ScheduledJobEntity
|
||||
{
|
||||
Id = scheduledJob.Id,
|
||||
Name = scheduledJob.Name,
|
||||
TaskType = scheduledJob.TaskType,
|
||||
ScheduleType = scheduledJob.ScheduleType,
|
||||
IntervalMinutes = scheduledJob.IntervalMinutes,
|
||||
Hour = scheduledJob.Hour,
|
||||
Minute = scheduledJob.Minute,
|
||||
Status = status,
|
||||
OwnerUserId = scheduledJob.OwnerUserId,
|
||||
LastStartedOnUtc = lastStartedOnUtc,
|
||||
LastCompletedOnUtc = lastCompletedOnUtc,
|
||||
CreatedOnUtc = scheduledJob.CreatedOnUtc,
|
||||
CreatedBy = scheduledJob.CreatedBy,
|
||||
UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
|
||||
UpdatedBy = scheduledJob.UpdatedBy
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a copy of <paramref name="execution"/> with the provided completion time.
|
||||
/// </summary>
|
||||
/// <param name="execution">The execution to copy.</param>
|
||||
/// <param name="completedOnUtc">The completion time of the copy.</param>
|
||||
/// <returns>The copy of the execution.</returns>
|
||||
private static ScheduledJobExecutionEntity CreateClosedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc)
|
||||
{
|
||||
return new ScheduledJobExecutionEntity
|
||||
{
|
||||
Id = execution.Id,
|
||||
ScheduledJobId = execution.ScheduledJobId,
|
||||
TaskType = execution.TaskType,
|
||||
IsCycleRun = execution.IsCycleRun,
|
||||
WasCycleActive = execution.WasCycleActive,
|
||||
StartedOnUtc = execution.StartedOnUtc,
|
||||
CompletedOnUtc = completedOnUtc,
|
||||
CreatedOnUtc = execution.CreatedOnUtc,
|
||||
CreatedBy = execution.CreatedBy,
|
||||
UpdatedOnUtc = execution.UpdatedOnUtc,
|
||||
UpdatedBy = execution.UpdatedBy
|
||||
};
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -98,7 +98,9 @@ public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor
|
||||
domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents());
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
|
||||
// Publish the domain events of the queued media library scans.
|
||||
foreach (IDomainEvent domainEvent in domainEvents)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
|
||||
using Lumina.Application.Common.Infrastructure.Themes;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -30,7 +32,7 @@ internal static class ThemeSynchronizer
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<PaginatedResultDto<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getThemesResult.IsFailure)
|
||||
{
|
||||
logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
|
||||
@@ -38,7 +40,7 @@ internal static class ThemeSynchronizer
|
||||
}
|
||||
|
||||
// Themes that were soft deleted by the user must not be reinstalled automatically.
|
||||
List<ThemeEntity> themes = [.. getThemesResult.Value];
|
||||
List<ThemeEntity> themes = [.. getThemesResult.Value.Data];
|
||||
|
||||
foreach (string archivePath in themeService.GetBundledThemeArchivePaths())
|
||||
{
|
||||
@@ -107,7 +109,9 @@ internal static class ThemeSynchronizer
|
||||
await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false);
|
||||
await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user