Implements library management update library

This commit is contained in:
BinaryAlley committed 2024-11-17 21:02:10 +02:00
1 parent d0d53fd471
commit 291d1fa329
68 files changed
+1003 -110

No files matched your search

@@ -1,7 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using System;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
@@ -10,6 +11,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
/// Interface for the repository for media libraries.
/// </summary>
public interface ILibraryRepository : IRepository<LibraryEntity>,
IInsertRepositoryAction<LibraryEntity>
IGetByIdRepositoryAction<LibraryEntity, Guid>,
IInsertRepositoryAction<LibraryEntity>,
IUpdateRepositoryAction<LibraryEntity>
{
}
@@ -11,6 +11,7 @@ public static partial class Errors
{
public static class Authorization
{
public static Error NotAuthorized => Error.Unauthorized(description: nameof(NotAuthorized));
public static Error AdminAccountAlreadyCreated => Error.Unauthorized(description: nameof(AdminAccountAlreadyCreated));
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Application.Common.Errors;
/// <summary>
/// Application persistence related error types.
/// </summary>
public static partial class Errors
{
public static class Persistence
{
public static Error ErrorPersistingMediaLibrary => Error.Failure(description: nameof(ErrorPersistingMediaLibrary));
}
}
@@ -2,6 +2,7 @@
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
#endregion
@@ -16,7 +17,7 @@ public static class AddMediaLibraryRequestMapping
/// Converts <paramref name="request"/> to <see cref="AddLibraryCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="userId">The Id of the user owning the media library. Required.</param>
/// <param name="userId">The Id of the user owning the media library.</param>
/// <returns>The converted command.</returns>
public static AddLibraryCommand ToCommand(this AddLibraryRequest request, Guid userId)
{
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Queries;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Extension methods for converting <see cref="GetLibraryRequest"/>.
/// </summary>
public static class GetLibraryRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetLibraryQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="userId">The Id of the user requesting the media library.</param>
/// <returns>The converted query.</returns>
public static GetLibraryQuery ToQuery(this GetLibraryRequest request, Guid userId)
{
return new GetLibraryQuery(
request.Id,
userId
);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Extension methods for converting <see cref="UpdateLibraryRequest"/>.
/// </summary>
public static class UpdateLibraryRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="UpdateLibraryCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="userId">The Id of the user making the request to update the media library.</param>
/// <returns>The converted command.</returns>
public static UpdateLibraryCommand ToCommand(this UpdateLibraryRequest request, Guid userId)
{
return new UpdateLibraryCommand(
request.Id,
request.UserId,
userId,
request.Title,
request.LibraryType,
request.ContentLocations
);
}
}
@@ -20,6 +20,6 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
public record AddLibraryCommand(
Guid UserId,
string? Title,
LibraryType? LibraryType,
string? LibraryType,
string[]? ContentLocations
) : IRequest<ErrorOr<LibraryResponse>>;
@@ -1,13 +1,15 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -40,23 +42,31 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
{
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
request.UserId,
request.Title!,
request.LibraryType ?? LibraryType.Other,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!
);
if (createLibraryResult.IsError)
return createLibraryResult.Errors;
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
// convert the domain library entity to a repository library entity
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// insert the repository entity and save changes
ErrorOr<Created> insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
if (insertLibraryResult.IsError)
return insertLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return persistenceLibrary.ToResponse();
// retrieve the newly saved media library from the persistence medium and return it
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (retrievedLibraryResult.IsError)
return retrievedLibraryResult.Errors;
if (retrievedLibraryResult.Value is null)
return Errors.Persistence.ErrorPersistingMediaLibrary;
return retrievedLibraryResult.Value.ToResponse();
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
using System;
#endregion
@@ -22,7 +23,8 @@ public class AddLibraryCommandValidator : AbstractValidator<AddLibraryCommand>
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.IsInEnum().WithMessage(Errors.Library.UnknownLibraryType.Description);
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
/// <summary>
/// Command for updating a media library.
/// </summary>
/// <param name="Id">The Id of the media library.</param>
/// <param name="OwnerId">The Id of the user owning the media library.</param>
/// <param name="CurrentUserId">The Id of the user making the request to update the media library.</param>
/// <param name="LibraryType">The type of the media library.</param>
/// <param name="ContentLocations">The file system paths of the directories where the media library elements are located.</param>
/// <param name="Title">The title of the media library.</param>
[DebuggerDisplay("Title: {Title}")]
public record UpdateLibraryCommand(
Guid Id,
Guid OwnerId,
Guid CurrentUserId,
string? Title,
string? LibraryType,
string[]? ContentLocations
) : IRequest<ErrorOr<LibraryResponse>>;
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
/// <summary>
/// Handler for the command to update a media library.
/// </summary>
public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public UpdateLibraryCommandHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the command to update a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken)
{
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
if (resultGetLibrary.IsError)
return resultGetLibrary.Errors;
else if (resultGetLibrary.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it
if (resultGetLibrary.Value.UserId != request.CurrentUserId) // TODO: after implementing the Admin role, add that permission check here too
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
LibraryId.Create(request.Id),
request.OwnerId,
request.Title!,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!
);
if (createLibraryResult.IsError)
return createLibraryResult.Errors;
// convert the domain library entity to a repository library entity
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// update the repository entity and save changes
ErrorOr<Updated> updateLibraryResult = await libraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
if (updateLibraryResult.IsError)
return updateLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// retrieve the updated media library from the persistence medium and return it
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (retrievedLibraryResult.IsError)
return retrievedLibraryResult.Errors;
if (retrievedLibraryResult.Value is null)
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
return retrievedLibraryResult.Value.ToResponse();
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateLibraryCommand"/>.
/// </summary>
public class UpdateLibraryCommandValidator : AbstractValidator<UpdateLibraryCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryCommandValidator"/> class.
/// </summary>
public UpdateLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.CurrentUserId)
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
RuleFor(x => x.OwnerId)
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description);
RuleForEach(x => x.ContentLocations)
.NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description)
.MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description);
RuleFor(x => x.Title)
.NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description);
}
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
/// <summary>
/// Query for getting a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library to get.</param>
/// <param name="UserId">The Id os the user requesting the media library.</param>
[DebuggerDisplay("Path: {Path}")]
public record GetLibraryQuery(
Guid Id,
Guid UserId
) : IRequest<ErrorOr<LibraryResponse>>;
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
/// <summary>
/// Handler for the query to authenticate an account.
/// </summary>
public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetLibraryQueryHandler(
IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to authenticate an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(GetLibraryQuery request, CancellationToken cancellationToken)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
if (resultGetLibrary.IsError)
return resultGetLibrary.Errors;
else if (resultGetLibrary.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that requested the library is not an Admin or is not the owner of the library, they do not have the right to view it
if (resultGetLibrary.Value.UserId != request.UserId) // TODO: after implementing the Admin role, add that permission check here too
return ApplicationErrors.Authorization.NotAuthorized;
return resultGetLibrary.Value.ToResponse();
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
/// <summary>
/// Validates the needed validation rules for <see cref="GetLibraryQuery"/>.
/// </summary>
public class GetLibraryQueryValidator : AbstractValidator<GetLibraryQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryQueryValidator"/> class.
/// </summary>
public GetLibraryQueryValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.UserId)
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
}
}
@@ -46,7 +46,7 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
@@ -59,7 +59,7 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
resultSelectUser.Value.TempPassword = null;
resultSelectUser.Value.TempPasswordCreated = null;
// update the user
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -56,7 +56,7 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
@@ -76,7 +76,7 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow;
// update the user
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -60,7 +60,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
{
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is not null)
@@ -85,7 +85,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken);
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (resultInsertUser.IsError)
return resultInsertUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -60,7 +60,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
@@ -1,6 +1,4 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
#endregion
@@ -15,6 +13,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
[DebuggerDisplay("Title: {Title}")]
public record AddLibraryRequest(
string? Title,
LibraryType? LibraryType,
string? LibraryType,
string[]? ContentLocations
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// <summary>
/// Represents a request to get a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library. Required.</param>
[DebuggerDisplay("Id: {Id}")]
public record GetLibraryRequest(
Guid Id
);
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// <summary>
/// Represents a request to update a media library.
/// </summary>
/// <param name="Id">The Id of the media library. Required.</param>
/// <param name="UserId">The Id of the user owning the media library. Required.</param>
/// <param name="Title">The title of the media library. Required.</param>
/// <param name="LibraryType">The type of the media library. Required.</param>
/// <param name="ContentLocations">The file system paths of the directories where the media library elements are located. Required.</param>
[DebuggerDisplay("Title: {Title}")]
public record class UpdateLibraryRequest(
Guid Id,
Guid UserId,
string? Title,
string? LibraryType,
string[]? ContentLocations
);
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -42,4 +43,39 @@ internal sealed class LibraryRepository : ILibraryRepository
_luminaDbContext.Libraries.Add(library);
return Result.Created;
}
/// <summary>
/// Gets a <see cref="LibraryEntity"/> identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the library to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="LibraryEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<ErrorOr<LibraryEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
.FirstOrDefaultAsync(library => library.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a media library.
/// </summary>
/// <param name="data">Ther media library to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Updated>> UpdateAsync(LibraryEntity data, CancellationToken cancellationToken)
{
LibraryEntity? foundLibrary = await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
.FirstOrDefaultAsync(library => library.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundLibrary is null)
return Errors.Library.LibraryNotFound;
// update scalar properties
_luminaDbContext.Entry(foundLibrary).CurrentValues.SetValues(data);
// update owned entities (their changes are not automatically tracked by EF)
foundLibrary.ContentLocations.Clear();
foreach (LibraryContentLocationEntity contentLocation in data.ContentLocations)
foundLibrary.ContentLocations.Add(contentLocation);
return Result.Updated;
}
}
@@ -11,8 +11,10 @@ public static partial class Errors
{
public static class Library
{
public static Error LibraryIdCannotBeEmpty => Error.Forbidden(description: nameof(LibraryIdCannotBeEmpty));
public static Error UserIdCannotBeEmpty => Error.Forbidden(description: nameof(UserIdCannotBeEmpty));
public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists));
public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound));
public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull));
public static Error UnknownLibraryType => Error.Unexpected(description: nameof(UnknownLibraryType));
public static Error PathsListCannotBeNull => Error.Validation(description: nameof(PathsListCannotBeNull));
@@ -13,5 +13,6 @@ public static partial class ApiRoutes
public const string GET_LIBRARY_BY_ID = "/libraries/{id}";
public const string GET_LIBRARIES = "/libraries";
public const string ADD_LIBRARY = "/libraries";
public const string UPDATE_LIBRARY = "/libraries/{id}";
}
}
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDirectoriesEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetDirectoriesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesEndpointSummary : Summary<GetDirectoriesEndpoint, GetDirectoriesRequest>
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDirectoryTreeEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetDirectoryTreeEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointSummary : Summary<GetDirectoryTreeEndpoint, GetDirectoryTreeRequest>
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTreeDirectoriesEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetTreeDirectoriesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointSummary : Summary<GetTreeDirectoriesEndpoint, GetTreeDirectoriesRequest>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDrivesEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetDrivesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesEndpointSummary : Summary<GetDrivesEndpoint>
@@ -8,7 +8,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTypeEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetTypeEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTypeEndpointSummary : Summary<GetTypeEndpoint, FileSystemTypeResponse>
@@ -11,7 +11,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFilesEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetFilesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesEndpointSummary : Summary<GetFilesEndpoint, GetFilesRequest>
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTreeFilesEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetTreeFilesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesEndpointSummary : Summary<GetTreeFilesEndpoint, GetTreeFilesRequest>
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
/// <summary>
/// Class used for providing a textual description for the <see cref="CheckPathExistsEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="CheckPathExistsEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsEndpointSummary : Summary<CheckPathExistsEndpoint, CheckPathExistsRequest>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath;
/// <summary>
/// Class used for providing a textual description for the <see cref="CombinePathEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="CombinePathEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathEndpointSummary : Summary<CombinePathEndpoint, CombinePathRequest>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathParentEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetPathParentEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentEndpointSummary : Summary<GetPathParentEndpoint, GetPathParentRequest>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathRootEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetPathRootEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootEndpointSummary : Summary<GetPathRootEndpoint, GetPathRootRequest>
@@ -7,7 +7,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathSeparatorEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetPathSeparatorEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathSeparatorEndpointSummary : Summary<GetPathSeparatorEndpoint>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath;
/// <summary>
/// Class used for providing a textual description for the <see cref="SplitPathEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="SplitPathEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathEndpointSummary : Summary<SplitPathEndpoint, SplitPathRequest>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
/// <summary>
/// Class used for providing a textual description for the <see cref="ValidatePathEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="ValidatePathEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathEndpointSummary : Summary<ValidatePathEndpoint, ValidatePathRequest>
@@ -8,7 +8,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThumbnailEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetThumbnailEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailEndpointSummary : Summary<GetThumbnailEndpoint, GetThumbnailRequest>
@@ -50,6 +50,7 @@ public class AddLibraryEndpoint : BaseEndpoint<AddLibraryRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddLibraryRequest request, CancellationToken cancellationToken)
{
// retrieve the currently authenticated user, and send it with the request
string? user = User.FindFirstValue(ClaimTypes.NameIdentifier);
ErrorOr<LibraryResponse> result = await _sender.Send(request.ToCommand(Guid.Parse(user!)), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Libraries.ADD_LIBRARY}/{result.Value.Id}", result.Value), Problem);
@@ -6,14 +6,12 @@ using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddLibraryEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="AddLibraryEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryRequest>
@@ -28,7 +26,7 @@ public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryR
ExampleRequest = new AddLibraryRequest(
Title: "TV Shows",
LibraryType: LibraryType.TvShow,
LibraryType: "TvShow",
ContentLocations: [
"/media/tv shows/drama/",
"/media/tv shows/SCI-FI/",
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Presentation.Api.Common.Routes.Library.Management;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrary;
/// <summary>
/// API endpoint for the <c>/libraries/{id}</c> route.
/// </summary>
public class GetLibraryEndpoint : BaseEndpoint<GetLibraryRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetLibraryEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Libraries.GET_LIBRARY_BY_ID);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets a library by Id.
/// </summary>
/// <param name="request">The request containing the id of the library to be retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetLibraryRequest request, CancellationToken cancellationToken)
{
// retrieve the currently authenticated user, and send it with the request
string? user = User.FindFirstValue(ClaimTypes.NameIdentifier);
ErrorOr<LibraryResponse> result = await _sender.Send(request.ToQuery(Guid.Parse(user!)), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrary;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetLibraryEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryEndpointSummary : Summary<GetLibraryEndpoint, GetLibraryRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryEndpointSummary"/> class.
/// </summary>
public GetLibraryEndpointSummary()
{
Summary = "Retrieves a media library by its Id.";
Description = "Retrieves a media library by its Id, if the user making the request is an Admin, or the owner of the library.";
ExampleRequest = new GetLibraryRequest(
Id: Guid.NewGuid()
);
RequestParam(r => r.Id, "The Id of the media library. Required.");
ResponseParam<LibraryResponse>(r => r.Id, "The unique identifier of the entity.");
ResponseParam<LibraryResponse>(r => r.UserId, "The Id of the user owning the media library.");
ResponseParam<LibraryResponse>(r => r.Title, "The title of the media library.");
ResponseParam<LibraryResponse>(r => r.LibraryType, "The type of the media library.");
ResponseParam<LibraryResponse>(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located.");
ResponseParam<LibraryResponse>(r => r.Created, "The date and time when the entity was created.");
ResponseParam<LibraryResponse>(r => r.Updated, "The date and time when the entity was last updated.");
Response(200, "The media library is returned.", example: new LibraryResponse(
Id: Guid.NewGuid(),
UserId: Guid.NewGuid(),
Title: "TV Shows",
LibraryType: LibraryType.TvShow,
ContentLocations: ["/media/tv shows/drama/", "/media/tv shows/SCI-FI/"],
Created: DateTime.UtcNow,
Updated: default
));
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/libraries/{id}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/libraries/{id}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/libraries/{id}"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/{id}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the requested media library does not exist.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = "/api/v1/libraries/{id}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/libraries/{id}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"UserIdCannotBeEmpty",
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Presentation.Api.Common.Routes.Library.Management;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary;
/// <summary>
/// API endpoint for the <c>/libraries/{id}</c> route.
/// </summary>
public class UpdateLibraryEndpoint : BaseEndpoint<UpdateLibraryRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public UpdateLibraryEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.PUT);
Routes(ApiRoutes.Libraries.UPDATE_LIBRARY);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Updates a media library stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the media library to be updated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UpdateLibraryRequest request, CancellationToken cancellationToken)
{
// retrieve the currently authenticated user, and send it with the request
string? user = User.FindFirstValue(ClaimTypes.NameIdentifier);
ErrorOr<LibraryResponse> result = await _sender.Send(request.ToCommand(Guid.Parse(user!)), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,148 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary;
/// <summary>
/// Class used for providing a textual description for the <see cref="UpdateLibraryEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateLibraryEndpointSummary : Summary<UpdateLibraryEndpoint, UpdateLibraryRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryEndpointSummary"/> class.
/// </summary>
public UpdateLibraryEndpointSummary()
{
Summary = "Updates an existing media library.";
Description = "Updates a media library and returns its details, if the user making the request is an Admin, or the owner of the library.";
ExampleRequest = new UpdateLibraryRequest(
Id: Guid.NewGuid(),
UserId: Guid.NewGuid(),
Title: "TV Shows",
LibraryType: "TvShow",
ContentLocations: [
"/media/tv shows/drama/",
"/media/tv shows/SCI-FI/",
]
);
RequestParam(r => r.Id, "The Id of the media library. Required.");
RequestParam(r => r.UserId, "The Id of the user owning the media library. Required.");
RequestParam(r => r.Title, "The title of the media library. Required.");
RequestParam(r => r.LibraryType, "The type of the media library. Required.");
RequestParam(r => r.ContentLocations, ">The file system paths of the directories where the media library elements are located. Required.");
ResponseParam<LibraryResponse>(r => r.Id, "The unique identifier of the entity.");
ResponseParam<LibraryResponse>(r => r.UserId, "The Id of the user owning the media library.");
ResponseParam<LibraryResponse>(r => r.Title, "The title of the media library.");
ResponseParam<LibraryResponse>(r => r.LibraryType, "The type of the media library.");
ResponseParam<LibraryResponse>(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located.");
ResponseParam<LibraryResponse>(r => r.Created, "The date and time when the entity was created.");
ResponseParam<LibraryResponse>(r => r.Updated, "The date and time when the entity was last updated.");
Response(200, "The media library was successfully updated.", example:
new LibraryResponse(
Id: Guid.NewGuid(),
UserId: Guid.NewGuid(),
Title: "TV Shows",
LibraryType: LibraryType.TvShow,
ContentLocations: ["/media/tv shows/drama/", "/media/tv shows/SCI-FI/"],
Created: DateTime.UtcNow,
Updated: default
));
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/libraries"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/libraries"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/libraries"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/{id}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the requested media library does not exist.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = "/api/v1/libraries/{id}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/libraries",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"UserIdCannotBeEmpty",
"LibraryTypeCannotBeNull",
"LibraryTypeCannotBeNull",
"UnknownLibraryType",
"PathsListCannotBeNull",
"PathsListCannotBeEmpty",
"PathCannotBeEmpty",
"TitleCannotBeEmpty",
"TitleMustBeMaximum255CharactersLong"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -14,7 +14,7 @@ using System;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddBookEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="AddBookEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
@@ -13,7 +13,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetBooksEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="GetBooksEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
@@ -12,7 +12,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.GetBook;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// API endpoint for the <c>/books/{id}</c> route.
/// </summary>
public class GetBookEndpoint : BaseEndpoint<GetBookRequest, IResult>
{
@@ -7,7 +7,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="CheckInitializationEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="CheckInitializationEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckInitializationEndpointSummary : Summary<CheckInitializationEndpoint>
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetupApplicationEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="SetupApplicationEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetupApplicationEndpointSummary : Summary<SetupApplicationEndpoint, RegistrationRequest>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="ChangePasswordEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="ChangePasswordEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordEndpointSummary : Summary<ChangePasswordEndpoint, ChangePasswordRequest>
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login;
/// <summary>
/// Class used for providing a textual description for the <see cref="LoginEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="LoginEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginEndpointSummary : Summary<LoginEndpoint, LoginRequest>
@@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="RecoverPasswordEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="RecoverPasswordEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordEndpointSummary : Summary<RecoverPasswordEndpoint, RecoverPasswordRequest>
@@ -13,7 +13,7 @@ using System.Diagnostics.CodeAnalysis;
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
/// <summary>
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterEndpointSummary : Summary<RegisterEndpoint, RegistrationRequest>
@@ -14,10 +14,15 @@ namespace Lumina.Presentation.Web.Common.Models.Libraries;
public class LibraryModel
{
/// <summary>
/// Gets or sets the unique identifier of the library.
/// Gets or sets the unique identifier of the media library.
/// </summary>
public Guid? Id { get; set; }
/// <summary>
/// Gets or sets the unique identifier of the user owning the media library.
/// </summary>
public Guid? UserId { get; set; }
/// <summary>
/// Gets or sets the title of the library.
/// </summary>
@@ -26,7 +31,7 @@ public class LibraryModel
/// <summary>
/// Gets or sets the type of the library.
/// </summary>
public LibraryType? LibraryType { get; set; }
public string? LibraryType { get; set; }
/// <summary>
/// Gets or sets the collection of directories that contain the library files.
@@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -40,7 +39,7 @@ public class DirectoriesController : Controller
public async Task<IActionResult> GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<DirectoryModel> response = await _apiHttpClient.GetAsync<DirectoryModel[]>(
$"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken);
$"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken);
return Json(new { success = true, data = response });
}
@@ -54,7 +53,7 @@ public class DirectoriesController : Controller
public async Task<IActionResult> GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<FileSystemTreeNodeModel> response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
$"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken);
$"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken);
return Json(new { success = true, data = response });
}
@@ -67,7 +66,7 @@ public class DirectoriesController : Controller
[HttpGet("get-directory-tree")]
public async Task<IActionResult> GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken);
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken);
return Json(new { success = true, data = response });
}
}
@@ -34,7 +34,7 @@ public class DrivesController : Controller
[HttpGet("get-drives")]
public async Task<IActionResult> GetDrives(CancellationToken cancellationToken)
{
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"drives/get-drives", cancellationToken: cancellationToken);
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"drives/get-drives", cancellationToken);
return Json(new { success = true, data = new { drives = response } });
}
}
@@ -34,7 +34,7 @@ public class FileSystemController : Controller
[HttpGet("get-type")]
public async Task<IActionResult> GetType(CancellationToken cancellationToken)
{
FileSystemTypeModel response = await _apiHttpClient.GetAsync<FileSystemTypeModel>($"file-system/get-type", cancellationToken: cancellationToken);
FileSystemTypeModel response = await _apiHttpClient.GetAsync<FileSystemTypeModel>($"file-system/get-type", cancellationToken);
return Json(new { success = true, data = new { platformType = response.PlatformType.ToString() } });
}
}
@@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -40,7 +39,7 @@ public class FilesController : Controller
public async Task<IActionResult> GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<FileSystemTreeNodeModel> response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
$"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken);
$"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken);
return Json(new { success = true, data = response });
}
@@ -54,7 +53,7 @@ public class FilesController : Controller
public async Task<IActionResult> GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<FileModel> response = await _apiHttpClient.GetAsync<FileModel[]>(
$"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken);
$"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken);
return Json(new { success = true, data = response });
}
}
@@ -36,7 +36,7 @@ public class PathController : Controller
[HttpGet("get-path-root")]
public async Task<IActionResult> GetPathRoot([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel response = await _apiHttpClient.GetAsync<PathSegmentModel>($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken);
PathSegmentModel response = await _apiHttpClient.GetAsync<PathSegmentModel>($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken);
return Json(new { success = true, data = new { root = response } });
}
@@ -47,7 +47,7 @@ public class PathController : Controller
[HttpGet("get-path-separator")]
public async Task<IActionResult> GetPathSeparator(CancellationToken cancellationToken)
{
PathSeparatorModel response = await _apiHttpClient.GetAsync<PathSeparatorModel>($"path/get-path-separator", cancellationToken: cancellationToken);
PathSeparatorModel response = await _apiHttpClient.GetAsync<PathSeparatorModel>($"path/get-path-separator", cancellationToken);
return Json(new { success = true, data = new { pathSeparator = response.Separator } });
}
@@ -59,7 +59,7 @@ public class PathController : Controller
[HttpGet("get-path-parent")]
public async Task<IActionResult> GetPathParent([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken);
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken);
return Json(new { success = true, data = new { pathSegments = response } });
}
@@ -71,7 +71,7 @@ public class PathController : Controller
[HttpGet("split")]
public async Task<IActionResult> SplitPath([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken);
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken);
return Json(new { success = true, data = new { pathSegments = response } });
}
@@ -83,7 +83,7 @@ public class PathController : Controller
[HttpGet("validate")]
public async Task<IActionResult> ValidatePath([FromQuery] string path, CancellationToken cancellationToken)
{
PathValidModel response = await _apiHttpClient.GetAsync<PathValidModel>($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken);
PathValidModel response = await _apiHttpClient.GetAsync<PathValidModel>($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken);
return Json(new { success = true, data = new { isValid = response.IsValid } });
}
@@ -96,7 +96,7 @@ public class PathController : Controller
[HttpGet("check-path-exists")]
public async Task<IActionResult> CheckPathExists([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
PathExistsModel response = await _apiHttpClient.GetAsync<PathExistsModel>($"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken);
PathExistsModel response = await _apiHttpClient.GetAsync<PathExistsModel>($"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken);
return Json(new { success = true, data = new { exists = response.Exists } });
}
}
@@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -30,24 +31,27 @@ public class LibraryManagementController : Controller
}
[HttpGet("item/{id?}")]
public IActionResult EditLibrary(Guid? id = null)
public async Task<IActionResult> EditLibrary(Guid? id = null, CancellationToken cancellationToken = default)
{
LibraryModel libraryModel = new()
{
Id = id,
LibraryType = LibraryType.Book,
ContentLocations = ["a", "b", "c"],
Title = ""
};
LibraryModel libraryModel = new();
if (id is not null)
libraryModel = await _apiHttpClient.GetAsync<LibraryModel>($"libraries/{id}", cancellationToken);
return View("/Views/Library/Management/Item.cshtml", libraryModel);
}
/// <summary>
/// Adds a new media library, or updates an existing one.
/// </summary>
/// <param name="data">The model containing the new library data.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[ValidateAntiForgeryToken]
[HttpPost("item")]
public async Task<IActionResult> SaveLibraryAsync([FromBody] LibraryModel model)
public async Task<IActionResult> SaveLibrary([FromBody] LibraryModel data, CancellationToken cancellationToken)
{
LibraryModel response = model.Id.HasValue
? await _apiHttpClient.PutAsync<LibraryModel, LibraryModel>($"libraries/{model.Id}", model)
: await _apiHttpClient.PostAsync<LibraryModel, LibraryModel>("libraries", model);
return Json(new { success = true });
// call different API endpoints based on whether this is a new library or an existing one
LibraryModel response = data.Id.HasValue
? await _apiHttpClient.PutAsync<LibraryModel, LibraryModel>($"libraries/{data.Id}", data, cancellationToken)
: await _apiHttpClient.PostAsync<LibraryModel, LibraryModel>("libraries", data, cancellationToken);
return Json(new { success = true, data = response });
}
}
@@ -14,6 +14,7 @@ using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -113,15 +114,16 @@ public class AuthController : Controller
/// Registers a new account.
/// </summary>
/// <param name="data">User credentials used for registration.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequestModel data)
public async Task<IActionResult> Register([FromBody] RegisterRequestModel data, CancellationToken cancellationToken)
{
// call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup
string endpoint = data.RegistrationType == "Admin" ? "initialization" : "auth/register";
// attempt API registration
RegisterResponseModel response = await _apiHttpClient.PostAsync<RegisterResponseModel, RegisterRequestModel>(endpoint, data);
RegisterResponseModel response = await _apiHttpClient.PostAsync<RegisterResponseModel, RegisterRequestModel>(endpoint, data, cancellationToken);
return Json(new { success = true, data = response });
}
@@ -129,15 +131,16 @@ public class AuthController : Controller
/// Logs in an account.
/// </summary>
/// <param name="data">User credentials used for login.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequestModel data)
public async Task<IActionResult> Login([FromBody] LoginRequestModel data, CancellationToken cancellationToken)
{
try
{
// attempt API registration
LoginResponseModel response = await _apiHttpClient.PostAsync<LoginResponseModel, LoginRequestModel>("auth/login", data);
LoginResponseModel response = await _apiHttpClient.PostAsync<LoginResponseModel, LoginRequestModel>("auth/login", data, cancellationToken);
// store the received token in a secure cookie
Response.Cookies.Delete("Token");
Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions
@@ -193,12 +196,13 @@ public class AuthController : Controller
/// Recovers the password of an account.
/// </summary>
/// <param name="data">User credentials used for password recovery.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("recover-password")]
public async Task<IActionResult> RecoverPassword([FromBody] RecoverPasswordRequestModel data)
public async Task<IActionResult> RecoverPassword([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken)
{
RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync<RecoverPasswordResponseModel, RecoverPasswordRequestModel>("auth/recover-password", data);
RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync<RecoverPasswordResponseModel, RecoverPasswordRequestModel>("auth/recover-password", data, cancellationToken);
return Json(new { success = true, data = response });
}
@@ -206,12 +210,13 @@ public class AuthController : Controller
/// Changes the password of an account.
/// </summary>
/// <param name="data">User credentials used for password change.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[ValidateAntiForgeryToken]
[HttpPost("change-password")]
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequestModel data)
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequestModel data, CancellationToken cancellationToken)
{
data = data with { Username = User?.Identity?.Name }; // assign the currently logged in user as the user for which to change the password
ChangePasswordResponseModel response = await _apiHttpClient.PostAsync<ChangePasswordResponseModel, ChangePasswordRequestModel>("auth/change-password", data);
ChangePasswordResponseModel response = await _apiHttpClient.PostAsync<ChangePasswordResponseModel, ChangePasswordRequestModel>("auth/change-password", data, cancellationToken);
return Json(new { success = true, data = response });
}
}
@@ -39,7 +39,7 @@
</div>
</div>
<div class="form-row">
<button id="btn-recover-password" type="button" class="abort-button h-22px w-150px" data-link="@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")">Recover Password</button>
<button id="btn-recover-password" type="button" class="abort-button h-22px w-150px">Recover Password</button>
<button id="btn-login" type="submit" class="confirm-button h-22px w-100px">Login</button>
</div>
<!-- 2FA -->
@@ -48,7 +48,7 @@
<!-- section registration success -->
<div class="text-center w-100">
<p id="recover-password-success" class="text-light-one w-100 hidden">Password Temporarily Reset</p>
<button id="btn-redirect-login" type="submit" class="confirm-button h-22px w-80px hidden" data-link="@_urlService.GetAbsoluteUrl("Login", "Auth")">Login</button>
<button id="btn-redirect-login" type="submit" class="confirm-button h-22px w-80px hidden">Login</button>
</div>
</div>
@section Scripts {
@@ -11,15 +11,18 @@
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
}
@inject IUrlService _urlService
@model LibraryModel
@await Component.InvokeAsync("FileSystemBrowser")
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="LibraryManagement" asp-action="EditLibrary" method="post" id="add-media-library-form">
<form asp-controller="LibraryManagement" asp-action="EditLibrary" method="post" id="add-media-library-form" class="inline">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Id" value="@id" />
<input type="hidden" asp-for="UserId" value="@Model.UserId"/>
<div class="form-row">
<h1 class="text-light-two w-100 text-center pt-0 pb-0 engraved-title">@(id is not null ? "Edit" : "Add New") Library</h1>
</div>
@@ -52,9 +55,44 @@
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<!-- Dropdown options remain the same -->
<div class="enlightenment-option first-option disabled">Book</div>
<div class="enlightenment-option first-option disabled">Written Content</div>
<div class="enlightenment-option" data-value="Book">Book</div>
<!-- ... rest of the options ... -->
<div class="enlightenment-option" data-value="EBook">E Book</div>
<div class="enlightenment-option" data-value="BookSeries">Book Series</div>
<div class="enlightenment-option" data-value="ComicBook">Comic Book</div>
<div class="enlightenment-option" data-value="ComicSeries">Comic Series</div>
<div class="enlightenment-option" data-value="Magazine">Magazine</div>
<div class="enlightenment-option" data-value="Manga">Manga</div>
<div class="enlightenment-option" data-value="GraphicNovel">Graphic Novel</div>
<div class="enlightenment-option" data-value="AcademicPaper">Academic Paper</div>
<div class="enlightenment-option" data-value="SheetMusic">Sheet Music</div>
<div class="enlightenment-option" data-value="Screenplay">Screenplay</div>
<div class="enlightenment-option disabled">Video Content</div>
<div class="enlightenment-option" data-value="TvShow">Tv Show</div>
<div class="enlightenment-option" data-value="Movie">Movie</div>
<div class="enlightenment-option" data-value="FilmSeries">Film Series</div>
<div class="enlightenment-option" data-value="FilmFranchise">Film Franchise</div>
<div class="enlightenment-option" data-value="Concert">Concert</div>
<div class="enlightenment-option" data-value="Documentary">Documentary</div>
<div class="enlightenment-option" data-value="Tutorial">Tutorial</div>
<div class="enlightenment-option" data-value="Personal">Personal</div>
<div class="enlightenment-option" data-value="Anime">Anime</div>
<div class="enlightenment-option" data-value="Youtube">Youtube</div>
<div class="enlightenment-option" data-value="Videoclip">Videoclip</div>
<div class="enlightenment-option disabled">Audio Content</div>
<div class="enlightenment-option" data-value="Music">Music</div>
<div class="enlightenment-option" data-value="AudioBook">Audio Book</div>
<div class="enlightenment-option" data-value="LivePerformance">Live Performance</div>
<div class="enlightenment-option" data-value="Interview">Interview</div>
<div class="enlightenment-option" data-value="Cover">Cover</div>
<div class="enlightenment-option" data-value="Remix">Remix</div>
<div class="enlightenment-option" data-value="Soundeffect">Soundeffect</div>
<div class="enlightenment-option" data-value="Podcast">Podcast</div>
<div class="enlightenment-option" data-value="RadioShow">Radio Show</div>
<div class="enlightenment-option disabled">Visual Content</div>
<div class="enlightenment-option" data-value="PhotoAlbum">Photo Album</div>
<div class="enlightenment-option disabled">Miscellaneous Content</div>
<div class="enlightenment-option last-option" data-value="Other">Other</div>
</div>
</div>
</div>
@@ -85,9 +123,18 @@
</div>
</div>
</form>
<!-- section success -->
<div class="text-center w-100">
<p id="save-success" class="text-light-one w-100 hidden">Library Saved</p>
<button id="btn-back-to-libraries" type="button" class="abort-button h-22px w-150px mx-auto mt-10 hidden">Back To Libraries</button>
<button id="btn-add-new-library" type="button" class="confirm-button h-22px w-150px mx-auto mt-10 hidden">Add New Library</button>
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
const saveSuccess = document.getElementById('save-success');
const btnBackToLibraries = document.getElementById('btn-back-to-libraries');
const btnAddNewLibrary = document.getElementById('btn-add-new-library');
document.getElementById('add-media-library-form').addEventListener('keypress', async (event) => {
if (event.key === 'Enter') {
@@ -105,19 +152,29 @@
async function handleAddMediaLibrary(form) {
const formData = {
Id: form.querySelector('[name="Id"]').value || null,
UserId: form.querySelector('[name="UserId"]').value || null,
Title: form.querySelector('[name="Title"]').value,
LibraryType: form.querySelector('.enlightenment-selected-text').textContent,
ContentLocations: Array.from(form.querySelectorAll('.form-table-row span'))
.map(span => span.textContent)
};
const result = await callApiPostAsync('/library/manage/item', formData);
if (result) {
// Optional: Handle successful response
// For example, redirect after success
// window.location.href = '/library/manage';
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("SaveLibrary", "LibraryManagement")', formData);
if (data) {
form.classList.replace('inline', 'hidden');
saveSuccess.classList.replace('hidden', 'inline');
btnAddNewLibrary.classList.replace('hidden', 'block');
btnBackToLibraries.classList.replace('hidden', 'block');
}
}
btnBackToLibraries.addEventListener('click', () => {
window.location.href = '@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")';
});
btnAddNewLibrary.addEventListener('click', () => {
window.location.href = '@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")';
});
document.getElementById('add-media-directory').addEventListener('click', function () {
showFileSystemBrowserDialogAsync('C:\\Users\\', true, false, addNewPaths); // TODO: take path and include hidden elements from settings
});
@@ -24,9 +24,9 @@
}
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Register</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Change Password</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Profile</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")" class="nav-link"><span>Register</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")" class="nav-link"><span>Change Password</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")" class="nav-link"><span>Profile</span></a></li>
}
</ul>
@if (User?.Identity?.IsAuthenticated == true)
@@ -42,7 +42,7 @@
</div>
<ul>
<li><a href="library/manage"><span>Manage libraries</span></a></li>
<li><a href="library/manage/item"><span>Add media library</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link"><span>Add new library</span></a></li>
</ul>
<div class="mobile-menu-heading">
Written Content
@@ -93,9 +93,9 @@
}
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")">Register</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")">Change Password</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")">Profile</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")" class="nav-link">Register</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")" class="nav-link">Change Password</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")" class="nav-link">Profile</a></li>
}
</ul>
</li>
@@ -113,7 +113,7 @@
<label for="library-menu">Library</label>
<ul>
<li tabindex="0"><a href="library/manage">Manage libraries</a></li>
<li tabindex="0"><a href="library/manage/item">Add new library</a></li>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link">Add new library</a></li>
<li class="has-submenu" tabindex="0">
<label>Written Content</label>
<ul>
@@ -23,7 +23,7 @@ public class AddMediaLibraryRequestMappingTests
Guid userId = Guid.NewGuid();
AddLibraryRequest request = new(
"My Library",
LibraryType.Book,
"Book",
["C:/Books", "D:/Media/Books"]
);
@@ -49,7 +49,7 @@ public class AddMediaLibraryRequestMappingTests
Guid userId = Guid.NewGuid();
AddLibraryRequest request = new(
"My Library",
libraryType,
libraryType.ToString(),
["C:/Media"]
);
@@ -60,7 +60,7 @@ public class AddMediaLibraryRequestMappingTests
result.Should().NotBeNull();
result.UserId.Should().Be(userId);
result.Title.Should().Be(request.Title);
result.LibraryType.Should().Be(libraryType);
result.LibraryType.Should().Be(libraryType.ToString());
result.ContentLocations.Should().BeEquivalentTo(request.ContentLocations);
}
@@ -79,7 +79,7 @@ public class AddMediaLibraryRequestMappingTests
Guid userId = Guid.NewGuid();
AddLibraryRequest request = new(
"My Library",
LibraryType.Book,
"Book",
contentLocations
);