mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 19: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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for adding several tracks to a playlist of the current user, in order.
|
||||
/// </summary>
|
||||
/// <param name="TrackIds">The Ids of the tracks to add, in the order they must take. Required.</param>
|
||||
[DebuggerDisplay("TrackCount: {TrackIds.Count}")]
|
||||
public record AddPlaylistEntriesRequest(
|
||||
List<Guid>? TrackIds
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for adding a track to a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track to add. Required.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record AddPlaylistEntryRequest(
|
||||
Guid? TrackId
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to add every track of a music library, an artist or an album to a playlist, resolved on the server.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the music library the scope belongs to. Required.</param>
|
||||
/// <param name="ArtistId">The Id of the artist the scope is limited to. Optional.</param>
|
||||
/// <param name="AlbumId">The Id of the album the scope is limited to. Optional.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")]
|
||||
public record AddPlaylistScopeEntriesRequest(
|
||||
Guid LibraryId,
|
||||
Guid? ArtistId = null,
|
||||
Guid? AlbumId = null
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for creating a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the playlist. Required.</param>
|
||||
/// <param name="Description">The description of the playlist. Optional.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds. Required.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public record CreatePlaylistRequest(
|
||||
string? Name,
|
||||
string? Description,
|
||||
PlaylistType? Type
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a window of the entries of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Offset">The zero based position of the first entry to return. Optional; defaults to 0.</param>
|
||||
/// <param name="Limit">The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.</param>
|
||||
[DebuggerDisplay("Offset: {Offset}; Limit: {Limit}")]
|
||||
public record GetPlaylistRequest(
|
||||
int? Offset,
|
||||
int? Limit
|
||||
);
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for moving one entry of a playlist of the current user to a new position.
|
||||
/// </summary>
|
||||
/// <param name="TargetPosition">The new zero based position of the entry. Required.</param>
|
||||
[DebuggerDisplay("TargetPosition: {TargetPosition}")]
|
||||
public record MovePlaylistEntryRequest(
|
||||
int? TargetPosition
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for updating the details of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the playlist. Required.</param>
|
||||
/// <param name="Description">The description of the playlist. Optional.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public record UpdatePlaylistRequest(
|
||||
string? Name,
|
||||
string? Description
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the editable scalars of a playlist after a details update.
|
||||
/// </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="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}")]
|
||||
public sealed record PlaylistDetailsResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the result of appending several tracks to a playlist, without returning the whole playlist.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist the entries were added to.</param>
|
||||
/// <param name="AddedCount">The number of entries that were appended, including repeated tracks.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; AddedCount: {AddedCount}")]
|
||||
public sealed record PlaylistEntriesAddedResponse(
|
||||
Guid PlaylistId,
|
||||
int AddedCount,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the entry that was appended to a playlist, together with its playlist and the new activity time of the playlist.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist the entry was added to.</param>
|
||||
/// <param name="Entry">The added entry, with the display details of the media item it references.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; Entry: {Entry.Id}")]
|
||||
public sealed record PlaylistEntryAddedResponse(
|
||||
Guid PlaylistId,
|
||||
PlaylistEntryResponse Entry,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the result of moving one entry of a playlist to a new position.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist whose entry was moved.</param>
|
||||
/// <param name="EntryId">The Id of the moved entry.</param>
|
||||
/// <param name="Position">The new zero based position of the entry.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; EntryId: {EntryId}; Position: {Position}")]
|
||||
public sealed record PlaylistEntryMovedResponse(
|
||||
Guid PlaylistId,
|
||||
Guid EntryId,
|
||||
int Position,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the result of removing an entry from a playlist.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist the entry was removed from.</param>
|
||||
/// <param name="RemovedEntryId">The Id of the removed entry.</param>
|
||||
/// <param name="RepositionedCount">Always zero, because sparse order keys need no remaining entries to be repositioned.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; RemovedEntryId: {RemovedEntryId}; RepositionedCount: {RepositionedCount}")]
|
||||
public sealed record PlaylistEntryRemovedResponse(
|
||||
Guid PlaylistId,
|
||||
Guid RemovedEntryId,
|
||||
int RepositionedCount,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for an ordered entry of a playlist.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the entry.</param>
|
||||
/// <param name="MediaItemId">The Id of the media item referenced by the entry.</param>
|
||||
/// <param name="MediaItemType">The kind of media item referenced by the entry.</param>
|
||||
/// <param name="Position">The zero based position of the entry in the playlist.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item, or an empty Guid when the item no longer exists.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, or an empty Guid when the item no longer exists.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, or an empty Guid when the item no longer exists.</param>
|
||||
/// <param name="MediaItemTitle">The title of the media item, or an empty string when the item no longer exists.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, or an empty string when the item no longer exists.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, or an empty string when the item no longer exists.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the media item in seconds, or zero when the item no longer exists.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the collection, if available.</param>
|
||||
[DebuggerDisplay("MediaItemId: {MediaItemId}; MediaItemType: {MediaItemType}; Position: {Position}")]
|
||||
public sealed record PlaylistEntryResponse(
|
||||
Guid Id,
|
||||
Guid MediaItemId,
|
||||
PlaylistMediaItemType MediaItemType,
|
||||
int Position,
|
||||
Guid LibraryId,
|
||||
Guid CollectionId,
|
||||
Guid CreatorId,
|
||||
string MediaItemTitle,
|
||||
string CollectionTitle,
|
||||
string CreatorName,
|
||||
int DurationInSeconds,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for a playlist together with its ordered 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="Entries">The ordered entries of the requested window of the playlist.</param>
|
||||
/// <param name="EntryCount">The number of entries the playlist holds, even when only a window of them is returned.</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>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}; Window: {Entries.Count}")]
|
||||
public sealed record PlaylistResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
IReadOnlyList<PlaylistEntryResponse> Entries,
|
||||
int EntryCount,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response 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>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}")]
|
||||
public sealed record PlaylistSummaryResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
int EntryCount,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,92 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="PlaylistEntity"/> entity.
|
||||
/// </summary>
|
||||
public class PlaylistConfiguration : IEntityTypeConfiguration<PlaylistEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="PlaylistEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<PlaylistEntity> builder)
|
||||
{
|
||||
builder.ToTable("Playlists");
|
||||
builder.HasKey(playlist => playlist.Id);
|
||||
builder.Property(playlist => playlist.Id)
|
||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
||||
.HasColumnOrder(0);
|
||||
|
||||
// A playlist belongs to the user that created it, and it is removed with that user.
|
||||
builder.HasOne<UserEntity>()
|
||||
.WithMany()
|
||||
.HasForeignKey(playlist => playlist.UserId)
|
||||
.IsRequired()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.Property(playlist => playlist.UserId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(playlist => playlist.Name)
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnOrder(2);
|
||||
|
||||
builder.Property(playlist => playlist.Description)
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(playlist => playlist.Type)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// Audit.
|
||||
builder.Property(playlist => playlist.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(playlist => playlist.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(playlist => playlist.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(7);
|
||||
|
||||
builder.Property(playlist => playlist.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(8);
|
||||
|
||||
// The entry count is maintained by the set-based entry operations, so a window read never counts the entries of the whole playlist.
|
||||
builder.Property(playlist => playlist.EntryCount)
|
||||
.IsRequired()
|
||||
.HasDefaultValue(0)
|
||||
.HasColumnOrder(10);
|
||||
|
||||
// The concurrency token is incremented by every details edit and by every set-based entry operation, so a concurrent writer is
|
||||
// detected instead of silently overwriting the ordering work of another request.
|
||||
builder.Property(playlist => playlist.Version)
|
||||
.IsConcurrencyToken()
|
||||
.HasDefaultValue(0L)
|
||||
.HasColumnOrder(9);
|
||||
|
||||
// The entries of the playlist are owned by the playlist: they are removed with it, and they are never referenced from elsewhere.
|
||||
builder.HasMany(playlist => playlist.Entries)
|
||||
.WithOne()
|
||||
.HasForeignKey(entry => entry.PlaylistId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
// Enables the list of the playlists of a user in the order of their most recent activity.
|
||||
builder.HasIndex(playlist => new { playlist.UserId, playlist.UpdatedOnUtc });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="PlaylistEntryEntity"/> entity.
|
||||
/// </summary>
|
||||
public class PlaylistEntryConfiguration : IEntityTypeConfiguration<PlaylistEntryEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="PlaylistEntryEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<PlaylistEntryEntity> builder)
|
||||
{
|
||||
builder.ToTable("PlaylistEntries");
|
||||
builder.HasKey(entry => entry.Id);
|
||||
builder.Property(entry => entry.Id)
|
||||
.ValueGeneratedNever()
|
||||
.HasColumnOrder(0);
|
||||
|
||||
builder.Property(entry => entry.PlaylistId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(entry => entry.MediaItemId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
|
||||
builder.Property(entry => entry.MediaItemType)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(entry => entry.Position)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// Audit.
|
||||
builder.Property(entry => entry.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(entry => entry.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(entry => entry.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(7);
|
||||
|
||||
builder.Property(entry => entry.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(8);
|
||||
|
||||
// The referenced media item is kept by Id only, without a foreign key, so a playlist entry survives the deletion of the item it
|
||||
// references and its owner can still see and remove the dangling entry.
|
||||
// The unique index makes the storage medium the owner of the ordering invariant: a duplicate position is rejected even if an operation bypasses the repository.
|
||||
builder.HasIndex(entry => new { entry.PlaylistId, entry.Position })
|
||||
.IsUnique();
|
||||
|
||||
// Enables finding the playlists that reference a media item, for example when a track is deleted.
|
||||
builder.HasIndex(entry => entry.MediaItemId);
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,21 @@ namespace Lumina.DataAccess.Common.Dapper;
|
||||
/// Maps <see cref="Guid"/> values to and from the TEXT representation used by the SQLite provider.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The SQLite provider stores <see cref="Guid"/> columns as TEXT, and Dapper falls back to Convert.ChangeType when materializing such
|
||||
/// columns into <see cref="Guid"/> properties. <see cref="Guid"/> has no string <see cref="TypeConverter"/>, so that conversion throws
|
||||
/// an <see cref="InvalidCastException"/>; this handler performs the conversion explicitly instead.
|
||||
/// The SQLite provider stores <see cref="Guid"/> columns as upper case TEXT. Dapper falls back to Convert.ChangeType when materializing
|
||||
/// such columns into <see cref="Guid"/> properties. <see cref="Guid"/> has no string <see cref="TypeConverter"/>, so that conversion
|
||||
/// throws an <see cref="InvalidCastException"/>; this handler performs the conversion explicitly instead, and writes the same upper case
|
||||
/// representation so raw key comparisons and foreign keys match the rows created by Entity Framework.
|
||||
/// </remarks>
|
||||
internal sealed class SqliteGuidTypeHandler : SqlMapper.TypeHandler<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets the parameter value to the TEXT representation of the <see cref="Guid"/> value, keeping writes consistent with reads.
|
||||
/// Sets the parameter value to the upper case TEXT representation the SQLite provider uses for <see cref="Guid"/> columns.
|
||||
/// </summary>
|
||||
/// <param name="parameter">The database parameter to set.</param>
|
||||
/// <param name="value">The <see cref="Guid"/> value to store.</param>
|
||||
public override void SetValue(IDbDataParameter parameter, Guid value)
|
||||
{
|
||||
parameter.Value = value.ToString();
|
||||
parameter.Value = value.ToString().ToUpperInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+3673
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsPlaylists : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Playlists",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Name = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
|
||||
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
|
||||
Type = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true),
|
||||
Version = table.Column<long>(type: "INTEGER", nullable: false, defaultValue: 0L),
|
||||
EntryCount = table.Column<int>(type: "INTEGER", nullable: false, defaultValue: 0)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Playlists", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Playlists_Users_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "PlaylistEntries",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
PlaylistId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
MediaItemId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
MediaItemType = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
|
||||
Position = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_PlaylistEntries", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_PlaylistEntries_Playlists_PlaylistId",
|
||||
column: x => x.PlaylistId,
|
||||
principalTable: "Playlists",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PlaylistEntries_MediaItemId",
|
||||
table: "PlaylistEntries",
|
||||
column: "MediaItemId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PlaylistEntries_PlaylistId_Position",
|
||||
table: "PlaylistEntries",
|
||||
columns: new[] { "PlaylistId", "Position" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Playlists_UserId_UpdatedOnUtc",
|
||||
table: "Playlists",
|
||||
columns: new[] { "UserId", "UpdatedOnUtc" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "PlaylistEntries");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Playlists");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1904,6 +1904,119 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.ToTable("Books", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<int>("EntryCount")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(0)
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<long>("Version")
|
||||
.IsConcurrencyToken()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(0L)
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId", "UpdatedOnUtc");
|
||||
|
||||
b.ToTable("Playlists", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("MediaItemType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("PlaylistId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<long>("Position")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("MediaItemId");
|
||||
|
||||
b.HasIndex("PlaylistId", "Position")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PlaylistEntries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -3429,6 +3542,24 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.Navigation("Ratings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null)
|
||||
.WithMany("Entries")
|
||||
.HasForeignKey("PlaylistId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null)
|
||||
@@ -3518,6 +3649,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.Navigation("Contributors");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b =>
|
||||
{
|
||||
b.Navigation("Entries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Navigation("Libraries");
|
||||
|
||||
@@ -16,8 +16,9 @@ internal static class CollectionReconciler
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Existing items that are absent from the desired set are removed, desired items that are absent are added, and matched items are left untouched, unless
|
||||
/// <paramref name="shouldReplace"/> reports that their non-key values changed, in which case only that item is replaced. Because the tracked instances are
|
||||
/// never rebuilt as a whole, the rows that did not change keep their identity and their audit columns.
|
||||
/// <paramref name="shouldReplace"/> reports that their non-key values changed, in which case only that item is replaced, or <paramref name="applyMatched"/> is
|
||||
/// provided, in which case the matched tracked item is updated in place. Because the tracked instances are never rebuilt as a whole, the rows that did not change
|
||||
/// keep their identity and their audit columns.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TExisting">The type of the tracked items.</typeparam>
|
||||
/// <typeparam name="TIncoming">The type of the desired items.</typeparam>
|
||||
@@ -28,13 +29,15 @@ internal static class CollectionReconciler
|
||||
/// <param name="incomingKeySelector">Selects the matching key of a desired item.</param>
|
||||
/// <param name="shouldReplace">Determines whether a matched tracked item must be replaced, because a non-key value changed.</param>
|
||||
/// <param name="createNew">Creates the entity used for a desired item that is not matched by any tracked item.</param>
|
||||
/// <param name="applyMatched">Applies the incoming non-key values onto a matched tracked item, when the caller updates matched items in place instead of replacing them.</param>
|
||||
public static void Reconcile<TExisting, TIncoming, TKey>(
|
||||
ICollection<TExisting> existingItems,
|
||||
IEnumerable<TIncoming> incomingItems,
|
||||
Func<TExisting, TKey> existingKeySelector,
|
||||
Func<TIncoming, TKey> incomingKeySelector,
|
||||
Func<TExisting, TIncoming, bool> shouldReplace,
|
||||
Func<TIncoming, TExisting> createNew)
|
||||
Func<TIncoming, TExisting> createNew,
|
||||
Action<TExisting, TIncoming>? applyMatched = null)
|
||||
where TExisting : class
|
||||
where TKey : notnull
|
||||
{
|
||||
@@ -65,6 +68,10 @@ internal static class CollectionReconciler
|
||||
existingItems.Add(replacementItem);
|
||||
existingByKey[incomingKey] = replacementItem;
|
||||
}
|
||||
else if (applyMatched is not null)
|
||||
// The caller updates the matched instance in place. This keeps the tracked instance and its key, which is the only
|
||||
// safe option when the key is user-assigned and the tracked instance is still in the change tracker.
|
||||
applyMatched(matchedItem, incomingItem);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -47,7 +47,13 @@ internal static class EditableValuesCopier
|
||||
{
|
||||
if (excludedProperties.Contains(property.Name))
|
||||
continue;
|
||||
trackedEntry.Property(property.Name).CurrentValue = incomingEntry.Property(property.Name).CurrentValue;
|
||||
PropertyEntry trackedProperty = trackedEntry.Property(property.Name);
|
||||
object? incomingValue = incomingEntry.Property(property.Name).CurrentValue;
|
||||
// Only an actual change is assigned and marked modified. Assigning every value unconditionally, or relying on change detection that has not run yet, would make the caller unable to tell a no-op save from a real edit.
|
||||
if (Equals(trackedProperty.CurrentValue, incomingValue))
|
||||
continue;
|
||||
trackedProperty.CurrentValue = incomingValue;
|
||||
trackedProperty.IsModified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,16 +226,14 @@ internal sealed class BookRepository : IBookRepository
|
||||
// Apply sorting based on the specified sortBy and sortOrder parameters.
|
||||
booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
|
||||
IQueryable<BookLiteRow> liteRowsQuery = booksQuery.Select(book => new BookLiteRow
|
||||
{
|
||||
Id = book.Id,
|
||||
Title = book.Title,
|
||||
ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear,
|
||||
CoverPath = book.Artwork
|
||||
IQueryable<BookLiteRow> liteRowsQuery = booksQuery.Select(book => new BookLiteRow(
|
||||
book.Id,
|
||||
book.Title,
|
||||
book.ReReleaseYear ?? book.OriginalReleaseYear,
|
||||
book.Artwork
|
||||
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()
|
||||
});
|
||||
.FirstOrDefault()));
|
||||
|
||||
// If no pagination was requested, return all the books of the library.
|
||||
if (paginationData is null)
|
||||
|
||||
@@ -102,7 +102,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
DateTime nowUtc = DateTime.UtcNow;
|
||||
object parameters = new { libraryId, scanId, userId, nowUtc };
|
||||
|
||||
// the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as lowercase hex (hex(randomblob(16))), which the storage layer parses as a Guid;
|
||||
// the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as upper case hex (hex(randomblob(16))), which the storage layer parses as a Guid;
|
||||
// generating the Ids in code would defeat the purpose of these single statement bulk inserts
|
||||
|
||||
// add an audit entry for every media library scan snapshot item that is no longer present in the current scan, meaning it was deleted from the storage medium
|
||||
|
||||
@@ -275,25 +275,23 @@ internal sealed class AlbumRepository : IAlbumRepository
|
||||
public async Task<Result<PaginatedResultDto<AlbumLiteRow>>> GetAlbumsLiteByArtistIdAsync(Guid artistId, PaginationDataDto? paginationData, CancellationToken cancellationToken)
|
||||
{
|
||||
// The lightweight read models are always retrieved without tracking, because they are never modified by the caller.
|
||||
// The release year and the release types are exposed so that the clients can group and order the releases of an artist.
|
||||
// The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album.
|
||||
IQueryable<AlbumLiteRow> liteRowsQuery = _luminaDbContext.Albums
|
||||
.AsNoTracking()
|
||||
.Where(album => album.ArtistId == artistId)
|
||||
.OrderBy(album => album.Title)
|
||||
.ThenBy(album => album.Id)
|
||||
.Select(album => new AlbumLiteRow
|
||||
{
|
||||
Id = album.Id,
|
||||
Title = album.Title,
|
||||
TotalTracks = album.TotalTracks,
|
||||
// The release year and the release types are exposed so that the clients can group and order the releases of an artist.
|
||||
ReleaseYear = album.ReReleaseYear ?? album.OriginalReleaseYear,
|
||||
ReleaseTypes = album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList(),
|
||||
// The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album.
|
||||
CoverPath = _luminaDbContext.MusicArtwork
|
||||
.Select(album => new AlbumLiteRow(
|
||||
album.Id,
|
||||
album.Title,
|
||||
album.TotalTracks,
|
||||
_luminaDbContext.MusicArtwork
|
||||
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()
|
||||
});
|
||||
.FirstOrDefault(),
|
||||
album.ReReleaseYear ?? album.OriginalReleaseYear,
|
||||
album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList()));
|
||||
|
||||
if (paginationData is null)
|
||||
{
|
||||
|
||||
@@ -565,17 +565,15 @@ internal sealed class ArtistRepository : IArtistRepository
|
||||
if (filterSpecification is not null)
|
||||
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
|
||||
|
||||
// The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist.
|
||||
IQueryable<ArtistLiteRow> liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker)
|
||||
.Select(artist => new ArtistLiteRow
|
||||
{
|
||||
Id = artist.Id,
|
||||
Name = artist.Name,
|
||||
// The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist.
|
||||
CoverPath = _luminaDbContext.MusicArtwork
|
||||
.Select(artist => new ArtistLiteRow(
|
||||
artist.Id,
|
||||
artist.Name,
|
||||
_luminaDbContext.MusicArtwork
|
||||
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()
|
||||
});
|
||||
.FirstOrDefault()));
|
||||
|
||||
// If no pagination was requested, return all the artists of the library.
|
||||
if (paginationData is null)
|
||||
|
||||
@@ -266,14 +266,12 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
.OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1
|
||||
.ThenBy(track => track.TrackNumber)
|
||||
.ThenBy(track => track.Id)
|
||||
.Select(track => new TrackLiteRow
|
||||
{
|
||||
Id = track.Id,
|
||||
Title = track.Title,
|
||||
TrackNumber = track.TrackNumber,
|
||||
DiscNumber = track.DiscNumber,
|
||||
DurationInSeconds = track.DurationInSeconds
|
||||
});
|
||||
.Select(track => new TrackLiteRow(
|
||||
track.Id,
|
||||
track.Title,
|
||||
track.TrackNumber,
|
||||
track.DiscNumber,
|
||||
track.DurationInSeconds));
|
||||
|
||||
if (paginationData is null)
|
||||
{
|
||||
@@ -333,24 +331,21 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
if (excludedIds.Length > 0)
|
||||
query = query.Where(track => !excludedIds.Contains(track.Id));
|
||||
|
||||
// SQLite randomizes the rows before the limit, so the result is a uniform sample of every matching track.
|
||||
// SQLite randomizes the rows before the limit, so the result is a uniform sample of every matching track. The cover is the cover artwork stored for the album, exactly like the album cards expose it.
|
||||
return await query
|
||||
.OrderBy(_ => EF.Functions.Random())
|
||||
.Take(count)
|
||||
.Select(track => new ShuffleTrackRowDto
|
||||
{
|
||||
TrackId = track.Id,
|
||||
Title = track.Title,
|
||||
DurationInSeconds = track.DurationInSeconds,
|
||||
AlbumId = track.AlbumId,
|
||||
AlbumTitle = track.Album!.Title,
|
||||
ArtistId = track.Album!.ArtistId,
|
||||
// The cover is the cover artwork stored for the album, exactly like the album cards expose it.
|
||||
CoverPath = _luminaDbContext.MusicArtwork
|
||||
.Select(track => new ShuffleTrackRowDto(
|
||||
track.Id,
|
||||
track.Title,
|
||||
track.DurationInSeconds,
|
||||
track.AlbumId,
|
||||
track.Album!.Title,
|
||||
track.Album!.ArtistId,
|
||||
_luminaDbContext.MusicArtwork
|
||||
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == track.AlbumId && artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()
|
||||
})
|
||||
.FirstOrDefault()))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -529,4 +524,54 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public async Task<Result<TrackAccessSummaryDto>> GetAccessInfoByIdsAsync(IReadOnlyCollection<Guid> trackIds, CancellationToken cancellationToken)
|
||||
{
|
||||
if (trackIds.Count == 0)
|
||||
return Result.From(new TrackAccessSummaryDto(0, []));
|
||||
|
||||
// The chunk is deliberately large: it stays below the SQLite parameter limit while keeping a 100k queue to a handful of sequential round trips.
|
||||
// The projection groups by library, so the storage medium returns one row per library instead of one row per requested track.
|
||||
const int LOOKUP_CHUNK_SIZE = 20_000;
|
||||
int trackCount = 0;
|
||||
HashSet<Guid> libraryIds = [];
|
||||
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
{
|
||||
List<TrackLibraryCount> chunkCounts = await _luminaDbContext.Tracks
|
||||
.AsNoTracking()
|
||||
.Where(track => chunk.Contains(track.Id))
|
||||
.GroupBy(track => track.LibraryId)
|
||||
.Select(group => new TrackLibraryCount
|
||||
{
|
||||
LibraryId = group.Key,
|
||||
TrackCount = group.Count()
|
||||
})
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
trackCount += chunkCounts.Sum(count => count.TrackCount);
|
||||
libraryIds.UnionWith(chunkCounts.Select(count => count.LibraryId));
|
||||
}
|
||||
return Result.From(new TrackAccessSummaryDto(trackCount, [.. libraryIds]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The number of requested tracks that exist in one library.
|
||||
/// </summary>
|
||||
private sealed class TrackLibraryCount
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the library.
|
||||
/// </summary>
|
||||
public Guid LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of requested tracks in the library.
|
||||
/// </summary>
|
||||
public int TrackCount { get; set; }
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
@@ -50,6 +51,8 @@ public class LuminaDbContext : DbContext
|
||||
public virtual DbSet<ScheduledJobExecutionEntity> ScheduledJobExecutions { get; set; } = null!;
|
||||
public virtual DbSet<SchedulerDisplayPreferencesEntity> SchedulerDisplayPreferences { get; set; } = null!;
|
||||
public virtual DbSet<MusicPlayRecordEntity> MusicPlayRecords { get; set; } = null!;
|
||||
public virtual DbSet<PlaylistEntity> Playlists { get; set; } = null!;
|
||||
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
|
||||
@@ -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;
|
||||
@@ -15,6 +16,7 @@ using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaContributors;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Playlists;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
using Lumina.DataAccess.Core.Repositories.Themes;
|
||||
@@ -65,6 +67,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private IUserRepository? _userRepository;
|
||||
private IUserSettingsRepository? _userSettingsRepository;
|
||||
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
|
||||
private IPlaylistRepository? _playlistRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the permission repository.
|
||||
@@ -387,6 +390,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist repository.
|
||||
/// </summary>
|
||||
public IPlaylistRepository PlaylistRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_playlistRepository ??= new PlaylistRepository(_luminaDbContext);
|
||||
return _playlistRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the kinds of media item an ordered playlist entry can reference.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum PlaylistMediaItemType
|
||||
{
|
||||
/// <summary>
|
||||
/// An entry that references a music track.
|
||||
/// </summary>
|
||||
MusicTrack,
|
||||
|
||||
/// <summary>
|
||||
/// An entry that references a video file.
|
||||
/// </summary>
|
||||
VideoFile,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the kinds of media a playlist can hold.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum PlaylistType
|
||||
{
|
||||
/// <summary>
|
||||
/// A playlist whose ordered entries reference music tracks.
|
||||
/// </summary>
|
||||
Music,
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// Playlist error types.
|
||||
/// </summary>
|
||||
public static partial class Errors
|
||||
{
|
||||
public static class Playlists
|
||||
{
|
||||
public static Error PlaylistNotFound => Error.NotFound(description: nameof(PlaylistNotFound));
|
||||
public static Error PlaylistAlreadyExists => Error.Conflict(description: nameof(PlaylistAlreadyExists));
|
||||
public static Error PlaylistIdCannotBeEmpty => Error.Validation(description: nameof(PlaylistIdCannotBeEmpty));
|
||||
public static Error PlaylistEntryIdCannotBeEmpty => Error.Validation(description: nameof(PlaylistEntryIdCannotBeEmpty));
|
||||
public static Error PlaylistNameCannotBeEmpty => Error.Validation(description: nameof(PlaylistNameCannotBeEmpty));
|
||||
public static Error PlaylistNameMustBeMaximum255CharactersLong => Error.Validation(description: nameof(PlaylistNameMustBeMaximum255CharactersLong));
|
||||
public static Error PlaylistDescriptionMustBeMaximum2000CharactersLong => Error.Validation(description: nameof(PlaylistDescriptionMustBeMaximum2000CharactersLong));
|
||||
public static Error PlaylistTypeIsInvalid => Error.Validation(description: nameof(PlaylistTypeIsInvalid));
|
||||
public static Error PlaylistDoesNotAcceptMediaItems => Error.Forbidden(description: nameof(PlaylistDoesNotAcceptMediaItems));
|
||||
public static Error PlaylistEntryNotFound => Error.NotFound(description: nameof(PlaylistEntryNotFound));
|
||||
public static Error PlaylistEntryPositionsAreInvalid => Error.Validation(description: nameof(PlaylistEntryPositionsAreInvalid));
|
||||
public static Error PlaylistMoveTargetPositionIsInvalid => Error.Validation(description: nameof(PlaylistMoveTargetPositionIsInvalid));
|
||||
public static Error PlaylistEntryWindowOffsetIsInvalid => Error.Validation(description: nameof(PlaylistEntryWindowOffsetIsInvalid));
|
||||
public static Error PlaylistEntryWindowLimitIsInvalid => Error.Validation(description: nameof(PlaylistEntryWindowLimitIsInvalid));
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a media item, duplicated from the media library bounded contexts to keep the cross bounded context references decoupled.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The kind of media item is carried by the playlist entry and by the playlist type, so this identifier stays generic across music tracks and video files.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay("{Value}")]
|
||||
public sealed class MediaItemId : EntityId<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaItemId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The value representing this object.</param>
|
||||
private MediaItemId(Guid value) : base(value)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="MediaItemId"/> class.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
|
||||
public static MediaItemId CreateUnique()
|
||||
{
|
||||
return new MediaItemId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="MediaItemId"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The value used to create the <see cref="MediaItemId"/> instance.</param>
|
||||
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
|
||||
public static MediaItemId Create(Guid value)
|
||||
{
|
||||
return new MediaItemId(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of items that define equality of the object.
|
||||
/// </summary>
|
||||
/// <returns>A list of items defining the equality.</returns>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Value;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Value}")]
|
||||
public sealed class UserId : EntityId<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The value representing this object.</param>
|
||||
private UserId(Guid value) : base(value)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserId"/> class.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="UserId"/> instance.</returns>
|
||||
public static UserId CreateUnique()
|
||||
{
|
||||
return new UserId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserId"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The value used to create the <see cref="UserId"/> instance.</param>
|
||||
/// <returns>The created <see cref="UserId"/> instance.</returns>
|
||||
public static UserId Create(Guid value)
|
||||
{
|
||||
return new UserId(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of items that define equality of the object.
|
||||
/// </summary>
|
||||
/// <returns>A list of items defining the equality.</returns>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Value;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Entity for an ordered entry of a playlist.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id.Value}; MediaItemId: {MediaItemId.Value}; MediaItemType: {MediaItemType}; Position: {Position}")]
|
||||
public sealed class PlaylistEntry : Entity<PlaylistEntryId>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the media item referenced by the entry.
|
||||
/// </summary>
|
||||
public MediaItemId MediaItemId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the kind of media item referenced by the entry.
|
||||
/// </summary>
|
||||
public PlaylistMediaItemType MediaItemType { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sparse order key of the entry in the ordered entries of the playlist.
|
||||
/// </summary>
|
||||
public long Position { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistEntry"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of the entry.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item referenced by the entry.</param>
|
||||
/// <param name="mediaItemType">The kind of media item referenced by the entry.</param>
|
||||
/// <param name="position">The sparse order key of the entry in the ordered entries of the playlist.</param>
|
||||
private PlaylistEntry(PlaylistEntryId id, MediaItemId mediaItemId, PlaylistMediaItemType mediaItemType, long position) : base(id)
|
||||
{
|
||||
Id = id;
|
||||
MediaItemId = mediaItemId;
|
||||
MediaItemType = mediaItemType;
|
||||
Position = position;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="PlaylistEntry"/> class, with a pre-existing <paramref name="id"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of the entry.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item referenced by the entry.</param>
|
||||
/// <param name="mediaItemType">The kind of media item referenced by the entry.</param>
|
||||
/// <param name="position">The sparse order key of the entry in the ordered entries of the playlist.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="PlaylistEntry"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<PlaylistEntry> Create(PlaylistEntryId id, MediaItemId mediaItemId, PlaylistMediaItemType mediaItemType, long position)
|
||||
{
|
||||
return new PlaylistEntry(id, mediaItemId, mediaItemType, position);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event raised when a playlist is created.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist.</param>
|
||||
/// <param name="UserId">The unique identifier of the user that owns the playlist.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; UserId: {UserId.Value}")]
|
||||
public record PlaylistCreatedDomainEvent(
|
||||
Guid Id,
|
||||
PlaylistId PlaylistId,
|
||||
UserId UserId,
|
||||
string Name,
|
||||
PlaylistType Type,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event raised when a playlist is deleted.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist.</param>
|
||||
/// <param name="UserId">The unique identifier of the user that owned the playlist.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; UserId: {UserId.Value}")]
|
||||
public record PlaylistDeletedDomainEvent(
|
||||
Guid Id,
|
||||
PlaylistId PlaylistId,
|
||||
UserId UserId,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event raised when the details of a playlist are updated.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist.</param>
|
||||
/// <param name="UserId">The unique identifier of the user that owns the playlist.</param>
|
||||
/// <param name="Name">The new name of the playlist.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; Name: {Name}")]
|
||||
public record PlaylistDetailsUpdatedDomainEvent(
|
||||
Guid Id,
|
||||
PlaylistId PlaylistId,
|
||||
UserId UserId,
|
||||
string Name,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Aggregate root for a playlist.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id.Value}; Name: {Name}; Type: {Type}")]
|
||||
public sealed class Playlist : AggregateRoot<PlaylistId>
|
||||
{
|
||||
private readonly List<PlaylistEntry> _entries;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the object representing the unique identifier of the user that owns the playlist.
|
||||
/// </summary>
|
||||
public UserId UserId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the playlist.
|
||||
/// </summary>
|
||||
public string Name { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the description of the playlist, if applicable.
|
||||
/// </summary>
|
||||
public Optional<string> Description { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the kind of media the playlist holds.
|
||||
/// </summary>
|
||||
public PlaylistType Type { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the playlist was marked for deletion in this unit of work.
|
||||
/// </summary>
|
||||
public bool IsDeleted { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ordered entries of the playlist.
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<PlaylistEntry> Entries => _entries.AsReadOnly();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Playlist"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of the playlist.</param>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns the playlist.</param>
|
||||
/// <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>
|
||||
/// <param name="entries">The ordered 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.</param>
|
||||
private Playlist(
|
||||
PlaylistId id,
|
||||
UserId userId,
|
||||
string name,
|
||||
Optional<string> description,
|
||||
PlaylistType type,
|
||||
List<PlaylistEntry> entries,
|
||||
DateTime createdOnUtc,
|
||||
Optional<DateTime> updatedOnUtc) : base(id)
|
||||
{
|
||||
Id = id;
|
||||
UserId = userId;
|
||||
Name = name;
|
||||
Description = description;
|
||||
Type = type;
|
||||
_entries = entries;
|
||||
CreatedOnUtc = createdOnUtc;
|
||||
UpdatedOnUtc = updatedOnUtc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new playlist for the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns the playlist.</param>
|
||||
/// <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>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Playlist"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Playlist> Create(UserId userId, string name, Optional<string> description, PlaylistType type)
|
||||
{
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
Playlist playlist = new(
|
||||
PlaylistId.CreateUnique(),
|
||||
userId,
|
||||
name,
|
||||
description,
|
||||
type,
|
||||
[],
|
||||
occurredOnUtc,
|
||||
Optional<DateTime>.None());
|
||||
|
||||
playlist._domainEvents.Add(new PlaylistCreatedDomainEvent(
|
||||
Guid.NewGuid(),
|
||||
playlist.Id,
|
||||
userId,
|
||||
name,
|
||||
type,
|
||||
occurredOnUtc));
|
||||
return playlist;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="Playlist"/> class, with pre-existing data.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of the playlist.</param>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns the playlist.</param>
|
||||
/// <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>
|
||||
/// <param name="entries">The ordered 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.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Playlist"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Playlist> Create(
|
||||
PlaylistId id,
|
||||
UserId userId,
|
||||
string name,
|
||||
Optional<string> description,
|
||||
PlaylistType type,
|
||||
List<PlaylistEntry> entries,
|
||||
DateTime createdOnUtc,
|
||||
Optional<DateTime> updatedOnUtc)
|
||||
{
|
||||
if (entries.Any(entry => !CanContain(type, entry.MediaItemType)))
|
||||
return Errors.Playlists.PlaylistDoesNotAcceptMediaItems;
|
||||
// The positions are sparse order keys, so they must be unique. The gaps between them are intentional and are not a reason to reject an otherwise readable playlist.
|
||||
if (!ArePositionsValid(entries))
|
||||
return Errors.Playlists.PlaylistEntryPositionsAreInvalid;
|
||||
|
||||
return new Playlist(id, userId, name, description, type, entries, createdOnUtc, updatedOnUtc);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the name and the description of the playlist, without touching its entries.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the playlist.</param>
|
||||
/// <param name="description">The optional description of the playlist.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
|
||||
public Result<Updated> UpdateDetails(string name, Optional<string> description)
|
||||
{
|
||||
bool hasChanged = Name != name
|
||||
|| Description.HasValue != description.HasValue
|
||||
|| (Description.HasValue && description.HasValue && Description.Value != description.Value);
|
||||
if (!hasChanged)
|
||||
return Result.Updated;
|
||||
|
||||
Name = name;
|
||||
Description = description;
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
_domainEvents.Add(new PlaylistDetailsUpdatedDomainEvent(
|
||||
Guid.NewGuid(),
|
||||
Id,
|
||||
UserId,
|
||||
name,
|
||||
occurredOnUtc));
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the playlist as deleted, raising the domain event that announces its deletion.
|
||||
/// </summary>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Deleted> Delete()
|
||||
{
|
||||
if (IsDeleted)
|
||||
return Result.Deleted;
|
||||
|
||||
// Earlier events become irrelevant once the playlist is deleted.
|
||||
_domainEvents.Clear();
|
||||
IsDeleted = true;
|
||||
_domainEvents.Add(new PlaylistDeletedDomainEvent(
|
||||
Guid.NewGuid(),
|
||||
Id,
|
||||
UserId,
|
||||
DateTime.UtcNow));
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a playlist of <paramref name="playlistType"/> can contain <paramref name="mediaItemType"/>.
|
||||
/// </summary>
|
||||
/// <param name="playlistType">The kind of media the playlist holds.</param>
|
||||
/// <param name="mediaItemType">The kind of media item referenced by an entry.</param>
|
||||
/// <returns><see langword="true"/> if the media item type belongs to the playlist type, <see langword="false"/> otherwise.</returns>
|
||||
public static bool CanContain(PlaylistType playlistType, PlaylistMediaItemType mediaItemType)
|
||||
{
|
||||
return playlistType switch
|
||||
{
|
||||
PlaylistType.Music => mediaItemType == PlaylistMediaItemType.MusicTrack,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the positions of <paramref name="entries"/> are unique.
|
||||
/// </summary>
|
||||
/// <param name="entries">The entries whose positions are checked.</param>
|
||||
/// <returns><see langword="true"/> if the positions are unique, <see langword="false"/> otherwise.</returns>
|
||||
private static bool ArePositionsValid(IReadOnlyCollection<PlaylistEntry> entries)
|
||||
{
|
||||
// The storage enforces unique order keys with a unique index, and the sparse keys are allowed to have wide gaps.
|
||||
HashSet<long> positions = [];
|
||||
foreach (PlaylistEntry entry in entries)
|
||||
if (!positions.Add(entry.Position))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 296 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user