mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 20:11:10 +00:00
Adds cover update endpoints for music artists and albums.
This commit is contained in:
1 parent
4f43bf352b
commit
4ceb8f7360
32 files changed
+4892
No files matched your search
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Command for updating the cover image of an existing album.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library the album belongs to, taken from the route.</param>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album whose cover image is updated, taken from the route.</param>
|
||||
/// <param name="Cover">The stream of the uploaded cover image file.</param>
|
||||
/// <param name="FileName">The name of the uploaded cover image file.</param>
|
||||
[DebuggerDisplay("AlbumId: {AlbumId} FileName: {FileName}")]
|
||||
public record UpdateAlbumCoverCommand(
|
||||
string? LibraryId,
|
||||
string? ArtistId,
|
||||
string? AlbumId,
|
||||
Stream? Cover,
|
||||
string? FileName
|
||||
) : ICommand;
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to update the cover image of an existing album.
|
||||
/// </summary>
|
||||
public class UpdateAlbumCoverCommandHandler : ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IMusicArtworkService _musicArtworkService;
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<UpdateAlbumCoverCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="musicArtworkService">Injected service for storing the artwork of a music library item.</param>
|
||||
/// <param name="pathService">Injected service for handling file system paths.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public UpdateAlbumCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IPathService pathService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateAlbumCoverCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_musicArtworkService = musicArtworkService;
|
||||
_pathService = pathService;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update the cover image of an existing album.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the response carrying the relative path of the stored cover image, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<UpdateAlbumCoverResponse>> HandleAsync(UpdateAlbumCoverCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route identifiers are non-empty Guids before this point.
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
|
||||
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getAlbumResult.IsFailure)
|
||||
return getAlbumResult.Errors;
|
||||
if (getAlbumResult.Value is null)
|
||||
return DomainErrors.Music.AlbumNotFound;
|
||||
AlbumEntity existingAlbum = getAlbumResult.Value;
|
||||
|
||||
// Resource scoping: the album must belong to the library and the artist named by the route, so that an album can never be edited through
|
||||
// another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere.
|
||||
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
|
||||
return DomainErrors.Music.AlbumNotFound;
|
||||
|
||||
// Admins can update the albums of all libraries; for everyone else, only the albums of the libraries they own.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingAlbum.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
string libraryName = getLibraryResult.Value.Title;
|
||||
|
||||
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(existingAlbum.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getArtistResult.IsFailure)
|
||||
return getArtistResult.Errors;
|
||||
string artistName = getArtistResult.Value?.Name ?? string.Empty;
|
||||
|
||||
// The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files, so that a
|
||||
// re-uploaded cover replaces the cover stored for the album at its standardized location instead of writing a second copy elsewhere.
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtworkResult.IsFailure)
|
||||
return getArtworkResult.Errors;
|
||||
string? existingCoverPath = getArtworkResult.Value
|
||||
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault();
|
||||
string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName)
|
||||
?? (existingAlbum.ReleaseTypes.Count > 0 ? existingAlbum.ReleaseTypes[0].ReleaseType.ToString() : null);
|
||||
|
||||
Result<string> storeArtworkResult = await _musicArtworkService.SaveAlbumArtworkAsync(
|
||||
existingAlbum.LibraryId,
|
||||
existingAlbum.Id,
|
||||
libraryName,
|
||||
artistName,
|
||||
existingAlbum.Title,
|
||||
command.Cover!,
|
||||
command.FileName!,
|
||||
releaseTypeName,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
if (storeArtworkResult.IsFailure)
|
||||
return storeArtworkResult.Errors;
|
||||
|
||||
// The stored cover of the album is replaced as a whole: when the new cover is stored under a different name than the previous one
|
||||
// (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
|
||||
if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
|
||||
{
|
||||
Result<Deleted> deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
|
||||
if (deleteResult.IsFailure)
|
||||
return deleteResult.Errors;
|
||||
}
|
||||
|
||||
// Map the newly stored cover image onto the artwork of the album, replacing the existing cover or adding a new one.
|
||||
Result<Updated> upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
|
||||
MusicArtworkOwnerType.Album, albumId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return new UpdateAlbumCoverResponse(storeArtworkResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the name of the release type directory the artwork of an album is stored under, from the relative path of its existing cover.
|
||||
/// </summary>
|
||||
/// <param name="coverRelativePath">The relative path of the existing cover image of the album, or <see langword="null"/> when the album has no cover.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the album does not use one.</returns>
|
||||
private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(coverRelativePath))
|
||||
return null;
|
||||
// The path is media/music/{library}/{artist}[/{releaseType}]/{album}/{file}, so the segment right before the album directory is the release
|
||||
// type directory when the album uses one, and the artist directory otherwise. An artist whose name happens to match a release type, like
|
||||
// "Live", must not be mistaken for one, so the segment is only accepted as a release type when it is not the directory of the artist.
|
||||
string[] segments = coverRelativePath.Split(_pathService.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (segments.Length < 3)
|
||||
return null;
|
||||
string candidate = segments[^3];
|
||||
if (IsArtistDirectory(candidate, artistName))
|
||||
return null;
|
||||
return Enum.TryParse(candidate, ignoreCase: true, out MusicReleaseType releaseType) && Enum.IsDefined(releaseType) ? candidate : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the provided path segment is the artwork directory of the artist of the album.
|
||||
/// </summary>
|
||||
/// <param name="pathSegment">The path segment to be checked.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns><see langword="true"/> when the segment is the artwork directory of the artist, <see langword="false"/> otherwise.</returns>
|
||||
private bool IsArtistDirectory(string pathSegment, string artistName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(artistName))
|
||||
return false;
|
||||
Result<PathSegment> artistSegmentResult = _pathService.SanitizeSegment(artistName);
|
||||
return artistSegmentResult.IsSuccess
|
||||
&& string.Equals(pathSegment, artistSegmentResult.Value.Name, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="UpdateAlbumCoverCommand"/>.
|
||||
/// </summary>
|
||||
public class UpdateAlbumCoverCommandValidator : AbstractValidator<UpdateAlbumCoverCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public UpdateAlbumCoverCommandValidator()
|
||||
{
|
||||
// Validates the identifier of the media library the album belongs to, taken from the route.
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.LibraryId)
|
||||
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
|
||||
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the artist the album belongs to, taken from the route.
|
||||
RuleFor(command => command.ArtistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.ArtistId)
|
||||
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
|
||||
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the album whose cover image is updated, taken from the route.
|
||||
RuleFor(command => command.AlbumId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.AlbumId)
|
||||
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
|
||||
.When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
|
||||
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
|
||||
// Validates the uploaded cover image.
|
||||
RuleFor(command => command.Cover)
|
||||
.NotNull()
|
||||
.WithError(Errors.Music.CoverCannotBeNull);
|
||||
|
||||
RuleFor(command => command.FileName)
|
||||
.NotEmpty()
|
||||
.When(command => command.Cover is not null)
|
||||
.WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Command for updating the cover image of an existing artist.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library this artist belongs to, taken from the route.</param>
|
||||
/// <param name="ArtistId">The unique identifier of the artist whose cover image is updated, taken from the route.</param>
|
||||
/// <param name="Cover">The stream of the uploaded cover image file.</param>
|
||||
/// <param name="FileName">The name of the uploaded cover image file.</param>
|
||||
[DebuggerDisplay("ArtistId: {ArtistId} FileName: {FileName}")]
|
||||
public record UpdateArtistCoverCommand(
|
||||
string? LibraryId,
|
||||
string? ArtistId,
|
||||
Stream? Cover,
|
||||
string? FileName
|
||||
) : ICommand;
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to update the cover image of an existing artist.
|
||||
/// </summary>
|
||||
public class UpdateArtistCoverCommandHandler : ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IMusicArtworkService _musicArtworkService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<UpdateArtistCoverCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="musicArtworkService">Injected service for storing the artwork of a music library item.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public UpdateArtistCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateArtistCoverCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_musicArtworkService = musicArtworkService;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update the cover image of an existing artist.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the response carrying the relative path of the stored cover image, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<UpdateArtistCoverResponse>> HandleAsync(UpdateArtistCoverCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route identifiers are non-empty Guids before this point.
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
|
||||
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getArtistResult.IsFailure)
|
||||
return getArtistResult.Errors;
|
||||
if (getArtistResult.Value is null)
|
||||
return DomainErrors.Music.ArtistNotFound;
|
||||
ArtistEntity existingArtist = getArtistResult.Value;
|
||||
|
||||
// Resource scoping: the artist must belong to the library named by the route, so that an artist can never be edited through another
|
||||
// library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library.
|
||||
if (existingArtist.LibraryId != libraryId)
|
||||
return DomainErrors.Music.ArtistNotFound;
|
||||
|
||||
// Admins can update the artists of all libraries; for everyone else, only the artists of the libraries they own.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingArtist.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
string libraryName = getLibraryResult.Value.Title;
|
||||
|
||||
// The existing cover of the artist is looked up, so that the previous file can be replaced as a whole instead of being left orphaned on disk.
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtworkResult.IsFailure)
|
||||
return getArtworkResult.Errors;
|
||||
string? existingCoverPath = getArtworkResult.Value
|
||||
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault();
|
||||
|
||||
Result<string> storeArtworkResult = await _musicArtworkService.SaveArtistArtworkAsync(
|
||||
existingArtist.LibraryId,
|
||||
libraryName,
|
||||
existingArtist.Name,
|
||||
command.Cover!,
|
||||
command.FileName!,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
if (storeArtworkResult.IsFailure)
|
||||
return storeArtworkResult.Errors;
|
||||
|
||||
// The stored cover of the artist is replaced as a whole: when the new cover is stored under a different name than the previous one
|
||||
// (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
|
||||
if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
|
||||
{
|
||||
Result<Deleted> deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
|
||||
if (deleteResult.IsFailure)
|
||||
return deleteResult.Errors;
|
||||
}
|
||||
|
||||
// Map the newly stored cover image onto the artwork of the artist, replacing the existing cover or adding a new one.
|
||||
Result<Updated> upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
|
||||
MusicArtworkOwnerType.Artist, artistId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
return new UpdateArtistCoverResponse(storeArtworkResult.Value);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="UpdateArtistCoverCommand"/>.
|
||||
/// </summary>
|
||||
public class UpdateArtistCoverCommandValidator : AbstractValidator<UpdateArtistCoverCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public UpdateArtistCoverCommandValidator()
|
||||
{
|
||||
// Validates the identifier of the media library the artist belongs to, taken from the route.
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.LibraryId)
|
||||
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
|
||||
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the artist whose cover image is updated, taken from the route.
|
||||
RuleFor(command => command.ArtistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.ArtistId)
|
||||
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
|
||||
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
// Validates the uploaded cover image.
|
||||
RuleFor(command => command.Cover)
|
||||
.NotNull()
|
||||
.WithError(Errors.Music.CoverCannotBeNull);
|
||||
|
||||
RuleFor(command => command.FileName)
|
||||
.NotEmpty()
|
||||
.When(command => command.Cover is not null)
|
||||
.WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response of an update album cover operation.
|
||||
/// </summary>
|
||||
/// <param name="CoverPath">The relative path of the stored cover image.</param>
|
||||
[DebuggerDisplay("CoverPath: {CoverPath}")]
|
||||
public record UpdateAlbumCoverResponse(
|
||||
string CoverPath
|
||||
);
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response of an update artist cover operation.
|
||||
/// </summary>
|
||||
/// <param name="CoverPath">The relative path of the stored cover image.</param>
|
||||
[DebuggerDisplay("CoverPath: {CoverPath}")]
|
||||
public record UpdateArtistCoverResponse(
|
||||
string CoverPath
|
||||
);
|
||||
@@ -65,5 +65,6 @@ public static partial class Errors
|
||||
public static Error IsniValueCannotBeEmpty => Error.Validation(description: nameof(IsniValueCannotBeEmpty));
|
||||
public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong));
|
||||
public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty));
|
||||
public static Error CoverCannotBeNull => Error.Validation(description: nameof(CoverCannotBeNull));
|
||||
}
|
||||
}
|
||||
+1
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
|
||||
public const string ADD_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums";
|
||||
public const string GET_ALBUM_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
|
||||
public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
|
||||
public const string UPDATE_ALBUM_COVER = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover";
|
||||
public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
|
||||
public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks";
|
||||
public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite";
|
||||
|
||||
+1
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
|
||||
public const string GET_ARTISTS_LITE = "/libraries/{libraryId}/artists/lite";
|
||||
public const string ADD_ARTIST = "/libraries/{libraryId}/artists";
|
||||
public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
|
||||
public const string UPDATE_ARTIST_COVER = "/libraries/{libraryId}/artists/{artistId}/cover";
|
||||
public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover</c> route.
|
||||
/// </summary>
|
||||
public class UpdateAlbumCoverEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>> _updateAlbumCoverCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="updateAlbumCoverCommandHandler">Injected service for handling update album cover commands.</param>
|
||||
public UpdateAlbumCoverEndpoint(ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>> updateAlbumCoverCommandHandler)
|
||||
{
|
||||
_updateAlbumCoverCommandHandler = updateAlbumCoverCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.Albums.UPDATE_ALBUM_COVER);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the cover image of the album with the image uploaded in the multipart form of the request.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take the identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
|
||||
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
|
||||
|
||||
IFormFile? cover = null;
|
||||
if (HttpContext.Request.HasFormContentType)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
|
||||
// so a malformed upload is treated as a missing cover, which the command validator reports.
|
||||
cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
cover = null;
|
||||
}
|
||||
}
|
||||
|
||||
// The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
|
||||
UpdateAlbumCoverCommand command = new(libraryId, artistId, albumId, cover?.OpenReadStream(), cover?.FileName);
|
||||
try
|
||||
{
|
||||
Result<UpdateAlbumCoverResponse> result = await _updateAlbumCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
finally
|
||||
{
|
||||
command.Cover?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="UpdateAlbumCoverEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCoverEndpointSummary : Summary<UpdateAlbumCoverEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public UpdateAlbumCoverEndpointSummary()
|
||||
{
|
||||
Summary = "Updates the cover image of an album.";
|
||||
Description = "Updates the cover image of the album identified by the route, with the image uploaded in the multipart form of the request.";
|
||||
|
||||
Response(200, "The relative path of the stored cover image is returned.",
|
||||
example: new UpdateAlbumCoverResponse(
|
||||
CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/A Night at the Opera-7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f/cover.jpg"
|
||||
)
|
||||
);
|
||||
|
||||
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 = "Authentication failed",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
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.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the album or its media library does not exist.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "AlbumNotFound",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "LibraryNotFound",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "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/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty",
|
||||
"ArtistIdCannotBeEmpty",
|
||||
"AlbumIdCannotBeEmpty",
|
||||
"CoverCannotBeNull",
|
||||
"FileNameCannotBeEmpty",
|
||||
"FileTooLarge",
|
||||
"CoverFileMustBeAnImage"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/cover</c> route.
|
||||
/// </summary>
|
||||
public class UpdateArtistCoverEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>> _updateArtistCoverCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="updateArtistCoverCommandHandler">Injected service for handling update artist cover commands.</param>
|
||||
public UpdateArtistCoverEndpoint(ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>> updateArtistCoverCommandHandler)
|
||||
{
|
||||
_updateArtistCoverCommandHandler = updateArtistCoverCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.Artists.UPDATE_ARTIST_COVER);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the cover image of the artist with the image uploaded in the multipart form of the request.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take the identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
|
||||
|
||||
IFormFile? cover = null;
|
||||
if (HttpContext.Request.HasFormContentType)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
|
||||
// so a malformed upload is treated as a missing cover, which the command validator reports.
|
||||
cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
cover = null;
|
||||
}
|
||||
}
|
||||
|
||||
// The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
|
||||
UpdateArtistCoverCommand command = new(libraryId, artistId, cover?.OpenReadStream(), cover?.FileName);
|
||||
try
|
||||
{
|
||||
Result<UpdateArtistCoverResponse> result = await _updateArtistCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
finally
|
||||
{
|
||||
command.Cover?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="UpdateArtistCoverEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistCoverEndpointSummary : Summary<UpdateArtistCoverEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public UpdateArtistCoverEndpointSummary()
|
||||
{
|
||||
Summary = "Updates the cover image of an artist.";
|
||||
Description = "Updates the cover image of the artist identified by the route, with the image uploaded in the multipart form of the request.";
|
||||
|
||||
Response(200, "The relative path of the stored cover image is returned.",
|
||||
example: new UpdateArtistCoverResponse(
|
||||
CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg"
|
||||
)
|
||||
);
|
||||
|
||||
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 = "Authentication failed",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
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.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the artist or its media library does not exist.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "ArtistNotFound",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "LibraryNotFound",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "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/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty",
|
||||
"ArtistIdCannotBeEmpty",
|
||||
"CoverCannotBeNull",
|
||||
"FileNameCannotBeEmpty",
|
||||
"FileTooLarge",
|
||||
"CoverFileMustBeAnImage"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -265,6 +265,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "albums", "albums", "{B4DF8E
|
||||
..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F3818697-E304-491D-8BF3-4DAA1733B5F5}"
|
||||
@@ -277,6 +278,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F381
|
||||
..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657B1-60DC-4E22-89D2-6212154D6BA8}"
|
||||
|
||||
Reference in new issue
Block a user