mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Adds playlist management and playback
This commit is contained in:
1 parent
009a0c8156
commit
9889c86c76
296 files changed
+18830
-367
No files matched your search
+14
-32
@@ -9,35 +9,17 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A
|
||||
/// <summary>
|
||||
/// Lightweight read model of an album, containing only the fields needed to display the album in a card-based grid or a list.
|
||||
/// </summary>
|
||||
public sealed record AlbumLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the album.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the album.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of tracks of the release.
|
||||
/// </summary>
|
||||
public int TotalTracks { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the image representing the album, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the release year of the album (the re-release year, if available, or the original release year), if known.
|
||||
/// </summary>
|
||||
public int? ReleaseYear { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the set of types of the release.
|
||||
/// </summary>
|
||||
public List<MusicReleaseType>? ReleaseTypes { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the album.</param>
|
||||
/// <param name="Title">The title of the album.</param>
|
||||
/// <param name="TotalTracks">The number of tracks of the release.</param>
|
||||
/// <param name="CoverPath">The path of the image representing the album, if available.</param>
|
||||
/// <param name="ReleaseYear">The release year of the album (the re-release year, if available, or the original release year), if known.</param>
|
||||
/// <param name="ReleaseTypes">The set of types of the release.</param>
|
||||
public sealed record AlbumLiteRow(
|
||||
Guid Id,
|
||||
string Title,
|
||||
int TotalTracks,
|
||||
string? CoverPath,
|
||||
int? ReleaseYear,
|
||||
List<MusicReleaseType>? ReleaseTypes
|
||||
);
|
||||
+8
-17
@@ -7,20 +7,11 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A
|
||||
/// <summary>
|
||||
/// Lightweight read model of an artist, containing only the fields needed to display the artist in a card-based grid or a list.
|
||||
/// </summary>
|
||||
public sealed record ArtistLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the artist.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the artist.
|
||||
/// </summary>
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the image representing the artist, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the artist.</param>
|
||||
/// <param name="Name">The name of the artist.</param>
|
||||
/// <param name="CoverPath">The path of the image representing the artist, if available.</param>
|
||||
public sealed record ArtistLiteRow(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? CoverPath
|
||||
);
|
||||
+16
-37
@@ -7,40 +7,19 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
|
||||
/// <summary>
|
||||
/// Read model of a track returned by a randomized shuffle query, carrying everything the client needs to queue and play it.
|
||||
/// </summary>
|
||||
public sealed record ShuffleTrackRowDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the track.
|
||||
/// </summary>
|
||||
public required Guid TrackId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the track.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the album the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid AlbumId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the album the track belongs to.
|
||||
/// </summary>
|
||||
public required string AlbumTitle { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the artist the album belongs to.
|
||||
/// </summary>
|
||||
public required Guid ArtistId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the cover of the album, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
}
|
||||
/// <param name="TrackId">The Id of the track.</param>
|
||||
/// <param name="Title">The title of the track.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <param name="AlbumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="AlbumTitle">The title of the album the track belongs to.</param>
|
||||
/// <param name="ArtistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="CoverPath">The path of the cover of the album, if available.</param>
|
||||
public sealed record ShuffleTrackRowDto(
|
||||
Guid TrackId,
|
||||
string Title,
|
||||
int DurationInSeconds,
|
||||
Guid AlbumId,
|
||||
string AlbumTitle,
|
||||
Guid ArtistId,
|
||||
string? CoverPath
|
||||
);
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the access information of a set of existing tracks.
|
||||
/// </summary>
|
||||
/// <param name="TrackCount">The number of distinct requested tracks that exist.</param>
|
||||
/// <param name="LibraryIds">The distinct Ids of the media libraries that contain those tracks.</param>
|
||||
[DebuggerDisplay("TrackCount: {TrackCount}; Libraries: {LibraryIds.Count}")]
|
||||
public sealed record TrackAccessSummaryDto(
|
||||
int TrackCount,
|
||||
IReadOnlyList<Guid> LibraryIds
|
||||
);
|
||||
+12
-27
@@ -7,30 +7,15 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
|
||||
/// <summary>
|
||||
/// Lightweight read model of a track, containing only the fields needed to display the track in a list.
|
||||
/// </summary>
|
||||
public sealed record TrackLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the track.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the track.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of the track on its disc.
|
||||
/// </summary>
|
||||
public int TrackNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of the disc the track belongs to, if applicable.
|
||||
/// </summary>
|
||||
public int? DiscNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the track.</param>
|
||||
/// <param name="Title">The title of the track.</param>
|
||||
/// <param name="TrackNumber">The number of the track on its disc.</param>
|
||||
/// <param name="DiscNumber">The number of the disc the track belongs to, if applicable.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
|
||||
public sealed record TrackLiteRow(
|
||||
Guid Id,
|
||||
string Title,
|
||||
int TrackNumber,
|
||||
int? DiscNumber,
|
||||
int DurationInSeconds
|
||||
);
|
||||
+10
-22
@@ -7,25 +7,13 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookL
|
||||
/// <summary>
|
||||
/// Lightweight read model of a book, containing only the fields needed to display the book in a card-based grid or a list.
|
||||
/// </summary>
|
||||
public sealed record BookLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the book.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the book.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the release year of the book (re-release year, if available, or original release year), if known.
|
||||
/// </summary>
|
||||
public int? ReleaseYear { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the image representing the cover of the book, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the book.</param>
|
||||
/// <param name="Title">The title of the book.</param>
|
||||
/// <param name="ReleaseYear">The release year of the book (re-release year, if available, or original release year), if known.</param>
|
||||
/// <param name="CoverPath">The path of the image representing the cover of the book, if available.</param>
|
||||
public sealed record BookLiteRow(
|
||||
Guid Id,
|
||||
string Title,
|
||||
int? ReleaseYear,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the result of appending entries to a playlist in one bulk operation.
|
||||
/// </summary>
|
||||
/// <param name="FirstPosition">The sparse order key of the first appended entry.</param>
|
||||
/// <param name="AddedCount">The number of entries appended.</param>
|
||||
[DebuggerDisplay("FirstPosition: {FirstPosition}; AddedCount: {AddedCount}")]
|
||||
public sealed record PlaylistBulkAddResultDto(
|
||||
long FirstPosition,
|
||||
int AddedCount
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// A stored playlist together with a window of its entries and their display data.
|
||||
/// </summary>
|
||||
/// <param name="Playlist">The stored playlist.</param>
|
||||
/// <param name="Entries">The requested window of entries.</param>
|
||||
public sealed record PlaylistDetailsDto(
|
||||
PlaylistEntity Playlist,
|
||||
IReadOnlyList<PlaylistEntryDto> Entries
|
||||
);
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Display data of the media item referenced by a playlist entry, together with its collection and creator.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track.</param>
|
||||
/// <param name="TrackTitle">The title of the track.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
|
||||
/// <param name="AlbumId">The Id of the album that contains the track.</param>
|
||||
/// <param name="AlbumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
|
||||
/// <param name="ArtistName">The name of the artist that produced the track.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
|
||||
public sealed record PlaylistEntryDisplayDto(
|
||||
Guid TrackId,
|
||||
string TrackTitle,
|
||||
int DurationInSeconds,
|
||||
Guid LibraryId,
|
||||
Guid AlbumId,
|
||||
string AlbumTitle,
|
||||
Guid ArtistId,
|
||||
string ArtistName,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// A stored playlist entry together with the display data of the media item it references and its dense display position.
|
||||
/// </summary>
|
||||
/// <param name="Entry">The stored entry.</param>
|
||||
/// <param name="Display">The display data of the referenced media item, or <see langword="null"/> when it no longer exists.</param>
|
||||
/// <param name="DisplayPosition">The dense zero based position shown to the client.</param>
|
||||
public sealed record PlaylistEntryDto(
|
||||
PlaylistEntryEntity Entry,
|
||||
PlaylistEntryDisplayDto? Display,
|
||||
int DisplayPosition
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a playlist in a list, without its entries.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the playlist.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The description of the playlist, if applicable.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
/// <param name="EntryCount">The number of entries of the playlist.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the playlist was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
public sealed record PlaylistSummaryDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
int EntryCount,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a playlist.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; Type: {Type}")]
|
||||
public class PlaylistEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the playlist.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that owns the playlist.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the playlist.
|
||||
/// </summary>
|
||||
public required string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the playlist, if applicable.
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind of media the playlist holds.
|
||||
/// </summary>
|
||||
public required PlaylistType Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ordered entries of the playlist.
|
||||
/// </summary>
|
||||
public List<PlaylistEntryEntity> Entries { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of entries the playlist holds.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The count is maintained by the set-based entry operations in the same statement that appends or removes entries and updates the
|
||||
/// playlist, so reading a window of a very large playlist never has to count its entries.
|
||||
/// </remarks>
|
||||
public int EntryCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the concurrency token of the playlist.
|
||||
/// </summary>
|
||||
public long Version { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for an ordered entry of a playlist.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The entry references a media item by its Id and by the kind of media item, without a foreign key, so a playlist survives the deletion
|
||||
/// of the item it references and the entry can be shown to its owner so that it can be removed.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay("Id: {Id}; MediaItemId: {MediaItemId}; MediaItemType: {MediaItemType}; Position: {Position}")]
|
||||
public class PlaylistEntryEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the entry.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the playlist the entry belongs to.
|
||||
/// </summary>
|
||||
public required Guid PlaylistId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media item referenced by the entry.
|
||||
/// </summary>
|
||||
public required Guid MediaItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind of media item referenced by the entry.
|
||||
/// </summary>
|
||||
public PlaylistMediaItemType MediaItemType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sparse order key of the entry in the ordered entries of the playlist.
|
||||
/// </summary>
|
||||
public long Position { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entry was added.
|
||||
/// </summary>
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entry.
|
||||
/// </summary>
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entry was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entry.
|
||||
/// </summary>
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -129,4 +129,12 @@ public interface ITrackRepository : IRepository<TrackEntity>,
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of tracks in <paramref name="trackIds"/> that exist, together with the distinct Ids of the libraries that contain them.
|
||||
/// </summary>
|
||||
/// <param name="trackIds">The Ids of the tracks whose access information is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the access summary of the existing tracks, or an error.</returns>
|
||||
Task<Result<TrackAccessSummaryDto>> GetAccessInfoByIdsAsync(IReadOnlyCollection<Guid> trackIds, CancellationToken cancellationToken);
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for playlists.
|
||||
/// </summary>
|
||||
public interface IPlaylistRepository : IRepository<PlaylistEntity>,
|
||||
IInsertRepositoryAction<PlaylistEntity>,
|
||||
IUpdateRepositoryAction<PlaylistEntity>,
|
||||
IDeleteByIdRepositoryAction<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the playlist identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the playlist to get.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="shouldIncludeNavigationProperties">Whether the entries of the playlist should be loaded together with the playlist itself.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the playlist identified by <paramref name="id"/> and owned by <paramref name="userId"/>,
|
||||
/// <see langword="null"/> when no such playlist exists, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistEntity?>> GetByIdForUserAsync(Guid id, Guid userId, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlists of the user identified by <paramref name="userId"/>, ordered by their most recent activity.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose playlists are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the playlists of the user, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<PlaylistSummaryDto>>> GetAllForUserAsync(Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist identified by <paramref name="id"/> together with the display details of the media items its entries reference,
|
||||
/// when the playlist belongs to the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the playlist to get.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the playlist details, <see langword="null"/> when no such playlist exists, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, int offset, int limit, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Appends a batch of media items of one kind to the end of the ordered entries of a playlist of the user identified by
|
||||
/// <paramref name="userId"/>, using batched bulk inserts, and updates the activity time of the playlist in the same transaction.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist to append to.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="mediaItemIds">The Ids of the media items to append, in order. Duplicates are kept.</param>
|
||||
/// <param name="mediaItemType">The kind of media item referenced by every appended entry.</param>
|
||||
/// <param name="entryIds">The Ids to assign to the appended entries, in the same order as <paramref name="mediaItemIds"/>, or <see langword="null"/> to generate them.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the sparse order key of the first appended entry and the added count, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistBulkAddResultDto>> AddEntriesAsync(Guid playlistId, Guid userId, IReadOnlyList<Guid> mediaItemIds, PlaylistMediaItemType mediaItemType, IReadOnlyList<Guid>? entryIds, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Appends every media item of a library, an artist or an album to the end of the ordered entries of a playlist of the user identified by
|
||||
/// <paramref name="userId"/>, in catalogue order, without materializing the scope.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist to append to.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="libraryId">The Id of the library whose media items are appended.</param>
|
||||
/// <param name="artistId">The Id of the artist the scope is limited to, or <see langword="null"/> for every artist of the library.</param>
|
||||
/// <param name="albumId">The Id of the album the scope is limited to, or <see langword="null"/> for every album of the scope.</param>
|
||||
/// <param name="mediaItemType">The kind of media item referenced by every appended entry.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the sparse order key of the first appended entry and the added count, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistBulkAddResultDto>> AddScopeEntriesAsync(Guid playlistId, Guid userId, Guid libraryId, Guid? artistId, Guid? albumId, PlaylistMediaItemType mediaItemType, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Moves one entry of a playlist of the user identified by <paramref name="userId"/> to a new dense position by changing only its
|
||||
/// sparse order key, and updates the activity time of the playlist in the same transaction.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist whose entry is moved.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="entryId">The Id of the entry to move.</param>
|
||||
/// <param name="targetPosition">The new zero based position of the entry.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful move, or an error.</returns>
|
||||
Task<Result<Updated>> MoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, int targetPosition, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes one entry of a playlist of the user identified by <paramref name="userId"/> by deleting only that row, and updates the
|
||||
/// activity time of the playlist in the same transaction.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist whose entry is removed.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="entryId">The Id of the entry to remove.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either zero, because sparse positions need no repositioning, or an error.
|
||||
/// </returns>
|
||||
Task<Result<int>> RemoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the entry that was just appended to a playlist of the user identified by <paramref name="userId"/>, together with the display details of the track it references.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist the entry must belong to.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="entryId">The Id of the appended entry to get.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the entry details, <see langword="null"/> when the entry does not exist in that playlist of the user, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistEntryDto?>> GetAppendedEntryDetailsForUserAsync(Guid playlistId, Guid userId, Guid entryId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Themes;
|
||||
@@ -155,6 +156,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IMusicPlayRecordRepository MusicPlayRecordRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist repository.
|
||||
/// </summary>
|
||||
IPlaylistRepository PlaylistRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddPlaylistEntriesRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddPlaylistEntriesRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddPlaylistEntriesCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddPlaylistEntriesCommand ToCommand(this AddPlaylistEntriesRequest request, string? playlistId)
|
||||
{
|
||||
return new AddPlaylistEntriesCommand(playlistId, request.TrackIds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddPlaylistEntryRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddPlaylistEntryRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddPlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddPlaylistEntryCommand ToCommand(this AddPlaylistEntryRequest request, string? playlistId)
|
||||
{
|
||||
return new AddPlaylistEntryCommand(playlistId, request.TrackId);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddPlaylistScopeEntriesRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddPlaylistScopeEntriesRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddPlaylistScopeEntriesCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddPlaylistScopeEntriesCommand ToCommand(this AddPlaylistScopeEntriesRequest request, string? playlistId)
|
||||
{
|
||||
return new AddPlaylistScopeEntriesCommand(playlistId, request.LibraryId, request.ArtistId, request.AlbumId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Playlists.Commands.CreatePlaylist;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="CreatePlaylistRequest"/>.
|
||||
/// </summary>
|
||||
public static class CreatePlaylistRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="CreatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static CreatePlaylistCommand ToCommand(this CreatePlaylistRequest request)
|
||||
{
|
||||
return new CreatePlaylistCommand(request.Name, request.Description, request.Type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="MovePlaylistEntryRequest"/>.
|
||||
/// </summary>
|
||||
public static class MovePlaylistEntryRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="MovePlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <param name="playlistEntryId">The Id of the entry to move, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static MovePlaylistEntryCommand ToCommand(this MovePlaylistEntryRequest request, string? playlistId, string? playlistEntryId)
|
||||
{
|
||||
return new MovePlaylistEntryCommand(playlistId, playlistEntryId, request.TargetPosition);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistDetailsDto"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistDetailsDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to <see cref="PlaylistResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The playlist details data to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static PlaylistResponse ToResponse(this PlaylistDetailsDto data)
|
||||
{
|
||||
return new PlaylistResponse(
|
||||
data.Playlist.Id,
|
||||
data.Playlist.Name,
|
||||
data.Playlist.Description,
|
||||
data.Playlist.Type,
|
||||
[.. data.Entries.Select(entry => entry.ToResponse())],
|
||||
data.Playlist.EntryCount,
|
||||
data.Playlist.CreatedOnUtc,
|
||||
data.Playlist.UpdatedOnUtc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntity"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="Playlist"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Playlist"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Playlist> ToDomainEntity(this PlaylistEntity repositoryEntity)
|
||||
{
|
||||
List<PlaylistEntry> entries = [];
|
||||
// The entries are ordered by their position, because the order of a navigation collection is not guaranteed by the storage medium.
|
||||
foreach (PlaylistEntryEntity entryEntity in repositoryEntity.Entries.OrderBy(entry => entry.Position))
|
||||
{
|
||||
Result<PlaylistEntry> convertEntryResult = entryEntity.ToDomainEntity();
|
||||
if (convertEntryResult.IsFailure)
|
||||
return convertEntryResult.Errors;
|
||||
entries.Add(convertEntryResult.Value);
|
||||
}
|
||||
|
||||
return Playlist.Create(
|
||||
PlaylistId.Create(repositoryEntity.Id),
|
||||
UserId.Create(repositoryEntity.UserId),
|
||||
repositoryEntity.Name,
|
||||
Optional<string>.FromNullable(repositoryEntity.Description),
|
||||
repositoryEntity.Type,
|
||||
entries,
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntryDto"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntryDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to <see cref="PlaylistEntryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The playlist entry data to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static PlaylistEntryResponse ToResponse(this PlaylistEntryDto data)
|
||||
{
|
||||
if (data.Display is null)
|
||||
return new PlaylistEntryResponse(
|
||||
data.Entry.Id,
|
||||
data.Entry.MediaItemId,
|
||||
data.Entry.MediaItemType,
|
||||
data.DisplayPosition,
|
||||
Guid.Empty,
|
||||
Guid.Empty,
|
||||
Guid.Empty,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
0,
|
||||
null);
|
||||
|
||||
PlaylistEntryDisplayDto display = data.Display;
|
||||
return new PlaylistEntryResponse(
|
||||
data.Entry.Id,
|
||||
data.Entry.MediaItemId,
|
||||
data.Entry.MediaItemType,
|
||||
data.DisplayPosition,
|
||||
display.LibraryId,
|
||||
display.AlbumId,
|
||||
display.ArtistId,
|
||||
display.TrackTitle,
|
||||
display.AlbumTitle,
|
||||
display.ArtistName,
|
||||
display.DurationInSeconds,
|
||||
display.CoverPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntryEntity"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntryEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="PlaylistEntry"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="PlaylistEntry"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<PlaylistEntry> ToDomainEntity(this PlaylistEntryEntity repositoryEntity)
|
||||
{
|
||||
return PlaylistEntry.Create(
|
||||
PlaylistEntryId.Create(repositoryEntity.Id),
|
||||
MediaItemId.Create(repositoryEntity.MediaItemId),
|
||||
repositoryEntity.MediaItemType,
|
||||
repositoryEntity.Position);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntry"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntryMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="PlaylistEntryEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist that owns the entry.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
public static PlaylistEntryEntity ToRepositoryEntity(this PlaylistEntry domainEntity, Guid playlistId)
|
||||
{
|
||||
return new PlaylistEntryEntity
|
||||
{
|
||||
Id = domainEntity.Id.Value,
|
||||
PlaylistId = playlistId,
|
||||
MediaItemId = domainEntity.MediaItemId.Value,
|
||||
MediaItemType = domainEntity.MediaItemType,
|
||||
Position = domainEntity.Position
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="Playlist"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="PlaylistEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
public static PlaylistEntity ToRepositoryEntity(this Playlist domainEntity)
|
||||
{
|
||||
return new PlaylistEntity
|
||||
{
|
||||
Id = domainEntity.Id.Value,
|
||||
UserId = domainEntity.UserId.Value,
|
||||
Name = domainEntity.Name,
|
||||
Description = domainEntity.Description.HasValue ? domainEntity.Description.Value : null,
|
||||
Type = domainEntity.Type,
|
||||
Entries = [.. domainEntity.Entries
|
||||
.OrderBy(entry => entry.Position)
|
||||
.Select(entry => entry.ToRepositoryEntity(domainEntity.Id.Value))],
|
||||
// This is the correct count for an insert. The update path deliberately keeps the stored count, because details edits never load the entries and must not overwrite it.
|
||||
EntryCount = domainEntity.Entries.Count,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistSummaryDto"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistSummaryDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="dto"/> to <see cref="PlaylistSummaryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="dto">The data transfer object to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static PlaylistSummaryResponse ToResponse(this PlaylistSummaryDto dto)
|
||||
{
|
||||
return new PlaylistSummaryResponse(
|
||||
dto.Id,
|
||||
dto.Name,
|
||||
dto.Description,
|
||||
dto.Type,
|
||||
dto.EntryCount,
|
||||
dto.CreatedOnUtc,
|
||||
dto.UpdatedOnUtc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="UpdatePlaylistRequest"/>.
|
||||
/// </summary>
|
||||
public static class UpdatePlaylistRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="UpdatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static UpdatePlaylistCommand ToCommand(this UpdatePlaylistRequest request, string? playlistId)
|
||||
{
|
||||
return new UpdatePlaylistCommand(playlistId, request.Name, request.Description);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding several tracks to a playlist of the current user, in order.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="TrackIds">The unique identifiers of the tracks to add, in the order they must take.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackCount: {TrackIds.Count}")]
|
||||
public record AddPlaylistEntriesCommand(
|
||||
string? PlaylistId,
|
||||
List<Guid>? TrackIds
|
||||
) : ICommand;
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
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.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
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.Playlists.Commands.AddPlaylistEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add several tracks to a playlist of the current user, in order.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntriesCommandHandler : ICommandHandler<AddPlaylistEntriesCommand, Result<PlaylistEntriesAddedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<AddPlaylistEntriesCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntriesCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddPlaylistEntriesCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<AddPlaylistEntriesCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add several tracks to a playlist of the current user, in order.
|
||||
/// </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 number of appended entries and the playlist activity time, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntriesAddedResponse>> HandleAsync(AddPlaylistEntriesCommand 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 identifier is a non-empty Guid before this point.
|
||||
Guid playlistId = Guid.Parse(command.PlaylistId!);
|
||||
|
||||
// A missing playlist is reported before any track is read.
|
||||
Result<PlaylistEntity?> getPlaylistResult = await _unitOfWork.PlaylistRepository
|
||||
.GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistNotFound;
|
||||
|
||||
// The referenced tracks are resolved in a few bounded chunks, grouped by library, so adding a long queue does not turn into one query per entry.
|
||||
// Duplicate track Ids are collapsed for the lookup, because the same track may legitimately appear more than once in a playlist.
|
||||
List<Guid> distinctTrackIds = [.. command.TrackIds!.Distinct()];
|
||||
Result<TrackAccessSummaryDto> getAccessInfoResult = await _unitOfWork.TrackRepository.GetAccessInfoByIdsAsync(distinctTrackIds, cancellationToken).ConfigureAwait(false);
|
||||
if (getAccessInfoResult.IsFailure)
|
||||
return getAccessInfoResult.Errors;
|
||||
if (getAccessInfoResult.Value.TrackCount != distinctTrackIds.Count)
|
||||
return DomainErrors.Music.TrackNotFound;
|
||||
|
||||
// Every library that owns one of the referenced tracks must be reachable by the current user. The libraries are checked once each,
|
||||
// so a queue made of many tracks of the same library does not evaluate the policy once per track.
|
||||
foreach (Guid libraryId in getAccessInfoResult.Value.LibraryIds)
|
||||
{
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
// A track whose library is not reachable is reported exactly like a missing track, so the response cannot be used to probe whether a track exists in another user's library.
|
||||
if (!canAccessLibrary)
|
||||
return DomainErrors.Music.TrackNotFound;
|
||||
}
|
||||
|
||||
if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack))
|
||||
return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems;
|
||||
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
Result<PlaylistBulkAddResultDto> addEntriesResult = await _unitOfWork.PlaylistRepository
|
||||
.AddEntriesAsync(playlistId, userId, command.TrackIds!, PlaylistMediaItemType.MusicTrack, entryIds: null, updatedOnUtc, cancellationToken).ConfigureAwait(false);
|
||||
if (addEntriesResult.IsFailure)
|
||||
return addEntriesResult.Errors;
|
||||
|
||||
return new PlaylistEntriesAddedResponse(
|
||||
playlistId,
|
||||
addEntriesResult.Value.AddedCount,
|
||||
updatedOnUtc);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#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.Playlists.Commands.AddPlaylistEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddPlaylistEntriesCommand"/>.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntriesCommandValidator : AbstractValidator<AddPlaylistEntriesCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntriesCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public AddPlaylistEntriesCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.TrackIds)
|
||||
.NotNull()
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.TrackIds)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty)
|
||||
.When(command => command.TrackIds is not null);
|
||||
|
||||
RuleForEach(command => command.TrackIds)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding a track to a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track to add.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackId: {TrackId}")]
|
||||
public record AddPlaylistEntryCommand(
|
||||
string? PlaylistId,
|
||||
Guid? TrackId
|
||||
) : ICommand;
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Playlists.Commands.AddPlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add a track to a playlist of the current user.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntryCommandHandler : ICommandHandler<AddPlaylistEntryCommand, Result<PlaylistEntryAddedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<AddPlaylistEntryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntryCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddPlaylistEntryCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<AddPlaylistEntryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add a track to a playlist of the current user.
|
||||
/// </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 appended entry and the playlist activity time, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntryAddedResponse>> HandleAsync(AddPlaylistEntryCommand 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 identifiers are non-empty Guids before this point.
|
||||
Guid playlistId = Guid.Parse(command.PlaylistId!);
|
||||
Guid trackId = command.TrackId!.Value;
|
||||
|
||||
// A missing playlist is reported before the track is read.
|
||||
Result<PlaylistEntity?> getPlaylistResult = await _unitOfWork.PlaylistRepository
|
||||
.GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistNotFound;
|
||||
|
||||
// The track must exist, and its library must be reachable by the current user, so another user's library cannot be used as a source.
|
||||
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository
|
||||
.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getTrackResult.IsFailure)
|
||||
return getTrackResult.Errors;
|
||||
if (getTrackResult.Value is null)
|
||||
return DomainErrors.Music.TrackNotFound;
|
||||
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
// A track whose library is not reachable is reported exactly like a missing track, so the response cannot be used to probe whether a track exists in another user's library.
|
||||
if (!canAccessLibrary)
|
||||
return DomainErrors.Music.TrackNotFound;
|
||||
|
||||
if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack))
|
||||
return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems;
|
||||
|
||||
Guid entryId = Guid.NewGuid();
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
Result<PlaylistBulkAddResultDto> addEntryResult = await _unitOfWork.PlaylistRepository
|
||||
.AddEntriesAsync(playlistId, userId, [trackId], PlaylistMediaItemType.MusicTrack, [entryId], updatedOnUtc, cancellationToken).ConfigureAwait(false);
|
||||
if (addEntryResult.IsFailure)
|
||||
return addEntryResult.Errors;
|
||||
|
||||
// Only the appended entry is read back, with the display details of its track, so a single add does not return the whole playlist.
|
||||
// The appended entry is the last one, so the read-back derives its display position from the stored entry count.
|
||||
Result<PlaylistEntryDto?> getEntryResult = await _unitOfWork.PlaylistRepository.GetAppendedEntryDetailsForUserAsync(playlistId, userId, entryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getEntryResult.IsFailure)
|
||||
return getEntryResult.Errors;
|
||||
if (getEntryResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistEntryNotFound;
|
||||
|
||||
return new PlaylistEntryAddedResponse(
|
||||
playlistId,
|
||||
getEntryResult.Value.ToResponse(),
|
||||
updatedOnUtc);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#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.Playlists.Commands.AddPlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddPlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntryCommandValidator : AbstractValidator<AddPlaylistEntryCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public AddPlaylistEntryCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.TrackId)
|
||||
.NotNull()
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.TrackId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty)
|
||||
.When(command => command.TrackId is not null);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Command to add every track of a music library, an artist or an album to a playlist, with the track Ids resolved by the server.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <param name="LibraryId">The Id of the music library the scope belongs to.</param>
|
||||
/// <param name="ArtistId">The Id of the artist the scope is limited to, if applicable.</param>
|
||||
/// <param name="AlbumId">The Id of the album the scope is limited to, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")]
|
||||
public record AddPlaylistScopeEntriesCommand(
|
||||
string? PlaylistId,
|
||||
Guid? LibraryId,
|
||||
Guid? ArtistId,
|
||||
Guid? AlbumId
|
||||
) : ICommand;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
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.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Playlists.Commands.AddPlaylistScopeEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add every track of a music library, an artist or an album to a playlist.
|
||||
/// </summary>
|
||||
public class AddPlaylistScopeEntriesCommandHandler : ICommandHandler<AddPlaylistScopeEntriesCommand, Result<PlaylistEntriesAddedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<AddPlaylistScopeEntriesCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddPlaylistScopeEntriesCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<AddPlaylistScopeEntriesCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add every track of a music library, an artist or an album to a playlist.
|
||||
/// </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 number of appended entries and the playlist activity time, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntriesAddedResponse>> HandleAsync(AddPlaylistScopeEntriesCommand 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 identifiers are non-empty Guids before this point.
|
||||
Guid playlistId = Guid.Parse(command.PlaylistId!);
|
||||
Guid libraryId = command.LibraryId!.Value;
|
||||
|
||||
// A missing playlist is reported before a whole library is resolved.
|
||||
Result<PlaylistEntity?> getPlaylistResult = await _unitOfWork.PlaylistRepository
|
||||
.GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistNotFound;
|
||||
|
||||
// The whole scope belongs to one library, so access is evaluated once for the entire scope.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack))
|
||||
return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems;
|
||||
|
||||
// The repository resolves the scope and appends it in one set-based statement, so a whole library of any size is appended without
|
||||
// materializing its track Ids, sorting them in memory, or constructing one domain event per track.
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
Result<PlaylistBulkAddResultDto> addEntriesResult = await _unitOfWork.PlaylistRepository
|
||||
.AddScopeEntriesAsync(playlistId, userId, libraryId, command.ArtistId, command.AlbumId, PlaylistMediaItemType.MusicTrack, updatedOnUtc, cancellationToken).ConfigureAwait(false);
|
||||
if (addEntriesResult.IsFailure)
|
||||
return addEntriesResult.Errors;
|
||||
|
||||
return new PlaylistEntriesAddedResponse(
|
||||
playlistId,
|
||||
addEntriesResult.Value.AddedCount,
|
||||
addEntriesResult.Value.AddedCount == 0 ? null : updatedOnUtc);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#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.Playlists.Commands.AddPlaylistScopeEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddPlaylistScopeEntriesCommand"/>.
|
||||
/// </summary>
|
||||
public class AddPlaylistScopeEntriesCommandValidator : AbstractValidator<AddPlaylistScopeEntriesCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public AddPlaylistScopeEntriesCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.LibraryId)
|
||||
.Must(libraryId => libraryId.HasValue && libraryId.Value != Guid.Empty)
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.ArtistId)
|
||||
.Must(artistId => !artistId.HasValue || artistId.Value != Guid.Empty)
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.AlbumId)
|
||||
.Must(albumId => !albumId.HasValue || albumId.Value != Guid.Empty)
|
||||
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.CreatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Command for creating a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The optional description of the playlist.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public record CreatePlaylistCommand(
|
||||
string? Name,
|
||||
string? Description,
|
||||
PlaylistType? Type
|
||||
) : ICommand;
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Playlists.Commands.CreatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to create a playlist of the current user.
|
||||
/// </summary>
|
||||
public class CreatePlaylistCommandHandler : ICommandHandler<CreatePlaylistCommand, Result<PlaylistResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<CreatePlaylistCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CreatePlaylistCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public CreatePlaylistCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<CreatePlaylistCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to create a playlist of the current user.
|
||||
/// </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 created <see cref="PlaylistResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistResponse>> HandleAsync(CreatePlaylistCommand 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;
|
||||
|
||||
Result<Playlist> createPlaylistResult = Playlist.Create(
|
||||
UserId.Create(userId),
|
||||
command.Name!,
|
||||
Optional<string>.FromNullable(command.Description),
|
||||
command.Type!.Value);
|
||||
if (createPlaylistResult.IsFailure)
|
||||
return createPlaylistResult.Errors;
|
||||
Playlist playlist = createPlaylistResult.Value;
|
||||
|
||||
Result<Created> insertResult = await _unitOfWork.PlaylistRepository.InsertAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
return insertResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully.
|
||||
foreach (IDomainEvent domainEvent in playlist.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored.
|
||||
Result<PlaylistDetailsDto?> getDetailsResult = await _unitOfWork.PlaylistRepository
|
||||
.GetDetailsForUserAsync(playlist.Id.Value, userId, 0, PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getDetailsResult.IsFailure)
|
||||
return getDetailsResult.Errors;
|
||||
if (getDetailsResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistNotFound;
|
||||
|
||||
return getDetailsResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.CreatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="CreatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
public class CreatePlaylistCommandValidator : AbstractValidator<CreatePlaylistCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CreatePlaylistCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public CreatePlaylistCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.Name)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistNameCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.Name)
|
||||
.MaximumLength(255)
|
||||
.WithError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong);
|
||||
|
||||
RuleFor(command => command.Description)
|
||||
.MaximumLength(2000)
|
||||
.WithError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong);
|
||||
|
||||
RuleFor(command => command.Type)
|
||||
.NotNull()
|
||||
.WithError(Errors.Playlists.PlaylistTypeIsInvalid);
|
||||
|
||||
RuleFor(command => command.Type)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Playlists.PlaylistTypeIsInvalid)
|
||||
.When(command => command.Type is not null);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.DeletePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Command for deleting a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}")]
|
||||
public record DeletePlaylistCommand(
|
||||
string? PlaylistId
|
||||
) : ICommand;
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Playlists.Commands.DeletePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to delete a playlist of the current user.
|
||||
/// </summary>
|
||||
public class DeletePlaylistCommandHandler : ICommandHandler<DeletePlaylistCommand, Result<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<DeletePlaylistCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletePlaylistCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public DeletePlaylistCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<DeletePlaylistCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to delete a playlist of the current user.
|
||||
/// </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}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Deleted>> HandleAsync(DeletePlaylistCommand 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 identifier is a non-empty Guid before this point.
|
||||
Guid playlistId = Guid.Parse(command.PlaylistId!);
|
||||
|
||||
// The playlist is loaded so that its aggregate can raise the deletion event before the row is removed.
|
||||
Result<PlaylistEntity?> getPlaylistResult = await _unitOfWork.PlaylistRepository
|
||||
.GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistNotFound;
|
||||
|
||||
Result<Playlist> toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Playlist playlist = toDomainEntityResult.Value;
|
||||
|
||||
Result<Deleted> deleteResult = playlist.Delete();
|
||||
if (deleteResult.IsFailure)
|
||||
return deleteResult.Errors;
|
||||
|
||||
Result<Deleted> deletePlaylistResult = await _unitOfWork.PlaylistRepository.DeleteByIdAsync(playlist.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (deletePlaylistResult.IsFailure)
|
||||
return deletePlaylistResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
foreach (IDomainEvent domainEvent in playlist.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return Result.Deleted;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#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.Playlists.Commands.DeletePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="DeletePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
public class DeletePlaylistCommandValidator : AbstractValidator<DeletePlaylistCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletePlaylistCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public DeletePlaylistCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Command for moving one entry of a playlist of the current user to a new position.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="PlaylistEntryId">The unique identifier of the entry to move, taken from the route.</param>
|
||||
/// <param name="TargetPosition">The new zero based position of the entry.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}; TargetPosition: {TargetPosition}")]
|
||||
public record MovePlaylistEntryCommand(
|
||||
string? PlaylistId,
|
||||
string? PlaylistEntryId,
|
||||
int? TargetPosition
|
||||
) : ICommand;
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to move one entry of a playlist of the current user to a new position.
|
||||
/// </summary>
|
||||
public class MovePlaylistEntryCommandHandler : ICommandHandler<MovePlaylistEntryCommand, Result<PlaylistEntryMovedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<MovePlaylistEntryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovePlaylistEntryCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public MovePlaylistEntryCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IValidator<MovePlaylistEntryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to move one entry of a playlist of the current user to a new position.
|
||||
/// </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 moved entry and its position, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntryMovedResponse>> HandleAsync(MovePlaylistEntryCommand 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 playlistId = Guid.Parse(command.PlaylistId!);
|
||||
Guid playlistEntryId = Guid.Parse(command.PlaylistEntryId!);
|
||||
int targetPosition = command.TargetPosition!.Value;
|
||||
|
||||
// The entry is moved directly in the storage medium, so a playlist of any size is not loaded into memory for one move.
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
Result<Updated> moveEntryResult = await _unitOfWork.PlaylistRepository
|
||||
.MoveEntryAsync(playlistId, userId, playlistEntryId, targetPosition, updatedOnUtc, cancellationToken).ConfigureAwait(false);
|
||||
if (moveEntryResult.IsFailure)
|
||||
return moveEntryResult.Errors;
|
||||
|
||||
return new PlaylistEntryMovedResponse(
|
||||
playlistId,
|
||||
playlistEntryId,
|
||||
targetPosition,
|
||||
updatedOnUtc);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#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.Playlists.Commands.MovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="MovePlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
public class MovePlaylistEntryCommandValidator : AbstractValidator<MovePlaylistEntryCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovePlaylistEntryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public MovePlaylistEntryCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistEntryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistEntryId)
|
||||
.Must(entryId => Guid.TryParse(entryId, out Guid parsedEntryId) && parsedEntryId != Guid.Empty)
|
||||
.When(command => command.PlaylistEntryId is not null && command.PlaylistEntryId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.TargetPosition)
|
||||
.NotNull()
|
||||
.WithError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid);
|
||||
|
||||
RuleFor(command => command.TargetPosition)
|
||||
.Must(targetPosition => targetPosition.HasValue && targetPosition.Value >= 0)
|
||||
.When(command => command.TargetPosition.HasValue)
|
||||
.WithError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Command for removing an entry from a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="PlaylistEntryId">The unique identifier of the entry to remove, taken from the route.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}")]
|
||||
public record RemovePlaylistEntryCommand(
|
||||
string? PlaylistId,
|
||||
string? PlaylistEntryId
|
||||
) : ICommand;
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to remove an entry from a playlist of the current user.
|
||||
/// </summary>
|
||||
public class RemovePlaylistEntryCommandHandler : ICommandHandler<RemovePlaylistEntryCommand, Result<PlaylistEntryRemovedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<RemovePlaylistEntryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemovePlaylistEntryCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public RemovePlaylistEntryCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IValidator<RemovePlaylistEntryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to remove an entry from a playlist of the current user.
|
||||
/// </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 removed entry with zero repositioned entries, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntryRemovedResponse>> HandleAsync(RemovePlaylistEntryCommand 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 playlistId = Guid.Parse(command.PlaylistId!);
|
||||
Guid playlistEntryId = Guid.Parse(command.PlaylistEntryId!);
|
||||
|
||||
// The row is deleted and the gap is closed in set-based statements, so a playlist of any size is not loaded into memory for one removal.
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
Result<int> removeEntryResult = await _unitOfWork.PlaylistRepository.RemoveEntryAsync(playlistId, userId, playlistEntryId, updatedOnUtc, cancellationToken).ConfigureAwait(false);
|
||||
if (removeEntryResult.IsFailure)
|
||||
return removeEntryResult.Errors;
|
||||
|
||||
return new PlaylistEntryRemovedResponse(
|
||||
playlistId,
|
||||
playlistEntryId,
|
||||
removeEntryResult.Value,
|
||||
updatedOnUtc);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#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.Playlists.Commands.RemovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="RemovePlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
public class RemovePlaylistEntryCommandValidator : AbstractValidator<RemovePlaylistEntryCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemovePlaylistEntryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public RemovePlaylistEntryCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistEntryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistEntryId)
|
||||
.Must(entryId => Guid.TryParse(entryId, out Guid parsedEntryId) && parsedEntryId != Guid.Empty)
|
||||
.When(command => command.PlaylistEntryId is not null && command.PlaylistEntryId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.UpdatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Command for updating the details of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The optional description of the playlist.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}")]
|
||||
public record UpdatePlaylistCommand(
|
||||
string? PlaylistId,
|
||||
string? Name,
|
||||
string? Description
|
||||
) : ICommand;
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Playlists.Commands.UpdatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to update the details of a playlist of the current user.
|
||||
/// </summary>
|
||||
public class UpdatePlaylistCommandHandler : ICommandHandler<UpdatePlaylistCommand, Result<PlaylistDetailsResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<UpdatePlaylistCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaylistCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public UpdatePlaylistCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<UpdatePlaylistCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update the details of a playlist of the current user.
|
||||
/// </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 updated <see cref="PlaylistResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistDetailsResponse>> HandleAsync(UpdatePlaylistCommand 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 identifier is a non-empty Guid before this point.
|
||||
Guid playlistId = Guid.Parse(command.PlaylistId!);
|
||||
|
||||
// The playlist is scoped to the current user by the repository, so a playlist of another user is indistinguishable from a missing one.
|
||||
Result<PlaylistEntity?> getPlaylistResult = await _unitOfWork.PlaylistRepository
|
||||
.GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistNotFound;
|
||||
|
||||
Result<Playlist> toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Playlist playlist = toDomainEntityResult.Value;
|
||||
|
||||
Result<Updated> updateDetailsResult = playlist.UpdateDetails(command.Name!, Optional<string>.FromNullable(command.Description));
|
||||
if (updateDetailsResult.IsFailure)
|
||||
return updateDetailsResult.Errors;
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.PlaylistRepository.UpdateAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
foreach (IDomainEvent domainEvent in playlist.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// A details update only changes the playlist scalars, so the response carries those scalars and the audit timestamp the interceptor actually stored.
|
||||
return new PlaylistDetailsResponse(
|
||||
playlist.Id.Value,
|
||||
playlist.Name,
|
||||
playlist.Description.HasValue ? playlist.Description.Value : null,
|
||||
playlist.Type,
|
||||
getPlaylistResult.Value.UpdatedOnUtc);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#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.Playlists.Commands.UpdatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="UpdatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
public class UpdatePlaylistCommandValidator : AbstractValidator<UpdatePlaylistCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaylistCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public UpdatePlaylistCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.Name)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistNameCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.Name)
|
||||
.MaximumLength(255)
|
||||
.WithError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong);
|
||||
|
||||
RuleFor(command => command.Description)
|
||||
.MaximumLength(2000)
|
||||
.WithError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a playlist of the current user, together with a window of its ordered entries.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="Offset">The zero based position of the first entry to return.</param>
|
||||
/// <param name="Limit">The maximum number of entries to return in this window.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; Offset: {Offset}; Limit: {Limit}")]
|
||||
public record GetPlaylistQuery(
|
||||
string? PlaylistId,
|
||||
int Offset = 0,
|
||||
int Limit = PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE
|
||||
) : IQuery;
|
||||
@@ -0,0 +1,110 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a playlist of the current user, together with its ordered entries.
|
||||
/// </summary>
|
||||
public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<PlaylistResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<GetPlaylistQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetPlaylistQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService, IValidator<GetPlaylistQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a playlist of the current user, together with its ordered entries.
|
||||
/// </summary>
|
||||
/// <param name="query">The query 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 requested <see cref="PlaylistResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistResponse>> HandleAsync(GetPlaylistQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route identifier is a non-empty Guid before this point.
|
||||
Guid playlistId = Guid.Parse(query.PlaylistId!);
|
||||
|
||||
// The playlist is scoped to the current user by the repository, so a playlist of another user is indistinguishable from a missing one.
|
||||
Result<PlaylistDetailsDto?> getPlaylistResult = await _unitOfWork.PlaylistRepository
|
||||
.GetDetailsForUserAsync(playlistId, userId, query.Offset, query.Limit, cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
return DomainErrors.Playlists.PlaylistNotFound;
|
||||
|
||||
// Check the access permissions for each library that the tracks in the playlist might belong to.
|
||||
PlaylistDetailsDto playlist = getPlaylistResult.Value;
|
||||
List<Guid> libraryIds = [.. playlist.Entries
|
||||
.Select(entry => entry.Display?.LibraryId ?? Guid.Empty)
|
||||
.Where(libraryId => libraryId != Guid.Empty)
|
||||
.Distinct()];
|
||||
Dictionary<Guid, bool> libraryAccess = [];
|
||||
foreach (Guid libraryId in libraryIds)
|
||||
{
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
libraryAccess[libraryId] = canAccessLibrary;
|
||||
}
|
||||
|
||||
if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary))
|
||||
{
|
||||
List<PlaylistEntryDto> entries = [];
|
||||
foreach (PlaylistEntryDto entry in playlist.Entries)
|
||||
{
|
||||
Guid libraryId = entry.Display?.LibraryId ?? Guid.Empty;
|
||||
if (libraryId == Guid.Empty || libraryAccess[libraryId])
|
||||
entries.Add(entry);
|
||||
else
|
||||
// Keep the row so its owner can see and remove it, but do not expose display data from a library the user cannot access.
|
||||
entries.Add(entry with { Display = null });
|
||||
}
|
||||
playlist = playlist with { Entries = entries };
|
||||
}
|
||||
|
||||
return playlist.ToResponse();
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#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.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetPlaylistQuery"/>.
|
||||
/// </summary>
|
||||
public class GetPlaylistQueryValidator : AbstractValidator<GetPlaylistQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetPlaylistQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.PlaylistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.PlaylistId)
|
||||
.Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty)
|
||||
.When(query => query.PlaylistId is not null && query.PlaylistId.Length > 0)
|
||||
.WithError(Errors.Playlists.PlaylistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.Offset)
|
||||
.GreaterThanOrEqualTo(0)
|
||||
.WithError(Errors.Playlists.PlaylistEntryWindowOffsetIsInvalid);
|
||||
|
||||
RuleFor(query => query.Limit)
|
||||
.InclusiveBetween(1, PlaylistWindow.MAXIMUM_ENTRY_WINDOW_SIZE)
|
||||
.WithError(Errors.Playlists.PlaylistEntryWindowLimitIsInvalid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// The bounds of one playlist entry read window.
|
||||
/// </summary>
|
||||
public static class PlaylistWindow
|
||||
{
|
||||
/// <summary>
|
||||
/// The default number of entries a single read window returns.
|
||||
/// </summary>
|
||||
public const int DEFAULT_ENTRY_WINDOW_SIZE = 200;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum number of entries a single read window may return.
|
||||
/// </summary>
|
||||
public const int MAXIMUM_ENTRY_WINDOW_SIZE = 1000;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylists;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the playlists of the current user.
|
||||
/// </summary>
|
||||
public record GetPlaylistsQuery : IQuery;
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylists;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the playlists of the current user.
|
||||
/// </summary>
|
||||
public class GetPlaylistsQueryHandler : IQueryHandler<GetPlaylistsQuery, Result<PlaylistSummaryResponse[]>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
public GetPlaylistsQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the playlists of the current user.
|
||||
/// </summary>
|
||||
/// <param name="query">The query 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 playlists of the current user, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistSummaryResponse[]>> HandleAsync(GetPlaylistsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 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;
|
||||
|
||||
Result<IReadOnlyList<PlaylistSummaryDto>> getPlaylistsResult = await _unitOfWork.PlaylistRepository.GetAllForUserAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistsResult.IsFailure)
|
||||
return getPlaylistsResult.Errors;
|
||||
|
||||
return Result.From(getPlaylistsResult.Value.Select(playlist => playlist.ToResponse()).ToArray());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user